2012-04-14 08:55:14Morris

[JavaScript] Variables in functions

var greeting = "Ahoy";

var greeting = "Ahoy";
var greet = function() {
    console.log(greeting);
};
greet();

var greeting = "Ahoy";

var greet = function () {
  // Local greeting variable.
  var greeting = "Hello";
  console.log(greeting);
};

greet();


var greeting = "Ahoy";

var greet = function () {
  // Local greeting variable.
  var greeting = "Hello";
  console.log(greeting);
};

greet();
console.log(greeting);

var sayHelloTo = function (name) {
  console.log("Hello " + name);
};

sayHelloTo("Amjad");
sayHelloTo("Morris");

/* Start global variable `greeting` scope */
var greeting = "Ahoy";

var greet = function () {
  /* Start local variable `greeting` scope */
  var greeting = "Hello";
 
  /* Start local variable `myName` scope */
  var myName = prompt("Input your name: ");
 
  console.log(greeting + " " + myName);
 
  /* End local variables `myName` and `greeting` scope */
};

greet();

// This will produce a `ReferenceError` since we are out
// of the `myName` variable scope.
console.log(myName);