Reputation: 2038
I am creating variable and using it in for statement
for(var i = 0; i < 10; i++) {
console.log(i)
}
It is working properly and resulting from 1-10;
When I write same in the if
condition
if(var value = 10) {
console.log("Evaluate");
}
It is resulting Unexpected token var
.
When I declare a variable (var a = 10), resulting the same error. Is there any issue.
Upvotes: 0
Views: 482
Reputation: 68923
When you write
var value = 10
actually evaluated as the following statements:
var value;
value = 10
You can not write statement in if
as condition, as the condition must be only expression:
An expression that is considered to be either truthy or falsy.
Upvotes: 1
Reputation: 1449
You need to declare the variable like this:
var value = 10;
if(value == 10) {
console.log("Evaluate");
}
Upvotes: 0
Reputation: 325
Declare and initialize the variable outside. Use proper operators.
var value = 10;
if(value == 10) {
console.log("Evaluate");
}
else {
console.log("Hello");
}
Upvotes: 0
Reputation: 370999
An if
statement only accepts an expression inside (something that evaluates to a value). Something like var value = ...
is a statement - rather than evaluating to a value, it does something (namely, creates a local variable bound to the name value
). So, since var value = ...
cannot be evaluated as an expression, an error is thrown.
Some things can be evaluated both as statements and expressions (such as functions), but variable creation is not one of them.
Note that variable assignment is possible inside an if
, because assignment does evaluate to the value assigned:
var value;
if(value = 10) {
console.log('value now has the value 10');
}
But that's really confusing to read - a reader of the code will likely immediately worry whether that's a typo or not. Better to assign variables outside of an if
condition, whenever possible.
Only use var
when you want to create a new variable. If you simply want to check a variable (for example, check whether the variable named value
is 10
), then just print that variable name, and use a comparison operator (===
, not =
):
if (value === 10) {
// do stuff
}
Upvotes: 2