CodeOz translator: Front-end tips from Dev

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.

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

1. AvoidifToo long

If more than one condition is met, we might write:

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

If you have more than one condition like this, the if condition is very readable, and we can simplify it like this:

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

2. Double!The operator converts any variable to a Boolean value

! The (NOT) operator can be used twice!! This allows you to convert any variable to a Boolean value (like a Boolean function), which is handy when you need to check a value before processing it.

const toto = null !! toto // false Boolean(toto) // false if (!! toto) { } // toto is not null or undefinedCopy the code

3. Optional (?)

In JS, we often need to check the presence of certain attributes of an object before we can process it, otherwise an error will be reported. In the early days we might have done this:

const toto = { a: { b: { c: 5 } } } if (!! toto.a && !! toto.a.b && !! toto.a.b.c) { ... } // toto.a.b.c existCopy the code

If the objects are deeply nested, and this is hard to read, we can use it, okay? To simplify the:

if (!! toto.a? .b? .c) { ... } // to.a.b.exist // If the key does not exist, return 'undefined'. const test = toto.a? .b? .c? .d // undefinedCopy the code

4. IfifDo not write when the value is returned fromelse

You’ll often see this written:

if (...) {
  return 'toto'
} else {
  return 'tutu'
}
Copy the code

If there is a return value for if, we can write it like this:

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

return 'tutu'
Copy the code

5. AvoidforEach, use morefilter,map,reduce,everysome

As beginners, we use a lot of forEach functions, but JS gives us a lot of options, and these functions are FP (functional programming).

filter

The filter() method creates a new array containing all the elements of the test implemented through the provided function.

const toto = [1, 2, 3, 4] // evenValue = to.filter(currentValue => {return currentValue % 2 == 0}) // [2, 4]Copy the code

map

The map() method creates a new array with the result that each element in the array is the return value from a call to the provided function.

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

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

reduce

The reduce() method performs a reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value.

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

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

Some & Every

The some() method tests that at least one element in the array passes the provided function test. It returns a Boolean value.

The every() method tests whether all elements in an array pass the test of a given function. It returns a Boolean value.

When to use it?

All items meet one condition

const toto = [ 2, 4 ]

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

const falsyToto = [ 2, 4, 5 ]

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

As long as one of them fits, use some

const toto = [ 2, 4, 5 ] toto.some(val => val % 2 ! == 0) // return trueCopy the code

6. Don’t use itdeleteTo delete the property

Deleting an attribute from an object is very bad (poor performance), and it has many side effects.

But if you need to remove a property, how do you do it?

You can create a new object without this property functionally, as follows:

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

7. Add attributes to an object only if it exists

Sometimes, if we need to add attributes to an object that has already been defined, we might write:

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

if (condition) {
   other.name = toto.name 
}
Copy the code

❌ is not very good code

✅ could use something more elegant!

const condition = true const other = { other: 'other', ... condition && { name: 'toto' } }Copy the code

8. Use template strings

When we learn strings in JS, we need to concatenate them with variables

const toto = 'toto' const message = 'hello from ' + toto + '! ' // hello from toto!Copy the code

If there are other variables, we have to write long expressions, which can be optimized using template strings.

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

9. Conditional shorthand

When the condition is true and something is done, we might write:

if(condition){
    toto()
}
Copy the code

This can be done with && :

condition && toto()
Copy the code

10. Set the default values for variables

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
Copy the code

11. Use the 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
Copy the code

The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

Original text: dev. To/codeoz/impr…

communication

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.