In JavaScript, all variable and function declarations are automatically moved or hoisted to the top of their current scope, regardless of where they are defined. This is a default behavior of JavaScript known as hoisting. In the following sections, we'll delve into how this mechanism operates.
Functions that are declared using function declarations are hoisted by JavaScript. This allows them to be called before they are physically defined. Let's illustrate this with an example:
// Calling function before declaration
sayHello(); // Outputs: Hello, I'm hoisted!
function sayHello() {
alert("Hello, I'm hoisted!");
}
As observed, we've invoked the sayHello()
function before defining it, yet the code functions correctly. This behavior is due to JavaScript hoisting the function declaration behind the scenes.
Similarly, variable declarations are automatically hoisted to the top of their current scope. This means that if a variable is declared inside a function block, it gets moved to the top of that function. If declared outside any function, it is hoisted to the top of the script and becomes globally accessible. Consider the following example to understand how this works:
str = "Hello World!";
alert(str); // Outputs: Hello World!
var str;
However, JavaScript hoists only declarations, not initializations. This means if you declare a variable and then initialize it after using it, the variable will be assigned a value of undefined
. See the example below:
alert(str); // Outputs: undefined
var str;
str = "Hello World!";
Here is another instance that shows how JavaScript handles variable hoisting:
var i = 1; // Declare and initialize i
alert(i + ", " + j); // Outputs: 1, undefined
var j = 2; // Declare and initialize j
var x = 5; // Declare and initialize x
var y; // Declare y
alert(x + ", " + y); // Outputs: 5, undefined
y = 10; // Initialize y
var a = 3; // Declare and initialize a
b = 6; // Initialize b
alert(a + ", " + b); // Outputs: 3, 6
var b; // Declare b
var u = 4; // Declare and initialize u
alert(u + ", " + v); // Outputs: 4, undefined
var v; // Declare v
v = 8; // Initialize v
Understanding variable hoisting might seem confusing initially, but if you carefully review these examples, you'll grasp how it functions.
Note: It's recommended to declare variables at the beginning of the current scope due to hoisting. In JavaScript strict mode, using a variable without declaration is not permitted. Check out the following chapter to delve deeper into strict mode.