Can I use a JavaScript variable before it is declared?



Yes, you can use a JavaScript variable before it is declared, with a technique called hoisting. The parser reads through the complete function before running it.

The behavior in which a variable appears to be used before it's declared is known as hoisting.

For example, the following,

rank = 5;
var rank;

The above works the same as the following −

var rank;
rank = 2;

Hoisting in JavaScript, allows us to declare variables, functions, or classes that are moved to the top of the scope preceding the execution of the code regardless of whether their scope is local or global.

JavaScript allocates memory for all the variables and functions before their execution. Note that hoisting means, declaring not initializations.

By being variables and functions used before they are declared in the code, there is a chance to get unexpected errors. So, hoisting is not recommended use. Hoisting will work differently with var, let, and const. We can check the below in detail.

First, we will check examples of hoisting with var. Later we will check in detail about variable hoisting.

Example

<!DOCTYPE html>
<html>
<body>
   <h4>Hoisting Example</h4>
   <p id="output"></p>
   <script>
      x = 10; // Assign 5 to x
      document.getElementById("output").innerHTML = x;
      var x; // Declare x
   </script>
</body>
</html> 

Here, we can see that we have used the x variable before it is declared.

Now, we will check JavaScript hoists only declarations but not initializations. Let's see another example

Example

<!DOCTYPE html>
<html>
   <body>
   <h3>Hoists only declarations</h3>
   <p id="output"></p>
   <script>
      x = 10; // initialize x
      document.getElementById("output").innerHTML = x + " , " + y;
      var x; // declare x
      var y = 20; // declare and initialize y
   </script>
</body>
</html> 

Here, we can check hoisting means y needs to be initialized before it is used. But y is not initialized. So, this is not hoisted. That's why the y value is undefined. We can write properly as mentioned in example 1.

Example

<!DOCTYPE html>
<html>
<body>
   <h1>Hoists only declarations</h1>
   <p id="output"></p>
   <script>
      var x = 10; // Initialize x
      var y; // declare y
      document.getElementById("output").innerHTML = x + " , " + y;
      y = 20; // Initialize y
   </script>
</body>
</html> 

Here, the variable y is declared but not initialized before we display.

JavaScript only hoists declaration, not initialization.

Always note that, in the background, JavaScript first declares the variables and initializes value to them. In JS, undeclared variables do not exist until the assigned code is executed. So, undeclared variables are considered global variables when the assignment code is executed. Let's look deeper into variable hoisting.

let and const hoisting

We all know let and, const are block scoped not function scoped. The let and const are introduced in ES6. We know ES6 will not allow undeclared values. If we try to use variables before the declaration, it will throw a reference error. Unlike var, variables are not initialized with the default value. Let's see an example

Example

<!DOCTYPE html>
<html>
<body>
   <h3>Hoisting with let</h3>
   <p id="output"></p>
   <script>
      try{
         document.getElementById("output").innerHTML = x;
         let x = "Hi";
      } catch(err) {
         document.getElementById("output").innerHTML = err;
      }
   </script>
</body>
</html>

Here, we can observe that we are trying to access x value before its declaration. Let's see another example with let.

Example

<!DOCTYPE html>
<html>
<body>
   <h2>Hoisting with let</h2>
   <p id="result1"></p>
   <p id="result2"></p>
   <script>
      let x;
      document.getElementById("result1").innerHTML = x;
      x = 5;
      document.getElementById("result2").innerHTML = x;
   </script>
</body>
</html>

Now, let's check with const

Hoisting with const

Like let, we can't use variables before the declaration, and also we can not only declare variables but also need to initialize the value to them. Otherwise, it will throw a SyntaxError error. Let's see an example

Example

<!DOCTYPE html>
<html>
<body>
   <h1>Hoisting with const</h1>
   <p> It will throw Uncaought SyntaxError: Missing initializer in const declaration </p>
   <p> To see this error please open the Console of the browser </p>
   <p id="output"></p>
   <script>
      const x;
      document.getElementById("output").innerHTML = x;
      x = 5;
      document.write(x);
   </script>
</body>
</html> 

We need to initialize the value while doing the declaration.

Example

<!DOCTYPE html>
<html>
<body>
   <h2>Hoisting with const</h2>
   <p id="output"></p>
   <script>
      try{
         document.getElementById("output").innerHTML = x;
         const x = 5;
      }catch(err){
         document.getElementById("output").innerHTML = err;
      }
   </script>
</body>
</html> 

Like, the above example is also not possible with const. It will throw a reference error.

Now, let's see hoisting with functions.

Function hoisting

Function hoisting allows us to call a function before it is defined. Let's see an example

Example

<!DOCTYPE html>
<html>
<body>
   <h2>Hoisting with function</h2>
   <p id="output"></p>
   <script>
      getName("Devika");
      function getName(name) {
         document.getElementById("output").innerHTML = ("Employee name is " + name);
      }
   </script>
</body>
</html> 

If the function expressions assigned to the variables. An output will depend on variable scope. Like,

Example

<!DOCTYPE html>
<html>
<body>
   <h2>Hoisting with function as var</h2>
   <p id="output"></p>
   <script>
      try{
         getName("Devika");
         var getName = function (name) {
         document.getElementById("output").innerHTML = ("Employee name is " + name);
      }
      }catch(err){
         document.getElementById("output").innerHTML = err;
      }
   </script>
</body>
</html>

Example

<!DOCTYPE html>
<html>
<body>
   <h2>Hoisting with function as let</h2>
   <p id="output"></p>
   <script>
      try{
         getName("Devika");
         let getName = function (name) {
            document.getElementById("output").innerHTML = ("Employee name is " + name);
         }
      }catch(err){
         document.getElementById("output").innerHTML = err;
      }
   </script>
</body>
</html>

Example

<!DOCTYPE html>
<html>
<body>
   <h2>Hoisting with function as const</h2>
   <p id="output"></p>
   <script>
      try{
         getName("Devika");
         const getName = function (name) {
            document.getElementById("output").innerHTML = ("Employee name is " + name);
         }
      }catch(err){
         document.getElementById("output").innerHTML = err;
      }
   </script>
</body>
</html>

Here we can observe, that functions with variables will work differently. If we assign function expressions as var, we are getting TypeError, and with let and const, we are getting ReferenceError.

However, using functions before their declarations is our personal matter of preference.

Hope this tutorial will give knowledge on hoisting in js and hoisting works with variables and functions.


Advertisements