Languages
[Edit]
EN

JavaScript - what is scope?

17 points
Created by:
cory
1486

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

Alternative titles

  1. What is scope in JavaScript?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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