With the following code JsLint warns that y is already defined in the 2nd block. I do this fairly often and don't think it is a syntax error since the variable is defined in a different block.
Should I really be using different variable names even though it is in a different block? Is the scope defined by the code block of the if statement or only scoped for a function block?
function x() {
if (condition1) {
var y = 0;
// use y
}
if (condition2) {
var y = 20;
// use y
}
}
With the following code JsLint warns that y is already defined in the 2nd block. I do this fairly often and don't think it is a syntax error since the variable is defined in a different block.
Should I really be using different variable names even though it is in a different block? Is the scope defined by the code block of the if statement or only scoped for a function block?
function x() {
if (condition1) {
var y = 0;
// use y
}
if (condition2) {
var y = 20;
// use y
}
}
Share
Improve this question
asked Oct 16, 2013 at 17:43
BrennanBrennan
11.7k16 gold badges68 silver badges86 bronze badges
1
-
I would not suggest using
var
at all. This will only exposey
to everything else of the if scope that you have defined, which could be harmful given where and what y means to the function/global scope. Uselet
instead. - stackoverflow./a/11444416/3670089 – Yashash Gaurav Commented May 26, 2020 at 16:19
3 Answers
Reset to default 8Declare it once
function x() {
var y;
if (condition1) {
y = 0;
}
if (condition2) {
y = 20;
}
}
JS will have block scoping in the future, but it's not widely implemented yet.
There is no different scope inside if
, for
and while
statements, but there is in functions.
I know there is accepted answer to this already, but I think what you are looking for is a let
statement.
Please refer to this answer to understand variable scoping (let
vs var
): https://stackoverflow./a/11444416/3670089
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745392828a4625742.html
评论列表(0条)