I have a javascript function as below :
function modifyx(xvalue) {
val = 1;
for (x = 0; x < 10; x++) {
val = val + 1;
}
return val;
}
And the main snippet passes a variable named x to the above function as below:
for (x = 0; x < 10; x++) {
console.log(modifyx(x));
}
The expected output should be "11" printed 10 times but instead it prints one time. The function call changes the value of x eventhough i am not modifying the passed value. The x inside the function has it's own scope. Yet it gets modified. Any help on this would be highly appreciated.
The variable x
in your code is global
. When your method modifyx(xvalue)
returns for the first time the value of x
is already 11 which is used in the for loop for the second iteration. Thus it fails to execute the method further.
Use let x
in the declaration in for (x = 0; x < 10; x++)
to create a unique execution environment.
function modifyx(xvalue) {
val = 1;
for (x = 0; x < 10; x++) {
val = val + 1;
}
return val;
}
for (let x = 0; x < 10; x++) {
console.log(modifyx(x));
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments