Search code examples
javascriptvariableslogical-operators

Variable attribution with logical operator


I saw a code using logic operators while attributing the result of this to a variable.

function createSomething(param = {}){
  const new = param || otherConstant; 
}

How can I be sure that it will only attribute otherConstant if I don't have a param? Is the order of the operators?

Where can I read more about it? What is the name of this?


Solution

  • That's attribution by Logical Operator OR (||). The easiest way to understand it is to think of it like a fallback. For example:

    const result = variableA || variableB
    

    If and only if variableA returns a falsy value will variableB be attributed, so in this case variableB serves as fallback for variableA.

    What defines which variable will be set is the order of the operands (from left to right). The right operand is the fallback to the left operand.

    How can I be sure that it will only attribute otherConstant if I don't have a param?

    There are two ways to do it:

    // defining a default value to your parameter as you did in "(param={})"
    
    function createSomething(param = {}){ 
      const something= param; 
    }
    

    or:

    //using logical operator OR (||)
    
    function createSomething(param){ 
      const something= param || otherConstant; 
    }
    

    Don't use both ways together as they will cause redundance.