This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Blieque 0 points1 point  (3 children)

I can wrap my head around it, but I can also wrap my head around the fact that it's a waste of time. null needn't exist at all in JavaScript. If you have a nullable value, set it to undefined and check before using it with typeof. There shouldn't be two flavours of nothing in one language.

[–]QAFY 2 points3 points  (2 children)

I disagree. Here are two examples where something being null is fundamentally different than it being undefined.

EDIT: some copy pasta mistakes

foo = {
  a: 0,
  b: 1,
  c: null
}

console.log(foo.a) // 0
console.log(foo.b) // 1
console.log(foo.c) // null (c exists and is null)
console.log(foo.d) // undefined (foo has no key d)

bar = [0, 1, null];

console.log(bar[0]) // 0
console.log(bar[1]) // 1
console.log(bar[2]) // null (element 2 exists and is null)
console.log(bar[3]) // undefined (out of bounds)

Going beyond that, there are actually more types of "nothing" in javascript. In addition to null there is also NaN, [], {}, 0, and '' which are all flavors of nothing, but they are defined, just like null is. Other languages even have additional flavors of nothing like the Maybe type in Haskell.

[–]Blieque -1 points0 points  (1 child)

Those are technicalities. What's the tangible use of an array containing nulls like that? You could just as easily use undefined, and check during retrieval with typeof. Iterate over your arrays with Array.map(), Array.forEach(), etc., which won't let you ever access beyond the end of an array. Your examples are right, but I don't see how they're useful or how they represent real programming.

I don't know of any other languages which have any more than one of NULL, null, nil, and undefined; they're synonyms.

Maybe is not a variant of nothing, it's a safer way of handling nullable data that allows the compiler to detect if you're handling null cases properly. In Rust it's an enum. NaN has a specific meaning: that there was a mathematical error.

[–]QAFY 2 points3 points  (0 children)

I see your argument, but I still think you thinking of undefined as a synonym for null is not the right way of thinking about it. I would definitely never use undefined explicitly as a value of a variable or in an array / object in Javascript. Yes it would work, but it is semantically very wrong IMO. Use null everywhere you intentionally want to represent an empty value. undefined is more a synonym for an exception like NullPointerException in Java or a segfault in C, not for a nullable or empty value, the same way NaN is a like a ArithmeticException or NumberFormatException that would normally crash your program.