In Javascript, when we try to get an attribute of a variable thats undefined, we get thrown an error.
Lets try to replicate this error with an empty object
var outfit = {}
console.log(outfit.shirt.color)
Our console log will throw us the following error:
Uncaught TypeError: Cannot read property 'color' of undefined
This error happens because we’re trying to get the property of an object that was never defined.
To solve this, we could easily wrap our console.log in two if statements
if(outfit.shirt) {
if(outfit.shirt.color) {
console.log(outfit.shirt.color);
}
}
Two if statements does feel like a lot of code just to find out the color or our shirt.
Another option we can do is
if(outfit.shirt && outfit.shirt.color) {
console.log(outfit.shirt.color);
}
Which seems like an obvious move. However note that while this code works, try reversing outfit.shirt and outfit.shirt.color in the if statement like this:
if(outfit.shirt.color && outfit.shirt) {
console.log(outfit.shirt.color);
}
And you’ll be greeted with the uncaught type error shown in the beginning.
If the first value in our if statement is false, our if statement will automatically be false, so we don’t bother evaluating our second condition.
However, if our first value is true, our if statement will attempt to evaluate our second condition.
The same rule applies for or statements. However, note that for or statements, if the first condition is evaluated as true, we don’t bother evaluating the to the second condition.
Lets create a new outfit object, but lets add a shirt property into it:
var outfit = { shirt: {} };
The following if statement
if(outfit.shirt || outfit.shirt.color) {
console.log(outfit.shirt);
}
will not throw an error because we have evaluated outfit.shirt to be true, so we run whatever code is inside the if statement. Note that we are logging the value of outfit.shirt. If we attempted to log the value of outfit.shirt.color we would be thrown our Type error. Note that while outfit.shirt.color wasn’t evaluated in our if conditionals, evaluating it inside our if statement block will lead to an error.
if(outfit.shirt.color || outfit.shirt) {
console.log(outfit.shirt.color);
}
Will lead to an type error because outfit.shirt.color is evaluated first by our if statement