I've just started learning JavaScript and I have a question about the if
statement: why when I assign a variable inside the if
I don't need to add var
before it and when I assign it outside the if
, I must add var
. So, mainly the question is: why I can't add var
inside the if
like this
if (var number = 5) {
document.write("successful");
} else {
document.write("failed");
}
and if i didn't add a var it assign the variable to the value like this
if (number = 5) {
document.write("successful");
} else {
document.write("failed");
}
I know it's a simple question but it got me confused.
Probably, what you are trying to do is this:
var number = 4;
if (number == 5){
document.write("successful");
}
else{
document.write("failed");
}
JavaScript does not support block level scoping and this means that declaring a variable inside of a block structure like a if
or a for
loop, does not restrict that variable to the statement.
Remember that you need to declare a variable before assigning it to something.
var x;
x = 'variable x is a string that was previously declared';
This means that in your first not syntactically correct example, you are trying to define a variable inside a statement that, instead, should check the truth of that variable against something else. And this seems actually what you are trying to do in your second example, except that you have to use a double equals ==
( comparison ) or triple equals ===
( strict equality or identity ).
At this point, you may want to understand the differences in using =
, ==
and ===
.
var a = 55;
a == 55 /* In this case the output will be true if you have declared the previous variable */
a === 55 /* Will return true as the content is the same and also the type (they are both numbers) */
a === '55' /* Will return false, as you are comparing a number against a string */
Said that, remember also that JavaScript has two variables scopes : global and local.
var b = 'hello world';
function test() {
console.log(b);
}
test();
/* Output will be:
hello world
*/
var b = 'hello world';
function test() {
var b = 'Wonderful World';
console.log(b);
}
console.log(b);
test();
console.log(b);
/* Output will be:
hello world
Wonderful World
hello world
*/
It's because var means that you declare a variable. However you can't declare a variable in an if condition. You can just assign values to previously declared variables in the condition. It is Javascript's syntax.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.