JavaScript Mistakes — null vs undefined, Constructors, and Scopes
JavaScript is a language that’s friendlier than many other programming languages in the world. However, it’s still very easy to make mistakes when writing JavaScript code through misunderstanding or overlooking stuff that we already know. By avoiding some of the mistakes below, we can make our lives easier by preventing bugs and typos in our code that bog us down with unexpected results. In this article, we’ll look at the confusion between null
and undefined
, scope issues with asynchronous code, and scopes and using object literals vs. constructors for built-in objects.
Confusing Null and Undefined
In JavaScript, both null
and undefined
mean no value for a variable. They’re pretty similar but there are some important differences. One if that null
is of type object
, so when we use the typeof
operator on null
as we do below:
typeof null
We get 'object'
.
On the other hand, if we use the typeof
operator on undefined
, as we do below:
typeof undefined
We get 'undefined'
.
If we compare them with the ===
operator, as we do below:
undefined === null
We get false
since they’re of 2 different types. However, when we compare them with the ==
operator:
undefined == null
Then we get true
since they’re both falsy. Since they’re 2 different types, they shouldn’t be confused with each other.
One thing to note is that for function default parameters, they will only be assigned if the value is undefined
and not null
.
const hello = (name = 'World') => console.log(`Hello, ${name}!`)
hello(null) // Hello, null!
hello(undefined) // Hello, World!
Asynchronous Code and Scope
One confusing aspect of JavaScript is that the visibility of a variable remains in the parent scope. This means that when a loop runs with a loop variable that we want to access in the callback of the setTimeout
function, the index variable would have already been incremented to meet the end condition before the callback in setTimeout
is called. This…