// Variables declared in global scope (Window)
var x = 5;
y = 10;
// Objects are no different
// It's all global here
var myObj = {
name: "Mr. Object",
x: x // i can access variables in my scope
}
// Typical blocks do not affect scope
if (x<10) {
// z becomes global
// x is in my scope
var z = 20 + x;
}
console.group("From global");
console.log("x:", x);
console.log("y:",y);
console.log("myObj:",myObj);
console.groupEnd();
// Only a function defines a new scope
function foo(fooVar) {
// the "x" here is in this function's scope, not global
// there now exists two "x" variables in this program (shadowed)
var x = 222;
// I cannot access Function bar's barVar from here
console.group("From foo");
console.log("x:",x);
//console.log(barVar); // ReferenceError
console.log("y:",y);
console.groupEnd();
function bar(barVar) {
// But from here I can access everything
// below me in the scope chain
// (Except shadowed variables)
console.group("From bar");
console.log("barVar:",barVar); // from my scope
console.log("fooVar:",fooVar); // from my parent scope, foo's scope
console.log("x:",x); // shadowed in foo's scope
console.log("y:",y); // from global scope
console.groupEnd();
}
bar("Mr. Bar");
}
foo("Mr. Foo");
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.