Local Scope

Local Scope

  • Variables defined inside a function are in the local scope

  • A variable with local scope cannot be referenced outside of that function

  • Functions create their own private scope that prevents code from outside directly accessing it’s variables

Example

function showInspirationalMessage() {
  // "message" variable is declared **inside** a function which means it is LOCAL to this function

  const message = "Don't give up, you can do it!!"
  console.log(message)
}

// prints message variable
showInspirationalMessage()

/*
Now let's attempt to directly access the message variable
and log it out to the console
*/

console.log(message) // <-- Error! The variable is local to the function can cannot be "directly" accessed outside of the function

  • As you can see in this example any variables declared / defined inside of the showInspirationalMessage() function are only accessible inside showInspirationalMessage; this prevents any other code from outside of the function from directly accessing it’s variables

Local Scope with Parameters

  • Function parameters are local to the function and cannot be accessed outside of the function

Example

function squareMe(number) {
  // The "number" parameter is variable that is LOCAL to the squareMe function

  return number**2
}

const result = squareMe(7)
console.log(result)

/*
Now let's attempt to directly access the `number` parameter
*/

console.log(number) // <-- Error! The variable is local to the function can cannot be "directly" accessed outside of the function


Variables with the same name in different scopes ARE NOT THE SAME

  • Multiple variables with the same name but different scopes each will be treated as if they are distinct variables with each variable containing their own separate values

Example

// declare a variable named 'actor' in the Global Scope
const actor = "Daniel Craig"

function bestBondActor() {
  // declare a variable named 'actor' within a function (Local Scope)
  const actor  = "Sean Connery"
  return actor
}

const result = bestBondActor()
console.log(result) // <-- prints Sean Connery

/*
Now let's print out the `actor` variable
*/

console.log(actor) // <-- prints Daniel Craig