Skip to content

Instantly share code, notes, and snippets.

@shreshthmohan
Created February 12, 2018 14:49
Show Gist options
  • Save shreshthmohan/e4c0658a45142d81c2342681538a06b2 to your computer and use it in GitHub Desktop.
Save shreshthmohan/e4c0658a45142d81c2342681538a06b2 to your computer and use it in GitHub Desktop.
Undeclared? // source http://jsbin.com/qeyebah
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Undeclared?</title>
</head>
<body>
<script id="jsbin-javascript">
console.log('f = 15;');
f = 15;
console.log(f);
console.log('shouldn\'t this have returned some error?');
console.log('Looks like it\'s equivalent to writing:');
console.log('this.f = 15;');
console.log('Since \'this\' is created in the global execution context by JS engine on its own, it\'s valid JS. Makes sense?');
console.log('function test() {\n g = 14;\n}; \ntest();\nconsole.log(g);');
function test() {
g = 14;
}
test();
console.log(g);
console.log('The above works too. Why you ask? Again because when the syntax parser doesn\'t see a var/const/let before a variable it defaults to global scope.')
</script>
<script id="jsbin-source-javascript" type="text/javascript">console.log('f = 15;');
f = 15;
console.log(f);
console.log('shouldn\'t this have returned some error?');
console.log('Looks like it\'s equivalent to writing:');
console.log('this.f = 15;');
console.log('Since \'this\' is created in the global execution context by JS engine on its own, it\'s valid JS. Makes sense?');
console.log('function test() {\n g = 14;\n}; \ntest();\nconsole.log(g);');
function test() {
g = 14;
}
test();
console.log(g);
console.log('The above works too. Why you ask? Again because when the syntax parser doesn\'t see a var/const/let before a variable it defaults to global scope.') </script></body>
</html>
console.log('f = 15;');
f = 15;
console.log(f);
console.log('shouldn\'t this have returned some error?');
console.log('Looks like it\'s equivalent to writing:');
console.log('this.f = 15;');
console.log('Since \'this\' is created in the global execution context by JS engine on its own, it\'s valid JS. Makes sense?');
console.log('function test() {\n g = 14;\n}; \ntest();\nconsole.log(g);');
function test() {
g = 14;
}
test();
console.log(g);
console.log('The above works too. Why you ask? Again because when the syntax parser doesn\'t see a var/const/let before a variable it defaults to global scope.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment