JavaScript by Patrik

JavaScript Scope

JavaScript scope refers to the context in which variables, functions, and objects are defined. It determines the accessibility and visibility of these elements within the code. Understanding scope is crucial for writing maintainable and error-free JavaScript code.

JavaScript has three types of scope:

  • Block scope
  • Function scope
  • Global scope
...see more

Before ES6 (2015), JavaScript had only Global Scope and Function Scope.

ES6 introduced two important new JavaScript keywords: let and const.

These two keywords provide Block Scope in JavaScript.

Variables declared inside a { } block cannot be accessed from outside the block.

{
  let x = 2;
}
// x can NOT be used here
...see more

JavaScript has function scope: Each function creates a new scope.

Variables defined inside a function are not accessible (visible) from outside the function.

Variables declared with varlet and const are quite similar when declared inside a function.

function varFunction() {
  var message = "Hello";   // Function Scope
}
function letFunction() {
  let message = "Hello";   // Function Scope
}
function constFunction() {
  const message = "Hello";   // Function Scope
}
...see more

Variables declared Globally (outside any function) have Global Scope.

Global variables can be accessed from anywhere in a JavaScript program.

Variables declared with varlet and const are quite similar when declared outside a block.

var x = 2;       // Global scope
let x = 2;       // Global scope
const x = 2;       // Global scope

Comments

Leave a Comment

All fields are required. Your email address will not be published.