Languages
[Edit]
EN

JavaScript - what is scope?

14 points
Created by:
cory
286

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:

<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

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
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join