28

Why does isNil method in Lodash use null instead of undefined?

function isNil(value) {
  return value == null;
}
mohsinulhaq
  • 1,059
  • 1
  • 18
  • 31

2 Answers2

28

It makes no difference either way in terms of the logic using null or undefined as null == undefined == true, but using null instead of undefined would make the file size smaller by 5 bytes.

It's simply done to save a few bytes making the file smaller and faster to download from the server.

George
  • 6,630
  • 2
  • 29
  • 36
  • 3
    Also this may be useful: https://stackoverflow.com/questions/5076944/what-is-the-difference-between-null-and-undefined-in-javascript – Deepak Kamat Dec 14 '17 at 12:22
15

To understand this a bit better, it's important to note that lodash is using == here instead of ===.

Take the following example:

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

By using == (double equals), lodash is utilizing type coercion where null and undefined will be coerced to falsy values. As a result, null == undefined is true.

However, if using === (triple equals), no coercion is enforced, which means the types must be identical, and as we know null is not identical to undefined. As a result, null === undefined is false.

lux
  • 8,315
  • 7
  • 36
  • 49
  • 1
    It looks like the main value of _.isNil is to avoid confusing someone like me who can never remember the subtleties of these coercion rules. If I see _.isNil when doing a code review it looks fine, but if I see == instead of === it raises a red flag. – Glenn Lawrence Feb 18 '21 at 09:06