Languages
[Edit]
EN

What is scope in JavaScript?

14 points
Created by:
JustMike
26120

Scope determines the accessibility of variables. In JavaScript there are available few scopes.

1. global scopes (when variables are places direcly inside script)

var a = 123;
var b = true;

console.log(a);
console.log(b);

Output:

123
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

var a = 123;

function logNumber() {
    var a = 'text';

    console.log(a);
}

console.log(a);

Output:

text
123

3. Local scopes: curly braces scopes

Introduced in ECMAScript 6 (ES6/ES2015).

let a = 1;

{ // this brackets create new scope for let keyword variables
    let a = 2;

    console.log(a); // 2
}

console.log(a); // 1

Output:

2
1

Merged questions

  1. JavaScript - what is scope?
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join