0

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.

Ben Pearce
  • 6,884
  • 18
  • 70
  • 127

3 Answers3

5

?: 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]

broofa
  • 37,461
  • 11
  • 73
  • 73
0

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);}
Khamidulla
  • 2,927
  • 6
  • 35
  • 59
  • 1
    `typeof` isn't a function. You don't need the `()` after it. And it returns a string, so you need to compare to `"undefined"`. But better to just do `someVariable != undefined`. – Blue Skies Nov 07 '13 at 02:31
0

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

Community
  • 1
  • 1
Guy Gavriely
  • 11,228
  • 6
  • 27
  • 42