end video

This lesson is only accessible in the paid version of the course.

Get access to all lessons 💫 price: 34.99$

If you already have an account click here.

§ A little bit about scope in JavaScript

In this video, we will delve into the concept of scope in JavaScript and how it determines the accessibility of variables and functions in your code. We will learn about the difference between global and local scope, and how the let and const keywords can be used to declare variables with block-level scope. We will also explore the concept of function scope and how it is used to create closures.

Scope in JavaScript refers to the accessibility of variables, functions, and objects in certain parts of your code during runtime. In JavaScript, there are two types of scope: global scope and local scope.

A variable defined in the global scope is accessible from anywhere in the code, both inside and outside of functions. For example:

let globalVariable = "I am a global variable";

function myFunction() {
  console.log(globalVariable); // "I am a global variable"
}
console.log(globalVariable); // "I am a global variable"

On the other hand, a variable defined within a function is only accessible within that function and is said to have a local scope. In JavaScript, when a variable is defined within a function, it is only accessible within that function and any inner functions, but not from the outside:

function myFunction() {
  let localVariable = "I am a local variable";
  console.log(localVariable); // "I am a local variable"
}
console.log(localVariable); // ReferenceError: localVariable is not defined

Additionally, there is also block-level scope introduced in ES6 with the let and const keyword, which allows you to define a variable that is only accessible within the block it is defined in, for example inside a for-loop or an if-statement. These are similar to the function-level scope in the sense that they are not accessible outside the block they are defined in. For example:

if (true) {
  let blockVariable = "I am a block variable";
}
console.log(blockVariable); // ReferenceError: blockVariable is not defined

In summary, the scope in javascript determines the accessibility and lifetime of variables, functions and objects. Understanding the concept of scope is important in order to be able to write maintainable and efficient code.

questionnaire

Practice

Practice is the fastest way to learn knowledge permanently. I have prepared a small task for you related to the lesson.

Practice
discussion

Materials

Materials related to the lesson:
Files associated with the lesson

Materials

Next: Hoisting(04:44)

To the lesson →