why does javascript have both null and undefined?

I suggest you think of their pusposes to better understand the difference.

The value null represents the intentional absence of any object value. It's never assigned by the runtime.

Meanwhile any variable that has not been assigned a value is of type undefined. Methods, statements and functions can also return undefined. You also get undefined when you call a non-existent property or method of an object.

undefined has nothing to do with an empty value. For example:

console.log(5 + undefined);
// expected output: NaN
console.log(5 + null);
// expected output: 5

The distinction between both is useful given that JavaScript is dynamically typed and objects are dynamic "bags" of properties that can be changed at runtime.

let car = {type: "Fiat", model:"500", color:"white"};
console.log(car.type);
// expected output: "Fiat"
console.log(car.price);
// expected output: undefined
car.price = null;
console.log(car.price);
// expected output: null
car.price = 2000;
console.log(car.price);
// expected output:2000

Tags:

Javascript