Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Way for Conditional Variable Assignment

Tags:

javascript

Which is the better way for conditional variable assignment?

1st method

 if (true) {    var myVariable = 'True';  } else {    var myVariable = 'False';  } 

2nd Method

 var myVariable = 'False';  if (true) {    myVariable = 'True';  } 

I actually prefer 2nd one without any specific technical reason. What do you guys think?

like image 717
RaviTeja Avatar asked Jun 07 '12 06:06

RaviTeja


People also ask

How do you set a variable based on a condition?

The conditional ternary operator in JavaScript assigns a value to a variable based on some condition and is the only JavaScript operator that takes three operands. result = 'somethingelse'; The ternary operator shortens this if/else statement into a single statement: result = (condition) ?

Can we use assignment operator in if condition?

Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts: if (controlling expression)

Can you declare a variable in an if statement JS?

Should you define a variable inside IF statement? Honestly, there's no right or wrong answer to this question. JavaScript allows it, so you can make your decision from there.


2 Answers

try this

var myVariable = (true condition) ? "true" : "false" 
like image 85
dku.rajkumar Avatar answered Sep 21 '22 15:09

dku.rajkumar


There are two methods I know of that you can declare a variable's value by conditions.

Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into one statement.

var a = (true)? "true" : "false"; 

Nesting example of method 1: Change variable A value to 0, 1, 2 and a negative value to see how the statement would produce the result.

var a = 1; var b = a > 0? (a === 1? "A is 1" : "A is not 1") : (a === 0? "A is zero" : "A is negative"); 

Method 2: In this method, if the value of the left of the || is equal to zero, false, null, undefined, or an empty string, then the value on the right will be assigned to the variable. If the value on the left of the || does not equal to zero, false, null undefined, or an empty string, then the value on the left will be assigned to the variable.

Although the value on the left can be an undefined value for JS to evaluate the condition but the variable has to be declared otherwise an exception will be produced.

var a = 0; var b = a || "Another value"; 
like image 34
Kevin Ng Avatar answered Sep 22 '22 15:09

Kevin Ng