Skip to content
ParvinBDJ edited this page Jun 20, 2020 · 3 revisions

Scope

Today I am going to explain the concept: Scope. A scope is the range of how far something reaches. You have 2 kinds of scopes.

  1. Local Scope
  2. Global Scope

Local scope

Local scope is the scope created when you are within a function, the local scope doesn't give her variables to the global scope. Let's say you create a variable within a function (which automatically is local within the local scope of that particular function). This variable created within the function can not be used outside of the function (so in the global scope). Let me show you an example:

function localScope(){
  var hello = "Hello Stranger!"; // creating a variable within the local scope
}
console.log(hello);
// -> undefined
// This is because it is defined in the local scope and the local scope doesn't give his functions
// to the global scope

Global scope

This is the scope where you write all your code (if it isn't within a function). If you write anything in the global scope every local scope within your project can use that. Let's say you create a variable within the global scope and you try to console log that. That should work.

var hello = "Hello Stranger!"; // creating a variable within the global scope

function localScope(){
  console.log(hello);
  // -> Hello Stranger!
  // This works because the local scope can use everything within the global scope
}

And it does! Now you should know what a scope is and what kinds of scopes there are.

Sources

Clone this wiki locally