Exercises: JavaScript Variable Scope
Standard Exercises
0. Create a function called countUp() that adds one to a global variable called ‘counter’. Check it with the following code.
var counter = 0;
countUp();
countUp();
console.log(counter); // Should print 21. Figure out what value will be printed out by the console.log commands and then try it for yourself.
var name = "John";
function doSomething() { name = "Alex"; }
console.log(name);
doSomething();
console.log(name);2. What is wrong with the following code (tip: Run it in the console to find out!)?
function doSomething() { name = "Alex"; }
console.log(name);3. What is wrong with the following code (tip: Run it to see what value of ‘name’ is printed out!)?
var name = "John";
function updateGlobalName() {
var name = "Alex";
}
console.log(name);console.log("Hello World");
Hint: Alternatively, just hold "shift" and press "enter" to run your code.