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
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"?