Hey reader👋 Hope you are doing well😊
In the last post we have talked about about Math library, RegEx and destructuring in JavaScript. In this post we are going to know about hoisting and interpolation in JavaScript.
So let’s get started🔥
Hoisting in JavaScript
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compilation phase. This means that you can use variables and functions before you declare them in your code.
So here you can see that we can use x
before it is declared this is what hoisting is.
Hoisting of variables
For variables declared using var, the declaration is hoisted to the top, but the initialization stays in place. Until the code execution reaches the line where the variable is initialized, it will have a value of undefined
.
For variables declared using let
and const
, the declarations are also hoisted, but they are not initialized. Accessing them before their declaration results in a ReferenceError
.
Function Hoisting
Function declarations are hoisted entirely, including their definitions. This means you can call a function before you declare it in the code.
However, function expressions (both regular and arrow functions) are treated like variables and only the variable declaration is hoisted, not the assignment.
Interpolation in JavaScript
String interpolation is a great programming language feature that allows injecting variables, function calls, and arithmetic expressions directly into a string. String interpolation was absent in JavaScript before ES6.
Let’s see how string concatenation works-:
Here you can see that we can easily use variables in string by just concatenating them to the string. But this becomes very complex and tedious with large strings. This is why interpolation that is use of `(backticks) and $ {expression} were introduced in ES6.
” “` and complex concatenation.
Let's see the above code using interpolation-:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jasrhsm5rkiivxe4f4tk.png)
You can see that now we don't have to worry with adding whitespaces like
Interpolation is just use of JavaScript expression in string.
You can see that how we are easily using ternary expression in string using interpolation.
So this was it for this blog. I hope you have understood it well. In the later blogs we are going to see some more important concepts of JavaScript. Till then stay connected and don’t forget to follow me.
Thankyou 🩵