Skip to content

Commit

Permalink
Fixed console.log output
Browse files Browse the repository at this point in the history
In modern browsers console.log(1, 3) results in "1 3", not "1,3"
  • Loading branch information
snqb committed Jan 5, 2017
1 parent 93abe18 commit 3ff1d8d
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions scope & closures/ch2.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,12 @@ function foo(str, a) {

var b = 2;

foo( "var b = 3;", 1 ); // 1, 3

This comment has been minimized.

Copy link
@sherrygirl30

sherrygirl30 Jan 8, 2017

Symbols and numbers thrown together meaning nothing

This comment has been minimized.

Copy link
@legodude17

legodude17 Jan 9, 2017

What do you mean?

foo( "var b = 3;", 1 ); // 1 3
```

The string `"var b = 3;"` is treated, at the point of the `eval(..)` call, as code that was there all along. Because that code happens to declare a new variable `b`, it modifies the existing lexical scope of `foo(..)`. In fact, as mentioned above, this code actually creates variable `b` inside of `foo(..)` that shadows the `b` that was declared in the outer (global) scope.

When the `console.log(..)` call occurs, it finds both `a` and `b` in the scope of `foo(..)`, and never finds the outer `b`. Thus, we print out "1, 3" instead of "1, 2" as would have normally been the case.
When the `console.log(..)` call occurs, it finds both `a` and `b` in the scope of `foo(..)`, and never finds the outer `b`. Thus, we print out "1 3" instead of "1 2" as would have normally been the case.

**Note:** In this example, for simplicity's sake, the string of "code" we pass in was a fixed literal. But it could easily have been programmatically created by adding characters together based on your program's logic. `eval(..)` is usually used to execute dynamically created code, as dynamically evaluating essentially static code from a string literal would provide no real benefit to just authoring the code directly.

Expand Down

0 comments on commit 3ff1d8d

Please sign in to comment.