Home > front end >  JS Assign the value of variable depending on conditional
JS Assign the value of variable depending on conditional

Time:09-26

I don't know why this doesn't work. Any ideas?

   let a = 0
    if (a == 0) {return let a = value0}
    else if (a == 1) {return let a = value1}
    else {return let a = valuex}
    console.log(a)

The console always says 0. What should I do?

CodePudding user response:

You are declaring a variable every time inside the condition. So variables will be scoped into brackets not outside of that brackets. So the global variable will not change in your case. And remove return. Solution is

let a = 0
if (a == 0) {
   a = value; 
}
else if (a == 1) {
   a = value1;
}
else {
   a = value;
}
console.log(a)

CodePudding user response:

The problem here is the scope of 'a'. let allows us to declare variables that are limited to the scope of a block statement,and once the block closes, it's scope ends.

let a = 0
//You don't need to redeclare a by using let
//Also you don't need to return anything since it's not a function
if (a == 0) { a = value0}
else if (a == 1) { a = value1}
else { a = valuex}
console.log(a)

CodePudding user response:

You shouldn't return from if branches, just assign a value to a:

let a = 0
if (a == 0) {a = value0}
else if (a == 1) {a = value1}
else {a = valuex}
console.log(a)
  • Related