Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does javascript have both null and undefined? [duplicate]

Tags:

javascript

why does javascript have null and undefined? they both seem to mean the same thing, there's nothing here and they are both falsey, as they should be. But it means, for example if I want to check if something exists but it could be {}, [], 0 or some other falsey thing i have to check

if(thing !== undefined && thing !== null)

also, I know that typeof null is Object but typeof {} is also Object while typeof undefined is "undefined" but

const nullVariable = null;
console.log(nullVariable.x) // => error
const emptyVariable = {};
console.log(emptyVariable.x) // => undefined
const undefinedVariable;
console.log(undefinedVariable.x) // => error

also, undefined is supposed to mean that the variable hasn't been declared yet, but you can declare a variable like

const undefinedVariable = undefined;

so it has been defined but it has not yet been defined?

so what I am saying is while they have different semantic meanings, one means a variable that hasn't been declared and on means a variable with no value, they seem to have the functionality and they are both false, trying to get a property form them will return an error.

basically what I am asking is why do we need both, why not just use one like python with None or lower level languages like java and c++ with Null?

like image 699
david snyder Avatar asked Apr 05 '20 00:04

david snyder


1 Answers

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
like image 95
dbaltor Avatar answered Oct 13 '22 11:10

dbaltor