If else shorthand inside array .push()

l2aelba picture l2aelba · Oct 15, 2013 · Viewed 10.9k times · Source

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 ?

Answer

lastr2d2 picture lastr2d2 · Oct 15, 2013
arr.push(typeof(test) == "undefined" ? null: test);