Search code examples
javascriptarraysif-statementpusharray-push

If else shorthand inside array .push()


Why I can do if else shorthand inside .push() function ? like

var arr = [];
arr.push(test||null);
// nothing

But

var arr = [];
var test = test||null;
arr.push(test);
// [null]

I need to insert null if variable is undefined.

Why I cant use test||null inside .push() function ?


Solution

  • Yes. You can use

    arr.push(test||null);
    

    if you define test. Why your second code is working ?

    var arr = [];
    var test = test||null;
    arr.push(test);
    // [null]
    

    It's working because you have defined test.

    So, this works

    var test;
    var arr = [];
    arr.push(test||null);