Is it possible to change a variable in the middle of an if else statement? For example when running this code after the first two false statements I try to change exampleOne to 7 and then have it log ’ This is equal to 7 ’ but instead it just remains the same number and I get Try again. logged. I assume i’m just doing something wrong but not sure where.
let exampleOne = 10
if (exampleOne=== 9) {
console.log(‘This is equal to 9’);
} else if ( exampleOne=== 8) {
console.log(‘This is equal to 8’);
exampleOne = 7
} else if (exampleOne=== 7) {
console.log(‘This is equal to 7’);
} else {
console.log(‘Try again.’)
}
You can change the variable, but it won’t give you your expected result.
Current code will always give you Try again, since no condition ever matches exampleOne === 10.
1 Like
So there is not a way to change the variable mid if else statement to the number 7 that would trigger the ‘This is equal to 7’ output?
Well you could force it to land on 7 by nesting a condition within your else if statement
let exampleOne = 8;
if (exampleOne === 9) {
console.log('This is equal to 9');
} else if (exampleOne === 8) {
console.log('This is equal to 8');
exampleOne = 7;
if (exampleOne === 7) {
console.log('This is equal to 7');
}
} else {
console.log('Try again.');
}
but I fail to see the point in this?
Yes, you can change the value of the variable inside.
No, it is not possible to change a variable so that it triggers more than one block in an if and else-if sequence.
I guess you could change the else if
to be if
but then you’d have to change the else
as well.
let exampleOne = 8;
if (exampleOne === 9) {
console.log('This is equal to 9');
}
if ( exampleOne=== 8) {
console.log('This is equal to 8');
exampleOne = 7;
}
if (exampleOne=== 7) {
console.log('This is equal to 7');
}
if (!(exampleOne === 7 || exampleOne === 8 || exampleOne === 9)) {
console.log('Try again.')
}
1 Like