Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript variable assignment with OR vs if check [duplicate]

Tags:

javascript

In JavaScript I recently realized you could use the OR || logical operator for assignment, and I want to know if it's considered bad practice.

In particular I have some functions that have optional array input, if the input is null or undefined I should just set it to an empty array [], if it has content it should take the content.

I found that using the assignment using the OR operator handles that perfectly in a single line, it's clean. However, it feels like the kind of thing that might be considered bad practice, or may have some horrible pitfalls I'm not considering.

Another approach is a simple if check, which is fairly safe in general.

I want to know if using the || approach seen below has any pitfalls I'm not considering, although it works in this scenario I would appreciate knowing if it works well to keep using this in the future, or to stop using it altogether.

https://jsbin.com/nozuxiwawa/1/edit?js,console

var myArray = ['Some', 'Strings', 'Whatever'];

// Just assign using OR
var pathOne = function(maybeAnArray) {
    var array = maybeAnArray || [];

    console.log(array);
}

// Assign using IF
var pathTwo = function(maybeAnArray) {
    var array = [];

    // Covers null and undefined
    if (maybeAnArray != null) {
        array = maybeAnArray;
    }

    console.log(array);
}

console.log('Path one:');

pathOne(myArray); // ['Some', 'Strings', 'Whatever']
pathOne(null);    // []

console.log('\nPath two:');

pathTwo(myArray); // ['Some', 'Strings', 'Whatever']
pathTwo(null);    // []
like image 985
Erick Avatar asked May 15 '26 23:05

Erick


1 Answers

IMHO the use of the OR || for the purposes of assignment is perfectly valid and is good practice. We certainly use it in our projects and I've seen it used in lots of 3rd party projects that we use.

The thing you need to be aware of is how certain JavaScript objects can be coerced to be other values. So for example, if you're ORing values such as "", false or 0 then they are treated as false... this means that when you have the following:

function f(o) {
   var x = o || -1;
   return x;
}

Calling:

f(0) 

...will return -1... but calling

f(1)

Will return 1 ... even though in both cases you passed a number - because 0 is treated as false -1 is assigned to x.

...that said, as long as you're aware of how the OR operator will treat the operands that you use with it - then it is good JavaScript practice to use it.

like image 200
Dave Draper Avatar answered May 18 '26 11:05

Dave Draper