Languages
[Edit]
EN

What is scope in JavaScript?

14 points
Created by:
JustMike
3497

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?
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.