Skip to content
SimonPlanje edited this page Jun 21, 2020 · 6 revisions

Scopes

There are 2 kinds of scopes the global and the local scope.
Inkedscope_cookiemonster

Global scope

Are variable lives in the global scope when is it defined outside of a function or in curly braces. Onces you have declared a variable in the global scope, you can use it anywhere even in functions.
The parent shares his cookies with his child. :)

Sometimes it is not always the best decision to call all the variables in the global scope because you can run into the issue that you declare two variables with the same name, for example:

Don't do this!
let thing = 'something'
let thing = 'something else' // Error, thing has already been declared

DON'T DECLARE YOUR VARIABLE WITH VAR!
When a variable is declared with var you will overwrite the value of this variable when you declare the variable with the same name again. This makes your code hard to debug. So always use local variables, not global variables.

// Don't do this!
var thing = 'something'
var thing = 'something else' // perhaps somewhere totally different in your code
console.log(thing) // 'something else'

Local scope

Variables that only can be used locally in a specific part of your code are called local variables. They are like the child variables that don't share their cookies with their parents.

In JavaScript there are two kinds of local scope:

  • Function scope
  • Block scope

Function scope

When a variable is declared inside a function it is not possible to access this variable outside this function. The variable can only be used inside the function it is declared in.

function sayHello () {
const hello = 'Hello CSS-Tricks Reader!'
console.log(hello)
}

sayHello() // 'Hello CSS-Tricks Reader!'
console.log(hello) // Error, hello is not defined

Block scope

When you declare a variable within curly brackets, you can access this variable within these curly brackets.
{
const hello = 'Hello CSS-Tricks Reader!'
console.log(hello) // 'Hello CSS-Tricks Reader!'
}

console.log(hello) // Error, hello is not defined

Sources

Clone this wiki locally