Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

var

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.

like image 676
user45867 Avatar asked Aug 12 '15 17:08

user45867


People also ask

Can you assign a variable to an IF statement in JavaScript?

Can you assign a variable in an if statement? Yes, you can assign the value of variable inside if.

What is the correct way to declare a variable in JavaScript?

Always declare JavaScript variables with var , let , or const . The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code to run in older browsers, you must use var .

Can var be used outside function JavaScript?

Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.

Why VAR should not be used in JavaScript?

Scoping — the main reason to avoid var var variables are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } .


1 Answers

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.

like image 70
James LeClair Avatar answered Sep 19 '22 16:09

James LeClair