8
atulmy
8y

Today I was asked a question on JavaScript regarding the difference between normal `for` loop and a `map` function on an array with regards to closures. Can anyone help me understand? #javascript #interview

Comments
  • 1
    I wanna' know this too.
  • 7
    Javascript uses function scoping.

    In a normal for loop you have no local scope within the loop and hence no closures.
  • 3
  • 0
    @Voxera traditionally true, though we do now have block scoping as well with the let/const keywords
  • 1
    @AllenII depending on platform but yes.

    But that is not a function of the for loop.

    And how does block scope work with closures? I actually do mot know if it is the same as function scope.
  • 0
    @Voxera to be honest with you, i only started using closures heavily only a few months ago, so i got nothing to personally say if there's any difference. But seeing as closures are formed by creating an inner execution context (function) i guess there shouldn't be much if any difference at all.

    Or I'm missing the point entirely somehow, I dunno
  • 1
    @AllenII looks like we have to try ;) and find out.
  • 0
    @Voxera i literally just layed down
  • 0
    @w0ble great article
  • 2
    In JS, functions are treated as first class objects. This allows you to return a function or pass it as an argument/parameter into other functions. This means a function could be created in one place and called in another place; closures help us handle possible problems with variable access (scope). Different from context (`this`).

    Reading articles is definitely useful, the one linked above seems handy.
  • 3
    @faisal
    Yes. And after some sleep I also realized that without the function there is no way to create a closure.

    Its not just scope that matters.

    Only a function allows you to return actual code which is what triggers closure so without a function no closure and back to the original question: a map uses a function to process each element which can trigger closure while a "for" loop does not by it self use a function and does not trigger a closure.
  • 0
    @Voxera yes exactly! +1
Add Comment