/ javascript

Javascript - Shorthand for Switch statement

You might have seen similar code in javascript. I wanted to understand how it is working. As it does not look like a ternary expression.

return {
  "false": React.DOM.a({
    href: "javascript:void(0)",
    onClick: this.linkClicked
  }, "Click Me Now"),
  "true": React.DOM.span({}, "You have clicked")
}[this.state.clicked];

While discussing with team we found that, it is nothing, but a SWITCH CASE

click her to see shorthand for js

So when we execute above mentioned code, if "this.state.clicked" is TRUE then it will show SPAN with text 'You have clicked'". This is just a shorthand for SWITCH, so we do not have to write complete "SWITCH CASE" statement.

You can try this code in your console and see it working.

clickState = 'true';
alert({
      "false": "I am FALSE case",
      "true": "I am TRUE case"
    }[clickState]
)
Shivani Thakur

Shivani Thakur

I am life time learner, passionate about technology, fullstack programmer and prefer clean deliveries. I am fearless, honest and vocal about my thoughts.

Read More