A developer summarizes these 15 elegant JavaScript tips

Author: Haseeb Anwar
Translator: Frontend Xiaozhi
Source: medium

If you have dreams and dry goods, search on [Daily Move to the World] Follow this wise brush who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line factory interview complete test sites, materials and my series of articles.

JavaScript has many cool features that most beginners and intermediate developers don't know. To share some today, I often use some techniques in projects.

1. Conditionally add attributes to objects

We can use the expansion operator ( ... ) to conditionally add properties to the JS object quickly.

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. So return an object {age: 16} , and then expand it to person object.

If condition is false , JavaScript will do something like this:

const person = {
  id: 1,
  name: '前端小智',
// 展开 `false` 对对象没有影响
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 certain property exists in the JavaScript object.

const person = { name: '前端小智', salary: 1000 };
console.log('salary' in person); // true
console.log('age' in person); // false

3. Dynamic attribute names in the object

Using dynamic keys to set object properties is simple. Just use ['key name'] to add attributes:

const dynamic = 'flavour';
var item = {
  name: '前端小智',
  [dynamic]: '巧克力'
console.log(item); // { name: '前端小智', flavour: '巧克力' }

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

const keyName = 'name';
console.log(item[keyName]); // returns '前端小智'

4. Use dynamic keys to deconstruct objects

We know that when the object is deconstructed, you can use : to rename the deconstructed attributes. But, did you know that when the key name is dynamic, you can also deconstruct the properties of the object?

const person = { id: 1, name: '前端小智' };
const { name: personName } = person;
console.log(personName); // '前端小智'

Now, we use dynamic keys to deconstruct the properties:

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

const { [templateName]: template } = templates;

console.log(template); // Good bye

5. Null merge ?? operator

When we want to check whether a variable is null or undefined , the ?? operator is 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 returned because even though 0 is considered false in JS, it is not null or undefined . You may think we can use || operator but there is a difference between the two

You might think that 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 this error: TypeError: Cannot read property ‘foo’ of null . This is an annoying problem for every Yi developer. The introduction of optional chains is to solve this problem. Lets come 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
// 或深度可选链
console.log(book.author?.address?.city); // undefined

You can also use the following function optional chain:

const person = {
  firstName: '前端',
  lastName: '小智',
  printName: function () {
    return `${this.firstName} ${this.lastName}`;
console.log(person.printName()); // '前端 小智'
console.log(persone.doesNotExist?.()); // undefined

7. Use !! operator

!! operator 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 requires careful selection and use.

9. Check for false values in the array

Everyone should have used array methods: filter , some , every , these methods can be used with the Boolean method to test the true and false values.

const myArray = [null, false, 'Hello', undefined, 0];

// 过滤虚值
const filtered = myArray.filter(Boolean);
console.log(filtered); // ['Hello']

// 检查至少一个值是否为真
const anyTruthy = myArray.some(Boolean);
console.log(anyTruthy); // 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. 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:


10. Flatten Array

There is a method flat on the prototype Array, which can make a single array from an array of arrays.

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 how deep a nested array structure should be flattened. E.g:

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


Most developers use the Object.keys method to iterate objects. This method only returns an array of object keys, not a value. We can use Object.entries to get the key and value.

const person = {
  name: '前端小智',
  age: 20

Object.keys(person); // ['name', 'age']
Object.entries(data); // [['name', '前端小智'], ['age', 20]]

In order to iterate an object, we can do the following:

Object.keys(person).forEach((key) => {
  console.log(`${key} is ${person[key]}`);

// 使用 entries 获取键和值
Object.entries(person).forEach(([key, value]) => {
  console.log(`${key} is ${value}`);

// name is 前端小智
// age is 20 

Both of the above methods return the same results, but Object.entries is 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 as shown below:

const str = 'Red-Green-Blue';

// 只规制第一次出现的
str.replace('-', ' '); // Red Green-Blue

// 使用 RegEx 替换所有匹配项
str.replace(/\-/g, ' '); // Red Green Blue

But in ES12, a replaceAll was added to String.prototype , which replaces all occurrences of the string with another string value.

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

13. Number separator

You can use the underscore as the number separator, so you can easily count the number of zeros in the number.

// 难以阅读
const billion = 1000000000;

// 易于阅读
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


Related to front-end JavaScript, the design mode allows you to edit any content on the page. Just open the browser console and enter the following.

document.designMode = 'on';

15. Logical assignment operator

The logical assignment operator is a combination of the logical operators && , || , ?? and the assignment operator = .

const a = 1;
const b = 2;

a &&= b;
console.log(a); // 2

// 上面等价于
a && (a = b);

// 或者
if (a) {
  a = b

Check a the value of 0616d68d2447a4 is true, if it is true, then update the value of a The same thing can be done using the logical or ||

const a = null;
const b = 3;

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

// 上面等价于
a || (a = b);

Use the null merge operator ?? :

const a = null;
const b = 3;

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

// 上面等价于
if (a === null || a === undefined) {
  a = b;

Note: The ?? operator only checks the value of null or undefined

~~ At the end, I’m the wise man. Likes and watching are my greatest support. I will do my best.

possible bugs in 1616d68d244831 editing cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .




The article is continuously updated every week, you can search for [Daqichang World] read it as , reply 1616d68d2448ab [Benefit] are many front-end videos waiting for you, this article GitHub https://github.com/qq449245884/xiaozhi has been included, welcome to Star.

阅读 978

62.9k 声望
94.9k 粉丝
0 条评论
62.9k 声望
94.9k 粉丝