JS: undefined | JavaScript

JavaScript undefined

A uninitialized variable is undefined.

var v; console.log(typeof v); undefined

Value of a variable is undefined until set. This can also be said that undefined is the default value of a variable when declared only.

var v; console.log('old:', typeof v); v = 'PiTribe'; console.log('new:', typeof v); old: undefined new: PiTribe

undefined refers an uninitialized variable.

undefined can be assigned to a variable, explicitly.

var v; console.log('old:', typeof v); v = 'PiTribe'; console.log('new:', typeof v); v = undefined; console.log('last:', typeof v); old: undefined new: PiTribe last: undefined

undefined is falsy

undefined is a falsy in logical comparisions.

var v; //v is undefined if(v) alert('Truly'); else alert('Falsy'); Falsy
undefined implies that the variable is virgin. A variable can be set to undefined again later in the program, there is no prohibtion.

undefined as null

undefined is truly (true) with double equal == operator.

var v; //v is undefined if(v == null) alert('Truly'); else alert('Falsy'); Truly

This is because JavaScript cast/convert true to null. But this is not the case with tripple equal === operator.

var v; //v is undefined if(v === null) alert('Truly'); else alert('Falsy'); Falsy

undefined with arithmetic operations

Arithmetic operations with undefined result NaN i.e. +, -, /, * & % operators etc.

var v; //v is undefined var u = v + 1; alert (u); NaN

This is because JavaScript cast/convert true to null. But this is not the ase with tripple equal === operator.

Notes

  1. undefined is the default value of an uninitialized variable
  2. undefined behaves as false in logical operations