21

Can this be done in JavaScript?

type == 1 ? function1() : function2();
6
  • 12
    Have you tested it? :) Commented Oct 31, 2009 at 17:38
  • 5
    you realize you can type javascript into the address bar of your browser to test it? Commented Oct 31, 2009 at 18:08
  • 2
    Try it yourself. Paste this: javascript:void(true ? alert('t') : alert('f')) Commented Oct 31, 2009 at 19:02
  • 2
    I'm just looking back at this question after all these years and it seem's pretty dumb that I didn't test it out on the console before posting it here. I think I was intimidated by the console back then. Commented Dec 1, 2015 at 18:59
  • Question from the title, solution: stackoverflow.com/questions/6678411/… Commented Feb 2, 2016 at 11:33

2 Answers 2

30

Yes, that's valid code. It will invoke either function1() or function2(), but not both - depending on the value of type.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 It must be a slow day on SO when Jon Skeet and Ned Batchelder are answering JavaScript questions! :)
Got to hit that rep-cap, whatever it takes :D
It's valid, but JSHint will give a warning when ternary operators are used in this manner. To disable the warning you should set expr: true in your .jshintrc file.
7

It won't invoke two functions. It will invoke one of your two functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.