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.
Can you assign a variable in an if statement? Yes, you can assign the value of variable inside if.
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 .
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.
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 { } .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With