Skip to content

Latest commit

 

History

History
101 lines (67 loc) · 2.46 KB

File metadata and controls

101 lines (67 loc) · 2.46 KB

04 Scopes

Scope determines where variables can be accessed or used in a JavaScript program. It defines the visibility and lifetime of variables and functions.

In JavaScript, scope controls where a variable is available and where it is not.

04.1 Global Scope

Variables declared outside of any function or block are in the global scope. They can be accessed from anywhere in the program.

let myGlobal = 10; // Global variable

const myFunc = () => {
  oopsGlobal = 5; // Not using var, let, or const makes the variable global
};

const myFuncTwo = () => {
  let myOutput = "";

  if (typeof myGlobal !== "undefined") {
    myOutput += `myGlobal: ${myGlobal}\n`; // myGlobal: 10
  }

  if (typeof oopsGlobal !== "undefined") {
    myOutput += `oopsGlobal: ${oopsGlobal}`; // oopsGlobal: 5
  }

  console.log(myOutput);
};

myFunc();
myFuncTwo();

Note: In strict mode, assigning a variable without var, let, or const throws an error.

Strict Mode

Strict mode helps you catch common coding mistakes and unsafe actions early by turning them into errors. You can enable strict mode by adding "use strict" at the top of a JavaScript file or at the beginning of a function.

04.2 Function Scope

Variables declared inside a function are function-scoped and can only be accessed within that function.

const myFunc = () => {
  var myVar = 5;
  console.log(myVar); // 5
};

console.log(myVar); // ReferenceError: myVar is not defined

Note: Variables declared with var follow function scope, not block scope.

04.3 Block Scope

Variables declared using let and const inside a block {} are block-scoped. They are only accessible within that block.

if (true) {
  let age = 25;
  console.log(age); // 25
}

console.log(age); // ReferenceError

04.4 Lexical Scope

Lexical scope means that inner functions can access variables from their outer scope. Scope is determined by where the code is written, not where it is executed.

const outer = () => {
  let count = 10;

  function inner() {
    console.log(count);
  }

  inner();
};

outer(); // 10

Global vs Local Scope

When the same variable name is used in both global and local scope, the local scope variable takes precedence over the global variable.

let value = 10;

if (true) {
  let value = 20; // Takes precedence over global scope
  console.log(value); // 20
}

console.log(value); // 10