Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

What is scope in JavaScript?

0 contributions
14 points

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?
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more