This content originally appeared on Bits and Pieces - Medium and was authored by Aman
Hoisting is the process of putting all declarations, such as variables and functions, into memory during the compile phase.
One of the biggest myths around hoisting is that all variable and function declarations are moved physically to the top of your code. This is not true.
But instead, variable and function declarations are put into memory during compile phase and stay exactly where we typed them.
So exactly how are var/let/const and functions hoisted.
Here are some examples:
Variables declared with var will be hoisted and initialized with undefined. This is why when we try to console.log(a) prior to initialization, we get undefined.
Variables declared with let and const, are hoisted, but not initialized with undefined. They can be accessed only after initialization, otherwise we receive a ReferenceError. This is because of the Temporal Dead Zone, a time window where the variable exists but it still uninitialized.
But what about with functions?
Well it depends how we declare our functions. See below.
Traditional function declarations will be fully hoisted thus making function accessible throughout our code.
But with function expressions, we are unable to call a function before it has been declared. This is why the 3 functions declared with variables give us an error. In order to solve these errors, we have two options. Either change the function expression to traditional function declarations or call the function after the declarations.
Build composable applications
Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.
Bring your team to Bit Cloud to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. Give it a try →
Learn More
- How We Build Micro Frontends
- How we Build a Component Design System
- The Composable Enterprise: A Guide
- 7 Tools for Faster Frontend Development in 2022
JavaScript Interview Question: What is Hoisting? was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Aman
Aman | Sciencx (2022-03-23T09:40:25+00:00) JavaScript Interview Question: What is Hoisting?. Retrieved from https://www.scien.cx/2022/03/23/javascript-interview-question-what-is-hoisting/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.