Jump to content

Tenary Operators: cannot load a function?


tinfanide

Recommended Posts

var b = true;window.onload = function(){(b==true) ? function(){  var c = "Hello!";  func(c);  } : null ;}function func(c){document.write("The word is " + c);}

It seems that the function cannot be loaded in this tenary operator.Why's that?

Link to comment
Share on other sites

what do you mean by "loaded"? In order for a function to execute, you need to call it, with parens (). Your inner "wrapper" function is never executed, and thus it will never call the inner func function. Consider a readable implementation of your code. There is no need to use the ternary operator since you are not assigning the value to anything, or returning anything from the function.Also, I would not recommend using document.write, and instead write to the innerHTML property of some element on the page. But for now, let's stick with your example.

var aCondition = true;var writeToPage = function(word){  document.write('The word is ' + word);}; window.onload = function(){  if(aCondition){	writeToPage('hello');  }}

Edited by thescientist
Link to comment
Share on other sites

I think Tin is looking for something like this:

window.onload =(b==true) ? function(){  var c = "Hello!";  func(c);  } : null;

EDIT: scientist was quicker. :P His example would also work. Mine only creates the onload function if b is true, where scientist's always creates the onload but only prints output if b is true. Same result, different technique.

Edited by ShadowMage
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...