This article mainly records the usual practice of their own, learn from the blog and see javascript skills in some project source code. Some of these things are weird tricks, and some of them might be useful new syntaxes in ES6+.

Use && and | |

Sometimes we need to execute another function when a function or variable is true. Such as:

const task1 = (a)= > {
    console.log('execution task1');
    return Math.random() >= 0.5;
}

const task2 = (a)= > console.log('Task1 execute task2 after successful execution');
if (task1()) task2();
Copy the code

The above if statement can be simply abbreviated as && :

task1() && task2();
Copy the code

If you want to execute task3 after task1 fails (i.e. task1 returns false), you can use:

const task3 = (a)= > console.log('Task3 executed after task1 failed');
task1() && task2() || task3();
Copy the code

In essence or use && and | | short circuit characteristics.

It is also possible to use the conditional operator:

task1() ? task2() : task3();
Copy the code

Here is a code snippet from a recent project I developed using React hooks, using render props:

const ProfileItem = (props) = > {
    const { name, value, render } = props;

    return (
        <div className="profile-item">
            <span className="item-name">{name}</span>
            <form action="">{/ * render depending on whether the props to return different content * /} {render && render (props) | |<SimpleProfileItemContent value={value}/>}
            </form>
        </div>)}Copy the code

Function defaults

ES5 version

It is quite common to use short circuits or operators to set function defaults. However, there are some pitfalls. In the code shown below, when the default parameter is a number, the default value is still used when the parameter is 0.

const pow = (x, y) = > {
    y = y || 2;
    
    let result = 1;
    for (let i =  0, max = y; i < max; i++) {
        result *= x;
    }

    return result;
}

console.log(pow(2)); / / = > 4
console.log(pow(2.3)); / / = > 8

// 当 y 传值为 0 时, y 取值 2
console.log(pow(2.0)); / / = > 4
Copy the code

ES6 version

ES6 provides much more reliable default syntax at the syntactic level

const pow = (x, y=2) = > {
    let result = 1;
    for (let i =  0, max = y; i < max; i++) {
        result *= x;
    }

    return result;
}

console.log(pow(2)); / / = > 4
console.log(pow(2.3)) / / = > 8
console.log(pow(2.0)); / / = > 1
Copy the code

Class array to array

An array is a class of objects like Arguments and jquery objects that can be accessed using subscripts and have a length property that looks like an array but is not an array.

Class arrays do not have slice, map, and other collection functions, which is why we sometimes need to convert class arrays to arrays.

function func() {
    for (let i = 0, max = arguments.length; i < max; i++) {
        console.log(arguments[i]);
    }

    console.log(Array.isArray(arguments)); // => false
    // Class arrays do not have slice, forEach, map, etc
    console.log(arguments.slice === undefined); // => true
}

func('Google'.'facebook'.'Microsoft'); 
/ / = >
// Google
// facebook
// Microsoft
Copy the code

Transformation methods in ES5

Call the Slice method from the Array prototype by binding it to the Arguments object and passing no arguments so that it returns all elements.

function func() {
    const array = Array.prototype.slice.call(arguments);
    console.log(array.slice(0.1));
}

func('Google'.'facebook'.'Microsoft'); // => [ 'Google' ]
Copy the code

Transformation methods in ES6

ES6 has more methods for converting class arrays to arrays.

Use extension operators

function func() {
    console.log([...arguments])
}

func('Google'.'facebook'.'Microsoft'); // [ 'Google', 'facebook', 'Microsoft' ]
Copy the code

The use of Array. The from

function func() {
    console.log(Array.from(arguments))
}

func('Google'.'facebook'.'Microsoft'); // [ 'Google', 'facebook', 'Microsoft' ]
Copy the code

Construct an array of contiguous integers

I’m going to go straight to what I think is the best method

// Outputs 2 to start with 8 consecutive integers
const array = Array.from({ length: 8}).map((ele, index) = > index + 2);
console.log(array); // => [2, 3, 4, 5, 6, 7, 8, 9]

