DEV Community

Discussion on: The Difference Between Null and Undefined in JavaScript

Collapse
 
michaelcurrin profile image
Michael Currin

Good point in other comment on filling in very common encounters of undefined as when getting a non-existent key from an object an getting undefined (in Ruby you get null and Python you get an error) and an argument that is not defined (Python will give an error when it is not defined but in JS you must validate yourself).

Also noteworthy for how to check for undefined.

const MY_VAR = process.env.MY_VAR

if (typeof MY_VAR === 'undefined') {
  throw new Error('Must set MY_VAR on environment variables')
}
Enter fullscreen mode Exit fullscreen mode
function foo(abc) {
 if (typeof abc === 'undefined') {
   throw new Error('abc is a required argument')
  }
  console.log(abc)
}

foo(123)
foo(null)
foo() // error
Enter fullscreen mode Exit fullscreen mode

Another use is to skip positional arguments by passing a value explicitly as undefined, assuming it is optional.

foobar("abc", undefined, 456)
Enter fullscreen mode Exit fullscreen mode

In Python this is not need as you can switch to keyword params.

foobar("abc", third_param=456)
Enter fullscreen mode Exit fullscreen mode