Search code examples
javascriptvar

setting a javascript variable with an if statement -- should the 'var = x' be inside or outside the IF?


This may be a basic question but I'm having difficulty finding an answer.

You want to set var B based on var A

would you do

var B = if(A == "red"){"hot"}else{"cool"}

I don't think this works.

I guess you could do

if(A == "red"){var B = "hot"}else{var B = "cool"}

This doesn't seem particularly elegant. I mean I would prefer something that starts with var b = .... just for clarity's sake.


Solution

  • perfect use for a ternary

    var B = (A ==="red") ? "hot":"cool";
    

    Ternary expressions will always return the first value if true, the second value if not. Great for one-off if/else statements, but if you get into more nested conditions, be sure to use the traditional if/else blocks for readability.