Sunday, May 19, 2024
111
rated 0 times [  116] [ 5]  / answers: 1 / hits: 26738  / 9 Years ago, wed, august 12, 2015, 12:00:00

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


More From » if-statement

 Answers
7

Answer to your real question in the comments:



all2.forEach(function (e) {
e.getAttribute(class) && only.push(e.getAttribute(class));
});

[#65443] Monday, August 10, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janayr

Total Points: 80
Total Questions: 80
Total Answers: 114

Location: Venezuela
Member since Sat, Aug 22, 2020
4 Years ago
;