One developer summed up these 15 elegant JavaScript tips

Keywords: Javascript node.js html5 TypeScript Programmer

Author: Haseeb Anwar
Translator: front end Xiaozhi
Source: medium

There are dreams and dry goods. Wechat search [Daqian world] pays attention to this bowl washing wisdom who is still washing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi It has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

JavaScript has many cool features that most beginners and intermediate developers don't know. Today I share some tips that I often use in projects.

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, the & & operator returns the last evaluated expression. Therefore, an object {age: 16} is returned and extended as part of the person object.

If the condition is false, JavaScript will do the following:

const person = {
  id: 1,
  name: 'Front end Xiaozhi',
  ...(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

You can use the in keyword to check whether a property exists in a JavaScript object.

const person = { name: 'Front end Xiaozhi', 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: 'Front end Xiaozhi',
  [dynamic]: 'Chocolates'
}
console.log(item); // {name: 'front end Xiaozhi', flavor: 'chocolate'}

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

const keyName = 'name';
console.log(item[keyName]); // returns' front end Xiaozhi '

4. Use dynamic keys to deconstruct objects

We know that when an object is deconstructed, you can use: to rename the deconstructed attributes. 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: 'Front end Xiaozhi' };
const { name: personName } = person;
console.log(personName); // 'front end Xiaozhi'

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,?? Operators are useful. When its left operand is null or undefined, it returns the right operand, otherwise it returns the left 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); // 0

In the third example, 0 is returned because even if 0 is considered false in JS, 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 the | operator here, 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 errors: 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: 'Xiao Zhi',
  printName: function () {
    return `${this.firstName} ${this.lastName}`;
  },
};
console.log(person.printName()); // 'front end Xiaozhi'
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 the + operator to quickly convert a string to a number:

const stringNumer = '123';

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

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'

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 cooperate with 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 the callback function. The Boolean function itself accepts a parameter and returns true or false according to the authenticity of the parameter. So:

myArray.filter(val => Boolean(val));

Equivalent to:

myArray.filter(Boolean);

10. Flatten array

There is a method flat on the prototype Array, which can make a single Array from 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 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 get keys and values.

const person = {
  name: 'Front end Xiaozhi',
  age: 20
};

Object.keys(person); // ['name', 'age']
Object.entries(data); // [['name ',' front end Xiaozhi '], ['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 Xiaozhi
// age is 20 

Both of the above methods return the same result, but it is easier to get key value pairs with Object.entries.

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, a new method called replaceAll is added to String.prototype, which replaces all existing strings 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. The same thing can be done using logical or | operators.

const a = null;
const b = 3;

a ||= b;
console.log(a); // 3

// The above is equivalent to
a || (a = b);

Use null merge operator?:

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:?? The operator only checks for null or undefined values.

~~After that, I am the wisdom of washing the dishes. Some praise and watching are the greatest support for me. I will wash the dishes well.

The possible bugs in editing cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful bug monitoring tool Fundebug.

Original text:

https://betterprogramming.pub/10-modern-javascript-tricks-every-developer-should-use-377857311d79
https://betterprogramming.pub/5-cool-modern-javascript-features-most-developers-dont-know-6baf19b532da

communication

The article is continuously updated every week. You can search * * [Daqian world] on wechat to read it for the first time and reply to [welfare] * * there are many front-end videos waiting for you. This article GitHub https://github.com/qq449245884/xiaozhi Already included, welcome Star.

Posted by onepixel on Mon, 11 Oct 2021 17:37:59 -0700