// The comments section points out that there is a more concise version of array. from with its own mapping function
const array = Array.from({ length: 8}, (ele, index) => index + 2);
console.log(array); // => [2, 3, 4, 5, 6, 7, 8, 9]

// Array.prototype.keys can be used to construct the prototype
const array = [...Array(8).keys()].map((ele, index) = > index + 2)
Copy the code

Function arguments are assigned using deconstruction

When a function has a lot of parameters, we tend to let the parameters directly accept a configuration object. However, we cannot set the default value with object parameters. When we use object parameters in the function body, we also need to use object parameters to access, when the number of visits or deep nesting will feel inconvenient. Using deconstructed assignment in function parameters solves this problem.

// Default values must be set for object parameters, otherwise an error will be reported when passing parameters because there is no deconstruction of the object
const getUsers = ({
    offset=0,
    limit=1,
    orderBy="salary"= > {} = {})// Query the database based on the condition to return user data
    console.log({ offset, limit, orderBy });
}

getUsers({ offset: 10.limit: 20.orderBy: 'age' }); // => { offset: 10, limit: 20, orderBy: 'age' }
getUsers();// => { offset: 0, limit: 1, orderBy: 'salary' }
Copy the code

Use!!!!! Convert other types to bool

console.log(!! {});// true
console.log(!!0); // false
console.log(!! []);// true
console.log(!!undefined); // false

