1. Home
  2. >
  3. Undefined vs null in javascript
3

Undefined vs null in javascript
rahoolbenji

Before understanding the differences, let us understand the similarities between undefined and null

  1. They belong to javascript 7 primitive types ('string','number','null','undefined','boolean','symbol', 'bigint')
  2. They are falsy values. Values that evaluated to false when converting it to boolean using Boolean(value) or !!value.

Differences:

  • undefined is the default value of a variable that has not been assigned a specific value. Or a function that has no explicit return value ex. console.log(1). 
  • null is "a value that represents no value". null is value that has been explicitly defined to a variable. 
// Similarities

console.log(!!null); //logs false
console.log(!!undefined); //logs false

console.log(Boolean(null)); //logs false
console.log(Boolean(undefined)); //logs false


// Differences 
// Undefined
let _thisIsUndefined;
  const doNothing = () => {};
  const someObj = {
    a : "ay",
    b : "bee",
    c : "si"
  };

  console.log(_thisIsUndefined); //logs undefined
  console.log(doNothing()); //logs undefined
  console.log(someObj["d"]); //logs undefined

//null
fs.readFile('path/to/file', (e,data) => {
  console.log(e); //it logs null when no error occurred
  if(e){
    console.log(e);
  }
  console.log(data);
});


// Also
console.log(null == undefined); // logs true
console.log(null === undefined); // logs false


# javascript# primitives