Home > Mobile >  when there's a return in an if in a for loop how come you can't assign a variable?
when there's a return in an if in a for loop how come you can't assign a variable?

Time:07-14

Consider this:

let arr = ['hello', 'hi', 'ok', 'this one']
let varToAssign

function assignTheVar() {
    for(let i = 0; i < arr.length; i  ) {
    if(arr[i] == 'this one') {
        varToAssign = arr[i]
      return
    }
    }
  console.log(varToAssign)
}

window.addEventListener('load', assignTheVar)

The variable varToAssign doesn't get console logged.

Why is that?

Search results for this question

enter image description here

But this works:

let arr = ['hello', 'hi', 'ok', 'this one']
let varToAssign

function assignTheVar() {
    for(let i = 0; i < arr.length; i  ) {
    if(arr[i] == 'this one') {
        varToAssign = arr[i]
    }
    }
  console.log(varToAssign)
}

window.addEventListener('load', assignTheVar)

I'm aware this is a dumb question but I'm struggling finding answers online, I don't know what to search for.

Why can't I declare a variable inside a for loop?

Not really what I'm looking for...

this one kind of answers it

Returning values out of for loop in javascript

The return statement immediately exits a function, returning the value of the expression that follows it. If you use a return statement in a loop without some sort of conditional like that it will preform the first pass and then exit. You need to collect them in a variable and return the variable after the loop. As others have suggested you'll probably want to store them in an array. – Useless Code Nov 15, 2011 at 5:31

But isn't that what I'm doing? It "performed" the first pass so shouldn't it return the value before "returning"?

CodePudding user response:

The return statement returns from the function, immediately. So when you execute that return statement, the code that logs the value is not executed.

The variable does get assigned, just not logged, as you can see by executing the slightly modified version of your snippet below (I also modified the indentation, which may make the structure a little clearer):

let arr = ['hello', 'hi', 'ok', 'this one']
let varToAssign

function assignTheVar() {
    for(let i = 0; i < arr.length; i  ) {
        if(arr[i] == 'this one') {
            varToAssign = arr[i]
            console.log("before returning: "   varToAssign)
            return
        }
    }
    console.log(varToAssign)
}

window.addEventListener('load', assignTheVar)

CodePudding user response:

When you use for-loop till i === 2 the if condition is not true so there is no change of assignment but at the time i is equals to 3 then It assigns the value to varToAssign and then return. So the console inside the function assignTheVar will never run.

But for sure the value has assigned. you can see from below example

let arr = ['hello', 'hi', 'ok', 'this one'];
let varToAssign;

function assignTheVar() {
  for (let i = 0; i < arr.length; i  ) {
    if (arr[i] == 'this one') {
      varToAssign = arr[i];
      return;
    }
  }
  console.log(varToAssign); // WON'T EXECUTE THIS LINE BECAUSE THE CONTROL WILL RETURN EARLY
}
assignTheVar();
console.log(varToAssign);

CodePudding user response:

In addition to David. P Caldwell's answer, if what you actually want to do is this:

  1. Assign the value to varToAssign when the if statement is true
  2. And then stop the for loop and run the code that comes after the for loop

Then you can replace "return" with "break". That breaks (stops) the for loop, but doesn't return the function. This means that the for loop will stop running and the next step is that the program runs the code immediately after the for loop.

Like this:

let arr = ['hello', 'hi', 'ok', 'this one']
let varToAssign

function assignTheVar() {
    for(let i = 0; i < arr.length; i  ) {
      if(arr[i] == 'this one') {
        varToAssign = arr[i]
        break
      }
    }
    console.log(varToAssign)
}

window.addEventListener('load', assignTheVar)

See more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break

  • Related