This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

By Haseeb Anwar

Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom.

In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.

JavaScript has a lot of cool features that most beginner and intermediate developers don’t know about. Today I’m going to share some of the techniques that I often use in my projects.

1. Conditionally add attributes to objects

We can use the expansion notation (…) To quickly add attributes to JS objects conditionally.

const condition = true; const person = { id: 1, name: 'John Doe', ... (condition && { age: 16 }), };Copy the code

The && operator returns the last evaluated expression if each operand has a value of true. So return an object {age: 16} and then extend it as part of the Person object.

If condition is false, JavaScript does something like this:

Const person = {id: 1, name: '... (false), }; // Expanding 'false' has no effect on the object console.log(person); // { id: 1, name: 'John Doe' }Copy the code

2. Check whether the attribute exists in the object

You can use the in keyword to check for the presence of an attribute in a JavaScript object.

Const person = {name: salary: 1000}; console.log('salary' in person); // true console.log('age' in person); // falseCopy the code

3. Name of the dynamic property in the object

Setting object properties using dynamic keys is simple. Simply use [‘key name’] to add attributes:

const dynamic = 'flavour'; Var item = {name: 'console.log ', [dynamic]:' chocolate '} console.log(item); // {name: 'cross ', flavour:' chocolate '}Copy the code

The same technique can be used to reference object properties using dynamic keys:

const keyName = 'name'; console.log(item[keyName]); // returns' front-end smarts'Copy the code

4. Use dynamic keys to deconstruct objects

We know that when an object is deconstructed, we can use: to rename the deconstructed property. But did you know that when keys are dynamic, you can also deconstruct an object’s properties?

Const person = {id: 1, name: '1'}; const { name: personName } = person; console.log(personName); // select * from * where *Copy the code

Now, we use dynamic keys to deconstruct properties:

const templates = {
  'hello': 'Hello there',
  'bye': 'Good bye'
};
const templateName = 'bye';

const { [templateName]: template } = templates;

console.log(template); // Good bye
Copy the code

5. Null value merge??The operator

When we want to check whether a variable is null or undefined, Operators are useful. It returns the right-hand operand when its left-hand operand is null or undefined, otherwise returns its left-hand operand.

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); / / 0Copy the code

In the third example, 0 is returned, because even though 0 is considered false in JS, it is not null or undefined. You may think that we can use the | | operator but there are some differences between the two

You may think that we can use here | | operators, but there are some differences between the two.

const cannotBeZero = 0 || 5; console.log(cannotBeZero); // 5 const canBeZero = 0 ?? 5; console.log(canBeZero); / / 0Copy the code

6. Optional link chain? .

TypeError: Cannot read property ‘foo’ of null TypeError: Cannot read property ‘foo’ of null This is an annoying problem for every developer. Alternative chains were introduced to solve this problem. Take a look:

const book = { id:1, title: 'Title', author: null }; Console.log (book.author.age) // throws error console.log(book.author && book.author.age); // null // Console. log(book.author? .age); // undefined // or depth of the optional chain console.log(book.author? .address? .city); // undefinedCopy the code

You can also use the following function to select chains:

Const person = {firstName: ' ', lastName: ' ', printName: function () {return '${this.firstname} ${this.lastname}'; }}; console.log(person.printName()); DoesNotExist (persone.doesnotexist?) doesNotExist (persone.doesnotexist? . ()); // undefinedCopy the code

7. Use!!!!!The 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); // falseCopy the code

8. String and integer conversion

Use the + operator to quickly convert a string to a number:

const stringNumer = '123';

console.log(+stringNumer); //123
console.log(typeof +stringNumer); //'number'
Copy the code

To quickly convert a number to a string, you can also use the + operator, followed by an empty string:

const myString = 25 + '';

console.log(myString); //'25'
console.log(typeof myString); //'string'
Copy the code

These conversions are very convenient, but their clarity and code readability are poor. So the actual development, need to carefully choose to use.

9. Check the array for false values

You’ve probably used array methods: filter, some, and every, which work with Boolean methods to test true and false values.

