1. Conditionally add attributes to objects
We can use the expansion symbol (...) to conditionally and quickly add properties to JS objects.
const condition = true; const person = { id: 1, name: 'John Doe', ...(condition && { age: 16 }), };
If the value of each operand is true, then && Operator returns the last evaluated expression. Therefore, an object {age: 16} is returned and extended as part of the person object.
If condition by false, JavaScript will do such things:
const person = { id: 1, name: 'songshu', ...(false), }; // Expanding 'false' has no effect on the object console.log(person); // { id: 1, name: 'John Doe' }
2. Check whether the attribute exists in the object
have access to in Keyword to check whether a property exists in the JavaScript object.
const person = { name: 'songshu', salary: 1000 }; console.log('salary' in person); // true console.log('age' in person); // false
3. Dynamic attribute name in object
Setting object properties using dynamic keys is simple. Just use ['key name '] to add attributes:
const dynamic = 'flavour'; var item = { name: 'songshu', [dynamic]: 'Chocolates' } console.log(item); // {Name: 'Songshu', flavor: 'chocolate'}
The same technique can be used to reference object properties using dynamic keys:
const keyName = 'name'; console.log(item[keyName]); // returns 'songshu'
4. Use dynamic keys to deconstruct objects
We know that in object deconstruction, you can use : To rename the deconstructed attribute. However, do you know that when the key name is dynamic, you can also deconstruct the properties of the object?
const person = { id: 1, name: 'songshu' }; const { name: personName } = person; console.log(personName); // 'songshu'
Now we use dynamic keys to deconstruct attributes:
const templates = { 'hello': 'Hello there', 'bye': 'Good bye' }; const templateName = 'bye'; const { [templateName]: template } = templates; console.log(template); // Good bye
5. Null value consolidation ?? Operator
When we want to check whether a variable is null or undefined When,?? Operators are useful. When its left operand is null or When undefined, it returns the operand on the right, otherwise it returns the operand on the left.
const foo = null ?? 'Hello'; console.log(foo); // 'Hello' const bar = 'Not null' ?? 'Hello'; console.log(bar); // 'Not null' const baz = 0 ?? 'Hello'; console.log(baz); // 0
In the third example, return 0, because even 0 It is considered false in JS, but it is not null or undefined. You may think we can use the 𞓜 operator, but there is a difference between the two
You may think we can use it here || Operator, but there is a difference between the two.
const cannotBeZero = 0 || 5; console.log(cannotBeZero); // 5 const canBeZero = 0 ?? 5; console.log(canBeZero); // 0
6. Optional chain ?.
Do we often encounter such mistakes: TypeError: Cannot read property ‘foo’ of null. This is an annoying problem for every developer. The introduction of optional chain is to solve this problem. Let's see:
const book = { id:1, title: 'Title', author: null }; // Usually, you do console.log(book.author.age) // throws error console.log(book.author && book.author.age); // null // Use optional chain console.log(book.author?.age); // undefined // Or depth selectable chain console.log(book.author?.address?.city); // undefined
You can also use the following functions to select chains:
const person = { firstName: 'front end', lastName: 'songshu', printName: function () { return `${this.firstName} ${this.lastName}`; }, }; console.log(person.printName()); // 'front end songshu' console.log(persone.doesNotExist?.()); // undefined
7. Use !! Operator
!! Operators can be used to quickly convert the result of an expression to a Boolean value (true or false):
const greeting = 'Hello there!'; console.log(!!greeting) // true const noGreeting = ''; console.log(!!noGreeting); // false
8. String and integer conversion
use + Operator to quickly convert a string to a number:
const stringNumer = '123'; console.log(+stringNumer); //123 console.log(typeof +stringNumer); //'number'
To quickly convert numbers to strings, you can also use + Operator followed by an empty string:
const myString = 25 + ''; console.log(myString); //'25' console.log(typeof myString); //'string'
These type conversions are very convenient, but their clarity and code readability are poor. Therefore, the actual development needs to be carefully selected and used.
9. Check for false values in the array
Everyone should have used array methods: filter, some and every. These methods can be combined Boolean Method to test true and false values.
const myArray = [null, false, 'Hello', undefined, 0]; // Filter virtual values const filtered = myArray.filter(Boolean); console.log(filtered); // ['Hello'] // Check that at least one value is true const anyTruthy = myArray.some(Boolean); console.log(anyTruthy); // true // Check that all values are true const allTruthy = myArray.every(Boolean); console.log(allTruthy); // false
Here is how it works. We know that these array methods accept a callback function, so we pass Boolean As a callback function. Boolean The function itself takes a parameter and returns it according to the authenticity of the parameter true or false. So:
myArray.filter(val => Boolean(val));
Equivalent to:
myArray.filter(Boolean);
10. Flatten array
There is a method on the prototype Array flat, you can make a single Array from the Array of an Array.
const myArray = [{ id: 1 }, [{ id: 2 }], [{ id: 3 }]]; const flattedArray = myArray.flat(); //[ { id: 1 }, { id: 2 }, { id: 3 } ]
You can also define a depth level to specify the depth at which a nested array structure should be flattened. For example:
const arr = [0, 1, 2, [[[3, 4]]]]; console.log(arr.flat(2)); // returns [0, 1, 2, [3,4]]
11.Object.entries
Most developers use Object.keys Method to iterate over the object. This method returns only an array of object keys, not values. We can use Object.entries To get keys and values.
const person = { name: 'songshu', age: 20 }; Object.keys(person); // ['name', 'age'] Object.entries(data); // [['name', 'songshu'], ['age', 20]]
To iterate over an object, we can do the following:
Object.keys(person).forEach((key) => { console.log(`${key} is ${person[key]}`); }); // Use entries to get keys and values Object.entries(person).forEach(([key, value]) => { console.log(`${key} is ${value}`); }); // name is songshu // age is 20
Both methods return the same result, but Object.entries Getting key value pairs is easier.
12.replaceAll method
In JS, to replace all existing strings with another string, we need to use the regular expression as follows:
const str = 'Red-Green-Blue'; // Only the first time str.replace('-', ' '); // Red Green-Blue // Replace all matches with RegEx str.replace(/\-/g, ' '); // Red Green Blue
However, in ES 12, one named replaceAll A new method is added to String.prototype It replaces all occurrences of a string with another string value.
str.replaceAll('-', ' '); // Red Green Blue
13. Number separator
You can use underscores as number separators, which makes it easy to count the number of zeros in a number.
// Difficult to read const billion = 1000000000; // Easy to read const readableBillion = 1000_000_000; console.log(readableBillion) //1000000000
The underscore separator can also be used for BigInt numbers, as shown in the following example
const trillion = 1000_000_000_000n; console.log(trillion); // 1000000000000
14.document.designMode
Related to JavaScript on the front end, design patterns allow you to edit anything on the page. Just open the browser console and enter the following.
document.designMode = 'on';
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (IMG shxiajvx-1633998428732) (/ img / bvcvdbh)]
15. Logical assignment operator
The logical assignment operator is composed of the logical operators & &, |?? And assignment operator =.
const a = 1; const b = 2; a &&= b; console.log(a); // 2 // The above is equivalent to a && (a = b); // perhaps if (a) { a = b }
Check whether the value of a is true. If true, update the value of A. Use logical or || Operators can do the same thing.
const a = null; const b = 3; a ||= b; console.log(a); // 3 // The above is equivalent to a || (a = b);
Use null merge operators ??:
const a = null; const b = 3; a ??= b; console.log(a); // 3 // The above is equivalent to if (a === null || a === undefined) { a = b; }
Note:?? Operators check only null or undefined Value of.