5

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 ?

l2aelba
  • 21,591
  • 22
  • 102
  • 138
  • Your first example causes an error, that's why nothing happens. Please take a look at the console. – Teemu Oct 15 '13 at 08:04

2 Answers2

3
arr.push(typeof(test) == "undefined" ? null: test);
lastr2d2
  • 3,604
  • 2
  • 22
  • 37
2

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);
MC ND
  • 69,615
  • 8
  • 84
  • 126