Austin Story

Ruby, Rails and Javascript Blog

Powered by Genesis

Javascript Var Definitions Gotcha

December 19, 2016 By Austin Story Leave a Comment

This is one of the most common gotchas in Javascript.

What does this code do inside of a function?

‘var a = b = 0;’

Since javascript is right associative for assignments, at first glance you might expect it to create and set the variables a and b to 0. But there is a subtle gotcha hidden here. It actually does this

var a; //compile step initializes memory for a

b = 0; //we are in a scope, since b is not initialized in this scope (compile step misses it), javascript will go up the scope chain, assuming no parent scopes have b variable, the global scope will initialize var b for us and send it back.
a = b;

So more englishy, a is functionally scoped to the local function because it has the var in front of it. b is defined implicitly so it is put on the global scope.

Here is an example that demonstrates this further

[code]
function foo() {
var a = b = ‘assign in foo’;
function bar() {
var c = d = ‘assign in bar nested in foo’;
c; // ‘assign in bar nested in foo’
d; // ‘assign in bar nested in foo’
}
bar();
a; // ‘assign in foo’
b; // ‘assign in foo’
c; // ReferenceError, c only available in bar function
d; // ReferenceError, d available in bar and globally
}

foo();

a; // ReferenceError, because a is functionally scoped to the foo function
b; // ‘assign in foo’
c; // ReferenceError, because c is functionally scoped to the bar function
d; // ‘assign in bar nested in foo’
[/code]

After the invocation of foo in the code above, both b and d are now global variable.

Filed Under: Javascript Tagged With: gotchas, Javascript

Categories

  • AngularJS
  • Books
  • Devise
  • Elasticsearch
  • ES6
  • Information Security
  • Integrations
  • Javascript
  • Linux
  • Minitest
  • PhoneGap
  • Programming
  • React
  • Redux
  • Ruby
  • Ruby on Rails
  • Stripe
  • Testing
  • Theory
  • TypeScript
  • Uncategorized
  • Vue
  • Webpack