Jump to content
tinfanide

Tenary Operators: cannot load a function?

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?

Share this post


Link to post
Share on other sites

The function is executed after window loads and If 'b' is equal to 'true', a new function is created/returned and if not, 'null' is returned. What is it you want?

Edited by CodeName

Share this post


Link to post
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

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...