Undefined in JavaScript

undefined in javascript

We all know about undefined most of time we found undefined error in our browser console. Developer got confuse when it comes and why its coming.

Before we start to learn why its coming lets learn what is Undefined in JavaScript.

undefined is a property of the global object, The initial value of undefined is the primitive value undefined.

We get undefined in console for three reasons.

When value is not initialized.

Known behavior for undefined is whenever we create a variable and is not assigned anything into it, It has undefined.

Example:

<script>
  function myFunction() {    
    var x;    
    document.getElementById("demo").innerHTML = typeof(x);
  }
  myFunction();
</script>

When we return nothing from function

By default like variable every function has return type of undefined. Means if we have not mentioned return statement in our function and we print it in control will shows error.

Example

<!DOCTYPE html>
<html>
  <body>  
    <h1 id="i">This is a Heading</h1>  
    <script>    
      function g() {      
        var x = 20;      
        return x;  // Comment this line to see undefined result    
      }    
      document.getElementById("i").innerText = g();  
    </script>
  </body>
</html>

In Above example we can find the value X is print as 20, because we return the value of X to document.

now comment the line return in your code and see the result. This behavior is default in function.

When property is not exist in function.

When we create function we create variable to assign, calculate and print the values. While printing if we use variable that is not exist in local scope JavaScript will try to find out that variable into global scope. If its available there it will print the value. But if that variable is also not available in global scope that will gives error that is undefined and your application will breaks.

Please refer to below example.

Example

<!DOCTYPE html>
<html>
  <head>  
    <title>Page Title</title>
  </head>
  <body>  
    <h1 id="x">This is a Heading</h1>  
    <h1 id="i">This is a Heading</h1>  
    <script>    
      var x = 20;    
      function g() {      
        document.getElementById("x").innerText = x; // 20 which is Global Variable       
        document.getElementById("i").innerText = msg; // Gives error because msg is not available in Local scope as well as in Global Scope    
      }    
      g();  
    </script>
  </body>
</html>