#Javascript
####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
var greeting = "Hello WDI 13!";
var scoped = function(name) {
var greeting = "Hello " + name + "!";
return greeting;
};
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