Книга: Functional Programming in JavaScript
Назад: Closures
Дальше: Function declarations versus function expressions versus the function constructor

Gotchas

Many variable scope nuances can be found throughout JavaScript. The following is by no means a comprehensive list, but it covers the most common cases:

  • The following will output 4, not 'undefined' as one would expect:
    for (var n = 4; false; ) { } console.log(n);

    This is due to the fact that, in JavaScript, variable definition happens at the beginning of the corresponding scope, not just when it is declared.

  • If you define a variable in the outer scope, and then have an statement define a variable inside the function with the same name, even if that branch isn't reached, it is redefined. An example:
    var x = 1; function foo() {   if (false) {     var x = 2;   }   return x; } foo(); // Return value: 'undefined', expected return value: 2

    Again, this is caused by moving the variable definition at the beginning of the scope with the value.

  • In the browser, global variables are really stored in the object.
    window.a = 19; console.log(a); // Output: 19

    in the global scope means as an attribute of the current context, so and object in a browser act as an equivalent of the keyword in the global scope.

The first two examples are a result of a feature of JavaScript known as hoisting, which will be a critical concept in the next section about writing functions.

Назад: Closures
Дальше: Function declarations versus function expressions versus the function constructor

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)