const httpGet = (url, retry) = > {
    if(!!!!! retry) {// Retry the timeout}}Copy the code

JSON.stringify

The depth of the clone

Using serialization and deserialization to deeply clone objects is generally convenient, but the disadvantage is that functions and inherited properties cannot be cloned.

Lodash’s cloneDeep is recommended if you want to clone function properties.

const me = {
    name: 'lyreal666'.age: 23,
    speak() {
        console.log(`Hello, I'm ly! `); }}const clonedMe = JSON.parse(JSON.stringify(me));
console.log(clonedMe); // => { name: 'lyreal666', age: 23 }
console.log(clonedMe.speak === undefined); // => true
Copy the code

Use the second and third arguments

The second argument to json.stringify is used to process the property value, and the third argument is used to specify the indentation length of the output JSON string, which can be either a number or a string.

const me = {
    name: 'lyreal666'.age: 23,
    speak() {
        console.log(`Hello, I'm ly! `); }}const jsonStr = JSON.stringify(me, (key, value) => key === 'name' ? "Yu" : value, 2);

console.log(jsonStr);
/* => {"name": "old ", "age": 23} */
Copy the code

Elegant traversal of objects

Use deconstructed assignments and Object.entries.

const me = {
    name: 'lyreal666'.age: 23,
    speak() {
        console.log(`Hello, I'm ly! `); }}for (const [key, value] of Object.entries(me)) {
    console.log(`${key}: ${value}`);
}

/* => name: lyreal666 age: 23 speak: speak() { console.log(`Hello, I'm ly! `); } * /
Copy the code

The fastest way to empty an array

In the comments section, some people say that changing length directly is problematic. I’ve seen discussions about clearing arrays before, but I think it’s generally fine because it’s easy and doesn’t reallocate memory to a new array.

const array = [1.2.3.4];
array.length = 0;
console.log(array); / / = > []

// It is better to assign an empty array directly
let array = [1.2.3.4];
array = [];
Copy the code

Check whether an integer is -1

The ~ operator can be simply written as inverting the increment of one
console.log(~1); / / = > - 2
console.log(~0); / / = > 1
console.log(~(- 3)); / / = > 2
console.log(~(- 1)); / / = > 0

const number = 2 -;

// Check whether a number is -1
if(! ~number) {// 当 number 是 -1 的操作...
}
Copy the code

Execute function immediately

Executing functions immediately allows variables in our code to not contaminate external variables. Common uses are as follows.

// Call the function in parentheses
(function(window, $) {
    // Internal code
}) (window, jQuery)
Copy the code

The more elegant way is the following, in fact many other arithmetic operators such as +, -, *, ~, etc., also work.

! function(window, $) {
    // Internal code
} (window, jQuery)

// You can also use +, -, *, etc
+ function(window, $) {
    // Internal code
} (window, jQuery)

// You can also use the new, typeof operators
new function(window, $) {
    // Internal code
} (window, jQuery);Copy the code

Use set to duplicate arrays

console.log([...new Set([1.3.1.2.2.1]]);// => [1, 3, 2]
Copy the code

Use reduce to multiply or add

const array = [ 1.2.3.4];
/ / even
console.log(array.reduce((p, c) = > p + c)); / / = > 10
/ / LianCheng
console.log(array.reduce((p, c) = > p * c)); / / = > 24
Copy the code

integer

I’ll leave out a bunch of rounding functions in Math, but I’ll focus on some more subtle rounding methods.

console.log(~~3.14); / / = > 3
console.log(~~(2.5)); / / = > - 2

console.log(6.18 | 0); / / = > 6
console.log(3.6 | 0); / / = > - 3

console.log(9.9 >> 0); / / = > 9
console.log(2.1 >> 0); / / = > - 2

/ / the superagent is a very practical node module sends an HTTP request, it USES | handling of return code
var type = status / 100 | 0;

// status / class
res.status = status;
res.statusType = type;

// basics
res.info = 1 == type;
res.ok = 2 == type;
res.clientError = 4 == type;
res.serverError = 5 == type;
res.error = 4 == type || 5 == type;
Copy the code

Use + to convert other types to the number type

console.log(+'3.14'); / / = > 3.14
console.log(typeof +'3.14') // => number

const sleep = (milliseconds) = > {
        return new Promise((resolve, reject) = > {
            setTimeout((a)= > resolve(), milliseconds);
        });
}

// Consider using console.time for testing
! async function main() {
    const start = +new Date(a);await sleep(3000);
    const end = +new Date(a);console.log(` performed${end - start}`); // Execute 3002} ();Copy the code

Use scientific notation for large numbers

const str1 = 'hello';
const str2 = ' world'

console.time('Test + concatenate string');
for (let i = 0; i < 200000000; i++) {
    const joinedStr = str1 + str2;
}
console.timeEnd('Test + concatenate string');

console.time('Test template string concatenation string');
// Using scientific notation is much easier than typing 8 zeros
for (let i = 0; i < 2E8; i++) {
    const joinedStr =`${str1}${str2}`;
}
console.timeEnd('Test template string concatenation string')

/* => Test + stitching string: 3238.037ms Test template string Stitching string: 3680.225ms */
Copy the code

Exchange variable value

Use deconstruction assignment directly

let a = Awesome!;
let b = 999;
[a, b] = [b, a];
console.log({ a, b }); // => { a: 999, b: 666 }
Copy the code

Get random strings

The string after the beginning of the subscript 2 is truncated because the string 0 of the decimal returned by math.random () is not required. These two characters. Using base 36 allows you to create random strings with a greater variety of characters

console.log(Math.random().toString(16).substring(2)); // 13 bits => 45d9d0bb10b31 console.log(math.random ().toString(36).substring(2)); // 13 bits => 45d9d0bb10b31 console.log(math.random ().toString(36).substring(2)); // 11 bits => ZwCX1YEWJvjCopy the code

Flattening an array

ES 2019 added array.prototype. flat Chrome 73.0.3683.103 is currently supported. Node 10.15.3 is not supported. Node 11.13.0 is supported. Here is a post in nuggets a brother face through the inside see hack method, here should pay attention to do type conversion according to the situation.

const array = [1[2[3.4].5].6.7];
console.log(array.toString().split(', ').map(ele= > Number.parseInt(ele))); // => [1, 2, 3, 4, 5, 6, 7]
Copy the code

Recently interviewed Tencent, Ali front-end internship post is really a long story, behind the whole article to talk about my recent interview experience. Nodejs is nearing the end of the second article in her crawler series.

This article is original content, first published in personal blog, reproduced please indicate the source. Email harassment is welcome if you have questions [email protected].