Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 751
l2aelba Avatar asked Oct 15 '13 08:10

l2aelba


People also ask

How do you push inside an array?

The arr. push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array.

What does push () method of the array do?

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Can we push function in array?

JavaScript Array push()The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.

Which is faster push or Unshift?

Unshift is slower than push because it also needs to unshift all the elements to the left once the first element is added.


1 Answers

arr.push(typeof(test) == "undefined" ? null: test);
like image 130
lastr2d2 Avatar answered Sep 20 '22 19:09

lastr2d2