Variables and functions are the most common things we use everyday in a programming language. Almost all the programming languages have the same idea when declaring variables and functions except JavaScript. JavaScript likes to handle things little differently.
In other programming languages such as java, PHP, c++ when you declare a variable or function you define it before calling the function or using a variable.
$x;
$x = 'some value';
In php you can declare a variable like above and can use it for your own purpose but you don’t have to do the same thing in javascript. You can do something like this
x = 5;
var x;
This code is completely fine and works perfectly in JavaScript but it will not be the same in any other languages. This is possible in JavaScript and this is called hoisting.
Simply saying taking all your variables and functions and putting them at the top.
This would be the definitions you would have fined on most of the websites but that is not what actually happens under the hood exactly.
JavaScript has two steps in executing a particular script.
1.The First step is creation. 2. Then the execution of the code.
In the first step JavaScript analyses all the code and allocate the memory spaces for variables and functions. All the variables are assigned a value of undefined when declared first.
console.log(x); // This would print undefined
x = 5;
var x;
undefined is a primitive type in JavaScript and all the variables are given a value of undefined when declared.
Function Hoisting
Like variables functions are also hoisted in JavaScript. So even if you write a function definition at the end of the line and call it in the first line of code , it will work without any issues.
hello(); // output will be Hello, Welcome to my blog!
function hello() {
console.log("Hello, Welcome to my blog!");
}
sayHello(); // This would return undefined
var sayHello = function () {
console.log("hello");
};
The last function definition will not execute since it is defined as a function expression with a variable and all variables will be assigned with undefined before any assignment happen in script