Three practical JavaScript tips

Time:2020-5-20

Get array elements from back to front

If you want to get the elements of an array from the back to the front, you can write as follows:

var newArray = [1, 2, 3, 4]

console.log(newArray.slice(-1)) // [4]
console.log(newArray.slice(-2)) // [3, 4]
console.log(newArray.slice(-3)) // [2, 3, 4]
console.log(newArray.slice(-4)) // [1, 2, 3, 4]

Short circuit conditional sentence

If you want to have a conditional logical value oftrueTo execute a function, as follows:

if (condition) {
  dosomething()
}

In this case, you can use the short circuit as follows:

condition && dosomething()

Use the operator “|” to set the default value

If you have to assign a default value to a variable, you can simply write as follows:

var a

console.log(a) // undefined

a = a || 'default value'

console.log(a) // default value

a = a || 'new value'

console.log(a) // default value