Skip to content

Instantly share code, notes, and snippets.

@andineck
Last active August 29, 2015 14:23
Show Gist options
  • Save andineck/9f9c392a570cfa53b4e2 to your computer and use it in GitHub Desktop.
Save andineck/9f9c392a570cfa53b4e2 to your computer and use it in GitHub Desktop.
javascript variables

understand javascript variables

run:

node variables.js
var test = require('tape');
test('reuse local variable in inner function (same name) -> does not get overwritten', function(t){
var reused = 'hello';
['sauabona', 'hi', 'ciao', 'hoi', 'salue', 'hello'].forEach(function(reused){
if (reused == 'hello') reused = 'hello world';
});
t.equal(reused, 'hello');
t.end();
});
test('try use variable from inner function in outer function -> does not exist', function(t){
['sauabona', 'hi', 'ciao', 'hoi', 'salue', 'hello'].forEach(function(reused){
if (reused == 'hello') reused = 'hello world';
});
t.equal(typeof reused, 'undefined');
t.end();
});
test('assign outer variable in inner function -> gets persisted', function(t){
var outer = 'hello';
['sauabona', 'hi', 'ciao', 'hoi', 'salue', 'hello'].forEach(function(hello){
if (hello == 'hello') outer = 'hello world';
});
t.equal(outer, 'hello world');
t.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment