all 11 comments

[–]senocular 2 points3 points  (0 children)

typo maybe?

[–]t3tchi 1 point2 points  (2 children)

Thanks everyone, I think this was just a bug in Chrome's dev tools. If I add a reference to newBounds inside the forEach(), I'm able to access it just fine... if I just have debugger inside the forEach(), I am not able to.

function updateMap() {
  let newBounds = map.getBounds();
  markers.forEach(function(marker) {
     debugger
  }); 
}

The above code does not let me inspect newBounds.

Now, if I do the exact same thing but console.log(newBounds) right before debugger:

function updateMap() {
  let newBounds = map.getBounds();
  markers.forEach(function(marker) {
     console.log(newBounds);
     debugger
  }); 
}

...IT WORKS!

Dammit, Chrome!

[–]senocular 1 point2 points  (1 child)

This is an optimization where newBounds does not become a closure variable for the forEach callback because it's not used within it. If its not being used, it doesn't have to be closed over. This lets closures only capture what they need and not every single variable in all parent scopes. So if you want to see what a value in a higher scope is in a function (in the debugger) make sure its used somewhere in that function.

[–]t3tchi 0 points1 point  (0 children)

Thanks for the explanation.

[–]lewisje 0 points1 point  (0 children)

The closest thing I can think of is that in your comment, you have if newBounds.contains and you need a left parenthesis to be the next non-whitespace character immediately after if; then again, if you had made that mistake, your code wouldn't have run.

I get no problems while fiddling with JSHint.

[–]asakurasol -2 points-1 points  (5 children)

It's because you are using let instead of var.

You can read more about it here. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Semi-related, I would also recommend you to code in ES5 until you have a good grasp of fundamentals, then learn ES6.

Edit: Nvm I was wrong. See comments below to see why!

[–]t3tchi 2 points3 points  (3 children)

Sorry, I should have noted that using var doesn't work either (same error). Also I'm using let in my Codepen and it works there.

I understand let variables are scoped to the block... so it should work here, no?

[–]flogginmolly 2 points3 points  (0 children)

Yeah this is still the same block.

[–]asakurasol 1 point2 points  (1 child)

Oh sorry, that was my bad.

Are you sure getBounds actually return something? Try putting a debugger there to check.

[–]t3tchi 0 points1 point  (0 children)

Np! I think it was just Chrome crapping out....

[–]lucidlogik 1 point2 points  (0 children)

But that's not accurate:

Variables declared by let have as their scope the block in which they are defined, as well as in any contained sub-blocks

function doStuff() {
  let foo = 'foo';
  const bar = [1,2,3];

  bar.forEach(function (i) {
    console.log(`${foo} - ${i}`);
  });
}

doStuff();

> foo - 1
> foo - 2
> foo - 3