0

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?

2
  • Put your code in a snippet.As you can see, this does not work. Please add correct code Commented Sep 25, 2021 at 13:47
  • let isn’t an expression. Why do you even have return there? What are you actually testing? Only if(a == 0) will ever be true. Commented Sep 25, 2021 at 13:48

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.