
Hoisting
in JavaScript.Hoisting in JavaScript:
var
, let
, const
) and function declarations to the top of their scope before code execution. This means that declarations are moved to the top during compilation, allowing you to use variables or functions before they are declared in the code.undefined
.Example:
console.log(x); // undefined var x = 5; console.log(x); // 5
var x
is hoisted to the top, but the assignment remains in place. That's why the first console.log(x)
outputs undefined
.Understanding Hoisting
var x; console.log(x); // undefined x = 5; console.log(x); // 5
Hoisting with Functions
sayHello(); // "Hello, world!" function sayHello() { console.log("Hello, world!"); }
sayHello
function is hoisted to the top, so you can call it before its declaration.Hoisting with Let and Const
let
and const
are also hoisted, but they are placed in a "Temporal Dead Zone" (TDZ). This means that while the declaration is hoisted, the variable cannot be accessed until it is initialized, resulting in an error if you try to use it too early.console.log(y); // ReferenceError: Cannot access 'y' before initialization let y = 10;
y
variable is hoisted but remains in the TDZ, causing an error when accessed before initialization.Similar Articles
Main features of Reactjs
In this article, we will learn about the key features of React.js, which will also be useful for interview questions.
August 21, 2024Destructuring assignment in JavaScript
In today's article, we will explore in detail another important JavaScript syntax: Destructuring assignment.
August 17, 2024First Class Function in JavaScript
Hello friends. In today's post, we'll go into detail about another important concept in JavaScript that plays a crucial role First Class Functions!
August 14, 2024What is React js? What role does React play in software development?
Today, we'll discuss React.js, one of the top JavaScript libraries, including its advantages, what we can do with it, and everything else you need to know in this post.
August 20, 2024What is an SPA (Single Page Application)?
Let's explore what an SPA (Single Page Application) is, which is used in today's modern websites.
August 29, 2024What is the DOM? What is the difference between HTML and the DOM?
In today’s post, we’ll discuss what the DOM (Document Object Model) is and the differences between HTML and the DOM.
August 31, 2024