Skip to content

Instantly share code, notes, and snippets.

@mathildathompson
Forked from mispelaur/js_scopes.md
Last active August 29, 2015 14:20
Show Gist options
  • Save mathildathompson/57b4e2876abc5c11c63b to your computer and use it in GitHub Desktop.
Save mathildathompson/57b4e2876abc5c11c63b to your computer and use it in GitHub Desktop.

#Javascript

Scope

####Introduction When you declare a variable for the first time, you must use the var keyword, but when you update the value within the variable, you don't use the var keybord.

var pocket = ['phone', 'kindle'];
pocket = ['oysterCard', 'keys'];

Name and message are local variables to the greeting function, they are not available outside the function:

var greeting = function(name) {
  var message = 'Hello ' + name + '!';
  console.log(message); // will print because name and message are local to this function
}

console.log(message); // message not defined
console.log(greeting('Jo'); // Hello Jo! 

###Local vs. Global Scope and the 'var' keyword

//Declaring a new global greeting function
var greeting = "Hello WDI 13!";

var scoped = function(name) {
  //Declaring a new greeting function local to the scoped function (you do not have access to this variable outside the function);
  var greeting = "Hello " + name + "!";
  return greeting;
};
//The return value from calling the scoped function is stored inside the result variable. The return key word inside a function allows us to store data from that function inside global variables defined outside the function
var result = scoped("Pedro");

console.log(result); // Outputs: Hello Pedro!
console.log(greeting); // Outputs: Hello WDI 13!

###What will output to the console in the following examples?

var greeting = "Hello WDI 13!";

var scoped = function(name) {
  greeting = "Hello " + name + "!";
  return greeting;
};

var result = scoped("Pedro");

console.log(result); // Outputs: Hello Pedro!
console.log(greeting); // Outputs: Hello Pedro!

####Now consider the following code:

var x = 'outside';

var f1 = function(){
  var x = "inside f1";
  return x;
};

f1(); 
console.log(x); // Outputs: outside
var x = 'outside';

var f1 = function(){
  x = "inside f1";
  return x;
};

f1(); 
console.log(x); // Outputs: inside f1
var x = 'outside';

var f1 = function(){
  var x = "inside f1";
  return x;
};

x = f1(); 
console.log(x); // Outputs: inside f1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment