Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Ternary operator with empty else

I'm trying to convert the following if-else to it's ternary operator representation in javascript as follows

var x = 2;
if (x === 2) {alert("2");}
else
         { //do nothing}

But when I do this:

(t==2)?(alert("1")):();

Chrome throws a SyntaxError.

My question is - How to have a ternary operator in javascript with an empty "else" branch - i.e the part that comes after ":". Also, is this allowed- using a ternary operator in javascript to execute statements - NOT do assignment.

Also: the above code was just a base case. I'm actually trying to get all the DOM elements of the page as an array (called all2) and then add only those elements to another array (called only) only if they have non-null class names. Here is my code:

all2.forEach(function(e){ e.getAttribute("class") ? (only.push(e.getAttribute("class"))) : (); }); 

If I leave the third operand blank, it throws a syntax error. Passing a null works

like image 379
Probosckie Avatar asked Apr 13 '26 07:04

Probosckie


1 Answers

Answer to your real question in the comments:

all2.forEach(function (e) {
    e.getAttribute("class") && only.push(e.getAttribute("class"));
});
like image 122
Nina Scholz Avatar answered Apr 17 '26 11:04

Nina Scholz