EN
JavaScript - what is scope?
17
points
Scope determines the accessibility of variables. In JavaScript there are available few scopes.
1. global scopes (when variables are places direcly inside script)
// ONLINE-RUNNER:browser;
var a = 123;
var b = true;
console.log(a); // 123
console.log(b); // true
Note: there is alternative way to create and access global variables:
- NodeJS JavaScript:global.c = 'global variable'; console.log(c); console.log(global.c);
- WebBrowser JavaScript:
// ONLINE-RUNNER:browser; <html> <body> <script> window.c = 'global variable'; console.log(c); console.log(window.c); </script> </body> </html>
2. Local scopes: Function scopes
// ONLINE-RUNNER:browser;
var a = 123;
function logNumber() {
var a = 'text';
console.log(a);
}
logNumber(); // text
console.log(a); // 123
3. Local scopes: curly braces scopes
That scope works with let
and const
variables (it was introduced in ECMAScript 6 (ES6/ES2015)).
// ONLINE-RUNNER:browser;
let a = 1;
{ // this brackets create new scope for let keyword variables
let a = 2;
console.log(a); // 2
}
console.log(a); // 1