Question

I am trying to re-write the statement below using the javascript ?: syntax.

if(type of someVariable !="undefined"){
     someFunction(someVariable);
}else{}

This is my current attempt and it's causing a syntax error

typeof someVariable != "undefined" ? someFunction(someVariable) : ;

If any one can tell met what I'm doing wrong I'd appreciate it. Any accompanying tips on best practices for defensive programing are welcome.

No correct solution

OTHER TIPS

?: style (requires expressions on either side of the :):

typeof(someVariable) != 'undefined' ? someFunction : null;

Ninja-style:

someVariable !== undefined && someFunction(someVariable);

[Edit: I couldn've sworn noop was a thing in Javascript, but apparently I was wrong. Switched to null]

even though the ternary operation controls the program flow, I'd use it only in assignment operation or when returning a value from a function.

check this out: Benefits of using the conditional ?: (ternary) operator

It should look like this.

someVariable != undefined ? someFunction(someVariable):someOtherfunction(someOtherVarialbe);

if you do not want else statement and want it in single line you can do like this:

  if(someVariable != undefined){someFunction(someVariable);}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top