

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Function hoisting in JavaScript
Hoisting is a JavaScript technique which moves variables and function declarations to the top of their scope before code execution begins. Within a scope no matter where functions or variables are declared, they're moved to the top of their scope.
Note that hoisting only moves the declaration while assignments are left in place.
Example
console.log(functionBelow("Hello")); function functionBelow(greet) { return `${greet} world`; } console.log(functionBelow("Hi"));
Output
Hello world Hi world
Note that the function declaration was after it was called but was still called. This was possible due to function hoisting.
Also note that it doesn't work when you assign functions like variables.
console.log(functionBelow("Hello")); var functionBelow = function(greet) { return `${greet} world`; } console.log(functionBelow("Hi"));
This will fail with an error: functionBelow is not a function
If you remove var, it'll fail with the error: functionBelow is not defined
Note that when it was declared with var, it was hoisted as a variable in the context. But it still remained undefined. This is known as variable hoisting. Due to this property, anonymous and arrow functions are never hoisted in JavaScript.
- Related Questions & Answers
- Variable Hoisting in JavaScript
- Explain hoisting in JavaScript
- Function returning another function in JavaScript
- ArrayBuffer.isView() function in JavaScript
- ArrayBuffer.slice() function in JavaScript
- Atomics.add() function in JavaScript
- Atomics.and() function in JavaScript
- Atomics.or() function in JavaScript
- Atomics.isLockFree() function in JavaScript
- Atomics.load() function in JavaScript
- Atomics.store() function in JavaScript
- Atomics.sub() function in JavaScript
- DataView.setUint16() function in JavaScript
- DataView.setUint32() function in JavaScript
- Date.UTC() function in JavaScript