20

In this article, I will share with you some tips about JS that can improve your JS skills.

Author: CodeOz
Translator: Frontend Xiaozhi
Source: dev
There are dreams and dry goods. Wechat search [Daqiang World] Pay attention to this Shuawanzhi who is still doing dishes in the early morning.
This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

We are hiring, annual salary: 250,000-600,000 + bonus, if you are interested, please click me for details.

1. Avoid too long if

If the judgment value satisfies multiple conditions, we might write:

if (value === 'a' || value === 'b' || value === 'c') { ... }

Like this, if there are multiple conditions, the if condition will be very good, and the readability will be reduced. We can simplify it like this:

if (['a', 'b', 'c'].includes(value)) { ... }

2. The double ! operator converts any variable to a boolean value

The! (NOT) operator can be used twice !! , so that any variable can be converted to a Boolean value (like a Boolean function), which is very convenient when you need to check a certain value before processing it.

const toto = null

!!toto // false
Boolean(toto) // false

if (!!toto) { } // toto is not null or undefined

3. Optional ( ? )

In JS, we need to frequently check whether certain properties of the object exist before we can process it, otherwise an error will be reported. In the early days we might do this:

const toto = { a: { b: { c: 5 } } }

if (!!toto.a && !!toto.a.b && !!toto.a.b.c) { ... } // toto.a.b.c exist

If the object is deeply nested, our writing method will be difficult to read. At this time, you can use ? to simplify:


if (!!toto.a?.b?.c) { ... } // toto.a.b.c exist

//  如果键不存在,返回 `undefined`。
const test = toto.a?.b?.c?.d // undefined

4. If if when the return value, do not write else

We often see this way of writing:

if (...) {
  return 'toto'
} else {
  return 'tutu'
}

If if has a return value, you can write:

if (...) {
  return 'toto'
}

return 'tutu'

5. Avoid forEach , use filter , map , reduce , every , some

As a beginner, we use a lot of forEach functions, but JS provides us with a lot of choices, and these functions are FP (functional programming).

filter

filter() method creates a new array that contains all the elements of the test implemented by the provided function.

const toto = [1, 2, 3, 4]

// 过滤奇数
const evenValue = toto.filter(currentValue => {
   return currentValue % 2 == 0
}) // [2, 4]

map

map() method creates a new array, and the result is that each element in the array is the return value after calling the provided function once.

const toto = [1, 2, 3, 4]

const valueMultiplied = toto.map(currentValue => {
   return currentValue * 2 
}) // [2, 4, 6, 8]

reduce

reduce() reducer function (ascending order execution) provided by you on each element in the array, and aggregates the results into a single return value.

const toto = [1, 2, 3, 4]

const sum = toto.reduce((accumulator, currentValue) => {
   return accumulator += currentValue 
}, 0) // 10

Some & Every

some() method tests whether at least 1 elements in the array pass the provided function test. It returns a Boolean value.

every() method tests whether all elements in an array can pass the test of a specified function. It returns a boolean value.

When is it used?

All items meet one condition, you can use every

const toto = [ 2, 4 ]

toto.every(val => val % 2 === 0) // true

const falsyToto = [ 2, 4, 5 ]

falsyToto.every(val => val % 2 === 0) // false

As long as one meets the conditions, use some

const toto = [ 2, 4, 5 ]

toto.some(val => val % 2 !== 0) // return true

6. Do not use delete to delete attributes

delete from an object is very bad (bad performance), in addition, it will produce many side effects.

But if you need to delete an attribute, what should you do?

You can use the function method to create a new object without this attribute, as shown below:

const removeProperty = (target, propertyToRemove) => {
  const { [propertyToRemove]: _, ...newTarget } = target
  return newTarget
}
const toto = { a: 55, b: 66 }
const totoWithoutB = removeProperty(toto, 'b') // { a: 55 }

7. Only add properties to the object if it exists

Sometimes, if the object has properties defined, we need to add properties to the object, we might write like this:

const toto = { name: 'toto' }
const other = { other: 'other' }
// The condition is not important
const condition = true

if (condition) {
   other.name = toto.name 
}

❌Not very good code

✅ Some more elegant things can be used!

const condition = true

const other = {
   other: 'other',
   ...condition && { name: 'toto' }
}

8. Use template strings

When learning strings in JS, we need to connect them with variables

const toto = 'toto'
const message = 'hello from ' + toto + '!' // hello from toto!

If there are other variables, we have to write very long expressions, then we can use template strings to optimize.

const toto = 'toto'
const message = `hello from ${toto}!` // hello from toto!

9. Condition abbreviation

When the condition is true , to perform certain operations, we may write:

if(condition){
    toto()
}

This way can be abbreviated &&

condition && toto()

10. Set the default value of the variable

If you need to set a default value for a variable, you can do this:

let toto

console.log(toto) //undefined

toto = toto ?? 'default value'

console.log(toto) //default value

toto = toto ?? 'new value'

console.log(toto) //default value

11. Use console timer

If you need to know the execution time of a function, you can do this:

for (i = 0; i < 100000; i++) {
  // some code
}
console.timeEnd() // x ms

possible bugs after 1619db1c2969b2 code are deployed 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 .

Original: https://dev.to/codeoz/improve-your-js-skls-with-theses-tips-52ia

comminicate

If you have dreams and dry goods, search on [Great Move to the World] Follow the brushing wisdom who is still doing dishes in the early morning.

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


王大冶
68.1k 声望105k 粉丝