const myArray = [null, false, 'Hello', undefined, 0]; Const filtered = myarray. filter(Boolean); console.log(filtered); // ['Hello'] // Check whether at least one value is true const anyTruthy = myarray.some (Boolean); console.log(anyTruthy); // true // Check whether all values are true const allTruthy = myarray.every (Boolean); console.log(allTruthy); // falseCopy the code

Here’s how it works. We know that these array methods accept a callback function, so we pass Boolean as the callback function. Boolean functions themselves take an argument and return true or false depending on whether the argument is true. So:

myArray.filter(val => Boolean(val));
Copy the code

Is equivalent to:

myArray.filter(Boolean);
Copy the code

10. Flatten arrays

On the prototype Array there is a method called Flat, where you can make a single Array out of an Array.

const myArray = [{ id: 1 }, [{ id: 2 }], [{ id: 3 }]];

const flattedArray = myArray.flat(); 
//[ { id: 1 }, { id: 2 }, { id: 3 } ]
Copy the code

You can also define a depth level, specifying the depth at which a nested array structure should be flattened. Such as:

const arr = [0, 1, 2, [[[3, 4]]]];
console.log(arr.flat(2)); // returns [0, 1, 2, [3,4]]
Copy the code

11.Object.entries

Most developers use the object.keys method to iterate over objects. This method returns only an array of object keys, not values. We can use Object.entries to obtain keys and values.

Const person = {name: 'age ', age: 20}; Object.keys(person); // ['name', 'age'] Object.entries(data); // [['name', 'age'], ['age', 20]]Copy the code

To iterate over an object, we do the following:

Object.keys(person).forEach((key) => { console.log(`${key} is ${person[key]}`); }); Object.entries(person).foreach (([key, value]) => {console.log(' ${key} is ${value} '); }); // age is 20Copy the code

Both methods return the same result, but object. entries are easier to obtain key-value pairs.

12. ReplaceAll method

In JS, to replace all occurrences of a string with another string, we need to use a regular expression like this:

const str = 'Red-Green-Blue'; Replace ('-', ' '); // Red green-blue // Replace all matches with RegEx str.replace(/\-/g, "); // Red Green BlueCopy the code

But in ES12, a new method called replaceAll was added to String.Prototype, which replaces all occurrences with another String value.

str.replaceAll('-', ' '); // Red Green Blue
Copy the code

13. Numeric delimiters

You can use an underscore as a number separator, which makes it easy to count the number of zeros in a number.

// hard to read const billion = 1000000000; // Easy to read const readableBillion = 1000_000_000; console.log(readableBillion) //1000000000Copy the code

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); / / 1000000000000Copy the code

14.document.designMode

Related to the JavaScript on the front end, design mode lets you edit anything on the page. Just open your browser console and type the following.

document.designMode = 'on';
Copy the code

15. Logical assignment operators

Logic assignment operator is the logical operators &&, | |,?? And the assignment operator =.

const a = 1; const b = 2; a &&= b; console.log(a); // 2 // the above is equivalent to a && (a = b); // if (a) {a = b}Copy the code

Check if the value of A is true, and if so, update the value of A. Use logic or | | operators can also do the same thing.

const a = null; const b = 3; a ||= b; console.log(a); / / / / 3 above is equivalent to a | | (a = b);Copy the code

Use the null value merge operator?? :

const a = null; const b = 3; a ?? = b; console.log(a); / / 3 / / it is equivalent to the if (a = = = null | | a = = = undefined) {a = b; }Copy the code

Note:?????? The operator only checks for null or undefined values.

~~ end, I am brush bowl wisdom, praise and look is the biggest support for me, I will be good to brush the bowl.

Please feel free to discuss in the comments section. The nuggets will draw 100 nuggets in the comments section after the diggnation project. See the event article for details

The possible bugs in editing can not be known in real time. In order to solve these bugs after the event, I spent a lot of time on log debugging. By the way, I recommend a good bug monitoring tool for youFundebug.

The original:

Betterprogramming. Pub / 10 – modern – j… Betterprogramming. Pub / 5 – cool – mode…

communication

This article is updated weekly, you can search wechat ** [big move the world] the first time to read, reply [welfare] ** there are many front-end video waiting for you, this article GitHub github.com/qq449245884… Already included, welcome Star.