20 JavaScript Abbreviation Techniques To Improve Efficiency
There are many shorthand techniques in JavaScript that can shorten the code length, reduce redundancy, and improve the readability and maintainability of the code. This article will introduce 20 JS abbreviation techniques to improve efficiency, helping you say goodbye to the shit mountain and write elegant code easily!
Remove false values from an array
You can use filter()
combine Boolean
to simplify removing false values from an array. A false value refers to false
a value that is treated as a condition, such as null
, undefined
, the empty string ( ""
or ''
), 0, NaN
and false
.
Traditional writing:
let arr = [12, null, 0, 'xyz', null, -25, NaN, '', undefined, 0.5, false];
let filterArray = arr.filter(value => {
if(value) {
return value
};
});
// [12, 'xyz', -25, 0.5]
Simplified writing:
let arr = [12, null, 0, 'xyz', null, -25, NaN, '', undefined, 0.5, false];
let filterArray = arr.filter(value => Boolean(value)); // [12, 'xyz', -25, 0.5]
More simplified way of writing:
let arr = [12, null, 0, 'xyz', null, -25, NaN, '', undefined, 0.5, false];
let filterArray = arr.filter(Boolean); // [12, 'xyz', -25, 0.5]
Boolean
is a built-in constructor of JavaScript that converts a value into a Boolean value by passing it to it. In this case, Boolean
the constructor is passed to filter()
the method as a callback function, thus converting each array element to a Boolean value. Only elements whose conversion result is true will be retained in the new array.
Note: This method will also filter out 0. If you do not need to filter out 0, additional judgment is required.
Array search
When searching an array, indexOf()
it is used to obtain the position of the search item. If the item is not found, the return value is -1
. In JavaScript, 0 is treated as false
, and numbers greater or less than 0 are treated as true
. Therefore, it needs to be written like this:
Traditional writing:
if(arr.indexOf(item) > -1) {
}
if(arr.indexOf(item) === -1) {
}