Ternary operator? :

Every weekend I ask myself, what’s the schedule? So I wrote a program and ran it

    if (hasMoney) {
        console.log('Weekend Fun');
    } else {
        console.log('Sleep all weekend');
    }
Copy the code

It doesn’t look like a problem, but the code feels a bit bloated. Can we simplify it a bit?

With the ternary operator

    hasMoney ? console.log('Weekend Fun') : console.log('Sleep all weekend');
Copy the code

Look, when hasMoney is true, high, and false sleep for a day. This operator is useful when we assign values based on simple judgment conditions

    let weekendPlan = hasMoney ? 'Weekend Fun' : 'Sleep all weekend';
Copy the code

This way, our code won’t be riddled with if conditionals, and it’ll be a little slappy. But don’t be too flirtatious

    val = simpleCondition
        ? 1
        : simpleConditionAgain
        ? 2
        : simpleConditionAgainAndAgain
        ? 3
        : 4;
Copy the code

The above example is a bit pushy for the sake of pushy. It is a bit poor in code readability, even with the if conditional. In such cases, you can optimize using switch statements or the design philosophy of policy patterns.

Logic and operator &&

If you have money, you will go to the party on the weekend, but if you have no money, you haven’t decided what to do (although you can’t do anything without money)

    if (hasMoney) {
        console.log('Weekend Fun');
    }
Copy the code

This is the case with the ternary operator

    hasMoney ? console.log('Weekend Fun') : undefined;
Copy the code

It’s kind of weird that we have to write undefined to tell the program what to do if the condition is false. This problem can be avoided by using logic and operators

    hasMoney && console.log('Weekend Fun');
Copy the code

Logic and operators use Boolean functions to determine whether each condition (expression) is true. If all the conditions are true, the result of the final expression is returned. But if any of the criteria is false, the result of the first criteria is returned

    true && console.log('It is true');                         // It is true
    true && false && console.log('It is true');                / / returns false
    true && 0 && console.log('It is true');                    / / returns 0
    true && undefined= =null && console.log('It is true');    // It is true that undefined == null
    true && undefined= = =null && console.log('It is true');   // undefined === null returns false
Copy the code

Use logic and operators to render elements in React

    render() {
        return (
            <Fragment>{
                data.length && data.map(item => <span>{ item }</span>)}</Fragment>
        );
    }

    // When there is no data, the page renders a 0
Copy the code

The above example is intended to render data when it is available, and do nothing when it is not. But the logic and operator will return the result of the first false expression, resulting in a 0!

Logic or the operator | |

When it comes to logic and operators, we have to mention its gay friends: logic or operators. Consider the following scenario

    // If self is undefined, the value is 0, otherwise it is selfval = val ! = =undefined ? val : 0;
Copy the code

Using the ternary operator to handle the logic of the example above, we need to explicitly determine whether val is empty, and then determine whether the variable val should equal itself. So in the spirit of saving what we can, we can use logic or operators

    val = val || 0;
Copy the code

Logic or operator that passes the result of the first expression to a Boolean function, which returns the result if the Boolean function returns true; Otherwise the next one will be tried until the end; Returns the result of the last expression if all expressions have a Boolean value of false

This operator is therefore useful for setting default values for function arguments for backward compatibility

    // ES5 sets the function default value
    function testFunc(arg1) {
        arg1 = arg1 || 1;

        // do something else
    }

    let a = 1,
        b = 2,
        c = null;
    
    console.log(a || b || c);         / / 1
    console.log(0 || b || c);         / / 2
    console.log(0 || false || c);     // null
Copy the code

Note: The if conditional uses the Boolean or, logic, and operators to return the result of the expression, and then implicitly calls the Boolean function to get a final Boolean value

Logic take reverse!

As mentioned above, if you have money, you can do whatever you want on weekends. If you don’t have money, you probably have to sleep all day. In this case, using hasMoney as the criterion, our code looks like this

    hasMoney === false && console.log('Sleep all weekend');
Copy the code

When hasMoney is not a Boolean, the hasMoney === false statement always returns false, giving the illusion of money. So we have to convert hasMoney to a Boolean, and the inverse operator gives us both of those things

! hasMoney &&console.log('Sleep all weekend');
Copy the code

So you can sleep all day when you’re broke.

The negate operator converts a value of a non-Boolean type to a Boolean type and negates it

    !true && console.log('666');             / / returns false!!!!!true && console.log('666');            / / 666
    {} && console.log('666');                / / an error! {} &&console.log('666');               / / returns false!!!!! {} &&console.log('666');              / / 666
Copy the code

The bitwise inverse operator ~ is used

We need to check whether an element exists in an array. In ES6, you can use includes

    let arr = ['we'.'are'.'the'.'BlackGold'.'team'];

    arr.includes('the') && console.log('in');      // in
Copy the code

But this method has a major limitation: there is no way to pass in a filter function.

    let arr = ['we'.'are'.'the'.'BlackGold'.'team'];

    arr.includes(element= > element === 'the') && console.log('in');     / / returns false
Copy the code

In this case, we can usually use the findIndex method

    let arr = ['we'.'are'.'the'.'BlackGold'.'team'];

    arr.findIndex(element= > element === 'the')! = =- 1 && console.log('in');      // in
Copy the code

Since the findIndex method returns an index starting at 0, we must determine whether the index returned is not equal to -1 or greater than or equal to 0. If the bitwise inverse operator is used, no display is required to determine

    let arr = ['we'.'are'.'the'.'BlackGold'.'team'];

    ~arr.findIndex(element= > element === 'we') && console.log('in');      // in
    ~arr.findIndex(element= > element === 'the') && console.log('in');      // in
Copy the code

The bitwise inverse operator, as its name implies, reverses each bit of a variable: 0->1, 1->0

    console.log(~- 1);       // when 0 is converted to Boolean, the value is false
    console.log(~0);        // when -1 is converted to Boolean, the value is true
    console.log(~1);        // when -1 is converted to Boolean, the value is true
Copy the code

conclusion

JavaScript SAO operation series mainly summarizes some easy to use JavaScript features, methods, for communication and learning, do not like spray. If there is any mistake, welcome to correct.

Related articles:

Traversal, Enumeration and Iteration of JavaScript Operations (Part 1)

Traversal, Enumeration and Iteration of JavaScript Operations (Part 2)

@Author: PaperCrane