GV.

Saturday, January 27 2018

Defining the undefined in JavaScript

JavaScript seems simple enough at the first sight, but when you start writing code you’ll find weird bugs you don’t understand in your initial stage with JavaScript. One of the weirdness you will find is variable or method is undefined.

Uncaught TypeError: Cannot read property ‘get’ of undefined at :1:3

So what is undefined?

Undefined is a primitive value used when a variable has not been assigned a value.

Simply saying, when you create a variable and leave it without assigning a value to it, JavaScript will automatically assign a value called undefined.

var x; //undefined

In this stage, your variable is created by the JavaScript engine but not assigned any value by you.When you try to console log it, It will output undefined.

console.log(x); // undefined

undefined is a primitive type in JavaScript. If you try to see the typeof a variable with undefined will output undefined.

typeof x; // 'undefined'

That’s all for undefined in JavaScript but some people may think ‘undefined is like null in other programming languages’. Well not true in the case of JavaScript. JavaScript has null type but it is a typeof object. So when you assign null to a variable JavaScript wont throw any undefined error.

var y = null;
typeof y;
//"object"
null === undefined; // false

On a side note, JavaScript will throw you a not defined error when try to access a variable that you haven’t declared.

console.log(notdefined);
Uncaught ReferenceError: notdefined is not defined
    at <anonymous>:1:1