Ep. 4 How functions work in JS ❤️ & Variable Environment - HOISTING | Namaste JavaScript
If you're new to JavaScript, you may have heard the term "hoisting" thrown around but not fully understood what it means. In this article, we'll dive into the concept of hoisting and how it affects the way your code is executed.
What is Hoisting in JavaScript?
Hoisting is a JavaScript behaviour where the interpreter moves all variable and function declarations to the top of the current scope before executing any code. This means that you can access variables and functions even before they are initialized or assigned a value.
Variable Hoisting
When it comes to variables, only the declaration is hoisted, not the definition. Variables declared with var
are hoisted, initialized, and assigned a value of undefined
. Let's take a look at an example:
console.log(x); // Output: undefined
var x = 10;
In this code, even though x
is undefined at the time of the console.log
, it's still accessible due to hoisting. However, if we remove the var
keyword, we'll get a reference error:
console.log(y); // Output: ReferenceError: y is not defined
y = 20;
This is because y
is not declared, so it can't be hoisted.
Function Hoisting
Like variables, only the declaration of functions is hoisted, not the function expression. Function declarations are hoisted to the top of their scope, which means you can call a function before it's defined in your code. For example:
greet(); // Output: Hello, World!
function greet() {
console.log("Hello, World!");
}
On the other hand, function expressions are not hoisted, and trying to call them before they are defined will result in a TypeError:
hello(); // Output: TypeError: hello is not a function
var hello = function() {
console.log("Hello, World!");
};
Arrow Functions and Hoisting
Arrow functions, unlike regular functions, do not support hoisting. They behave like normal variables and are initialized with the value of undefined
in the global memory. This means that if you try to call an arrow function before it's defined, you'll get a TypeError:
hello(); // Output: TypeError: hello is not a function
var hello = () => {
console.log("Hello, World!");
};
Conclusion
Hoisting can be a tricky concept to grasp at first, but understanding it is important for writing effective JavaScript code. Remember that only the declaration of variables and functions is hoisted, not the definition or expression. Also, arrow functions do not support hoisting, so be sure to declare them before calling them. With this knowledge, you'll be well on your way to becoming a confident JavaScript developer.
The content of this blog post was inspired by the Youtube video: How functions work in JS ❤️ & Variable Environment | Namaste JavaScript Ep. 4. It is part of the Namaste JavaScript series by Akshay Saini.