Skip to content

Instantly share code, notes, and snippets.

View lenafaure's full-sized avatar

Lena Faure lenafaure

View GitHub Profile
@lenafaure
lenafaure / local_global_scope.js
Last active July 5, 2017 13:21
Local and global variable scope
var greeting = "Hi, I am a global variable"; // global scope variable
function sayHello() {
var greeting = "Hi, I am a local variable"; // local scope variable
console.log(greeting);
}
sayHello(); // Prints "Hi, I am a local variable"
console.log(greeting); // Prints "Hi, I am a global variable"
var businessStar = “Gary Vaynerchuck”;
function businessStar(){
  console.log(“Gary Vaynerchuck”);
}
console.log(businessStar); // Prints “Gary Vaynerchuck”
var businessStar;
function businessStar(){
  console.log(“Gary Vaynerchuck”);
}
console.log(businessStar); // Prints “function businessStar(){ console.log(“Gary Vaynerchuck”);}”
var movieStar = function () {
  var name = “Philip Seymour Hoffman”;
  console.log(name); 
}
movieStar(); // Prints “Philipp Seymour Hoffman”
movieStar(); // Prints “TypeError : movieStar is not a function”
var movieStar = function () {  // This is a function expression and therefore not hoisted
  var name = “Philip Seymour Hoffman”;
  console.log(name); 
}
function movieStar() { // function declaration is moved to the top of the global scope
  var name; // variable declaration is moved to the top of the local scope 
  name = “Meryl Streep”; // variable assignement is left in place
  console.log(name);
}
movieStar(); // Prints “Meryl Streep”
movieStar();
function movieStar() {
  var name = “Meryl Streep”;
  console.log(name);
}
var rockStar;
console.log(rockStar);
rockStar = “Mick Jagger”;
var rockStar;
rockStar = “Mick Jagger”;
console.log(rockStar); // Prints “undefined”
var rockStar = “Mick Jagger”;