-
Notifications
You must be signed in to change notification settings - Fork 0
Scope
There are 2 kinds of scopes the global and the local 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'
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
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
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
-
LearnCode.academy. (2014, 24 juli). Javascript Scope Tutorial - What Makes Javascript Weird...and Awesome Pt 4 [Video]. YouTube. https://www.youtube.com/watch?v=SBwoFkRjZvE
-
Liew, Z. (2019, 16 januari). JavaScript Scope and Closures. CSS-Tricks. https://css-tricks.com/javascript-scope-closures/
-
MDN contributors. (2020, 12 februari). Scope. MDN Web Docs. https://developer.mozilla.org/en-US/docs/Glossary/Scope
-
W3Schools. (z.d.). JavaScript Scope. Geraadpleegd 25 mei 2020, van https://www.w3schools.com/js/js_scope.asp
Simon Planje 20/06/2020
