Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62
Subscribe to my email list now at http://jauyeung.net/subscribe/
undefined is a value that’s often confused with
This is partly because
null == undefined returns
However, they’re actually very different from each other.
Variables that haven’t been assigned a value have the initial value of
This means it’s waiting for a real value to be assigned to it.
If we have:
let animal; console.log(animal === undefined);
Then the console log will log
undefined shouldn’t be used much in our code.
But we need to check for them so that we’ll avoid all sorts of runtime errors.
We often get things that are
Non-existent properties have value
Parameters that haven’t have an argument passed in for it is also
If we try to do something to something that’s
undefined , then we’ll get an error.
Therefore, we need to check for them.
To check for
undefined , we can use the
If something is
typeof will return
For example, we can write:
let animal; console.log(typeof animal);
Then we get
We shouldn’t use it for assignments, but we should check for them.
Object literals is a popular way to create objects with a set of properties.
It’s shorter than using the
Object constructor and does the same thing.
Therefore, we should use the object literal notation to create an object.
For example, instead of writing:
We should write:
It’s shorter and cleaner.
We just specify all the properties and values in between the curly braces.
We include the opening curly brace in the first line.
The properties are indented one level.
And the closing brace is in its own line.
Most style guides and linters suggest this format.
Guides like the Google style guide, Airbnb, style guide, ESLint default rules, etc. all look for this style.
Like object literals, we don’t need the
Array constructor to create arrays.
Instead, we use the array literal notation.
For instance, instead of writing:
let fruits = new Array("apple", "orange", "grape"); let numbers = new Array(1, 2, 3, 4);
let fruits = ["apple", "orange", "grape"]; let numbers = [1, 2, 3, 4];
It’s much shorter and does the same thing.
Array constructor also has 2 versions.
It returns an array with the arguments if we pass in multiple arguments.
If there’s only one argument and it’s a nonnegative integer, then it creates an array with the number of empty slots as indicated by the argument.
Therefore, it’s another reason to avoid the
We can work with
undefined , objects and arrays in better ways.
Literals are better than constructors for arrays and objects.