logo javascript

Javascript Course for Beginners

Instructor: Ivan Lourenço Gomes

Null and Undefined

Variables not always have values. Null and Undefined represent the lack of value.

Undefined

When we create a variable but do not assign any value to it. Its value and data type becomes undefined.

                    

    var noValue;
    console.log(noValue); // undefined
    console.log(typeof noValue); // undefined

                    
                

Undefined can also appear on other cases, for example when we try to access an index that does not exist in a string:

                    

    var name = "Peter";
    console.log(name[0]); // Console will show "P"
    console.log(name[4]); // Console will show "r"
    console.log(name[10]); // Console will show undefined


                    
                

When we talk about arrays and objects we'll see that:

  • Like strings, arrays have a length and each of their elements have an index from which we can access them. When we try to access an index that does not exist, we'll get the value of undefined.

  • Objects have properties. A car object might have "Manufacturer" or "Name" properties but probably not an "Email" property. If we try to get a non-existent property of an object, we'll get the value of undefined.
  • Null

    Null is not exactly a data type and for many people it should be avoided.

    Null is normally used to reset the value of a variable that had a value previously:

                        
    
        var temperature = 35;
        console.log(temperature);
    
        temperature = null;
        console.log(temperature); // The console will show null
        console.log(typeof temperature); // The console will show object - which could be misleading
        
                        
                    

    However, the same can be done with undefined:

                        
    
        var temperature = 35;
        console.log(temperature);
    
        temperature = undefined;
        console.log(temperature); // The console will show undefined
        
                        
                    

    In fact, Javascript even consider null and undefined to be equal:

                        
    
        console.log(undefined == null);  // The console will show true
    
                        
                    

    Some people probably just use it to differentiate when a value has never been assigned to a variable and when its value has just been reset.

    In our examples we'll leave null aside and use undefined when needed.

    Contents