JongHyeok Lee
JongHyeok Lee

Reputation: 29

I want to understand more specifically about using Array.prototype.map() in JavaScript with arrays

let progresses = [93,30,55];    
let speeds = [1,30,5];  

function solution(progresses, speeds) {
    progresses.map((v,i) => {
        console.log(speeds[i]);
    })
}

Hi! this might be a rather simple question, but I just wanted to make it clear to myself understanding the accessing arrays using the map().

So, I am using Array.prototype.map() to iterate over the progresses array, however when I console.log(speeds[i]), how am I possible to access the speeds array? So my questions is I am using the map() on progresses array, but why is it also possible to access the speeds array too? Thanks in advance!

Upvotes: 1

Views: 41

Answers (2)

miorey
miorey

Reputation: 946

Every function build in another function have access to all parent function vars. Example:

function test(myVar1, myVar2) {
    return (() => myVar1 + (() => myVar2)())()
}
document.getElementById('test').textContent = test(2, 3)
<div id="test">empty</div>

To understand more about check the scope of a var, let, const

Upvotes: 1

Muirik
Muirik

Reputation: 6289

It's not really something particular about how map() works, but rather because of closure in JavaScript:

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

Upvotes: 4

Related Questions