Hey folks, to understand what short-circuit evaluation is one must be aware of the logical operators in javascript.
There are three logical operators.
- Logical AND
&&
- Logical OR
||
- Logical NOT
!
In this blog we will explore how we can use the Logical OR ||
to our advantage while assigning variables.
Now we know that the ||
operator returns true if either of the operand is true.
true || false // returns true
false || true // returns true
true || true // returns true
false || false // returns false
The two things to remember here are:
- that logical operators in JavaScript evaluate from left to right, and;
- they short-circuit
This means that when javascript evaluates the ||
operator it will evaluate from left to right and if the first condition is true it will short-circuit and and not even look at the second condition
So how do we use this to our advantage ??
we will try to write a function to update a collection of my favorite music albums.
this collection which is an object looks like this.
var albumCollection = {
1546: {
albumTitle: 'Timewave',
artist: 'Terance Mckenna',
tracks: ['Meme Magic', 'Look Away']
},
1465: {
albumTitle: 'The Human Condition',
artist: 'Jon Bellion',
tracks: ['All Time Low', 'He is the Same']
},
4235: {
artist: 'Queen Crimson',
tracks: []
},
5459: {
albumTitle: 'Hollywoods Bleeding'
}
};
We will write a function to update this collection.
- Our function will always return updated album collection which is an object.
- If the property is not tracks and value is not an empty string we will update/set that album's property to the value.
- If the property is tracks but the album does not have a tracks property we will create an empty array and add the value to it.
- If property is tracks and value is not an empty string, we will add the value to the end of the album's existing tracks array.
- If value is an empty string, we will delete the given property from the album.
So our function will have 4 parameters
-
albumObj
to be passed -
id
of the album to be updated -
property
to be updated -
value
of the property
we can do this is two ways, without using the ||
operator and with using it. Since this blog is about using short-circuit evaluation we will first look at the way we can do this is with the ||
operator.
function updateAlbum(albumObj, id, property, value) {
if (value === '') {
delete albumObj[id][property];
} else if (property === 'tracks') {
// this is called shortcircuit evaluation
albumObj[id][property] = albumObj[id][property] || [];
albumObj[id][property].push(value);
} else {
albumObj[id][property] = value;
}
return albumObj;
}
Code Explanation
- First it checks if the value is a blank string. If so, then the key (property) is removed from the object then
- If the first condition does not pass then it will check if property is equal to tracks.
- The tracks array is initialized if it does not have that
property
, and then value is pushed into the tracks array. (This step uses short-circuit evaluation) (remember if it is there then it wont initialized the array because the first or the left operand is true) - If both these checks fail (meaning value is not an empty string and
property
is not tracks), - Then either a new key (property) and value (value) are added to the object,
- or an existing key is updated if the property already exists.
Example:
var albumCollection = {
1546: {
albumTitle: 'Timewave',
artist: 'Terance Mckenna',
tracks: ['Meme Magic', 'Look Away']
},
1465: {
albumTitle: 'The Human Condition',
artist: 'Jon Bellion',
tracks: ['All Time Low', 'He is the Same']
},
4235: {
artist: 'Queen Crimson',
tracks: []
},
5459: {
albumTitle: 'Hollywoods Bleeding'
}
};
function updateAlbum(albumObj, id, property, value) {
if (value === '') {
delete albumObj[id][property];
} else if (property === 'tracks') {
// this is called short-circuit evaluation
albumObj[id][property] = albumObj[id][property] || [];
albumObj[id][property].push(value);
} else {
albumObj[id][property] = value;
}
return albumObj;
}
updateAlbum(4235, "artist", "King Crimson")
- updateAlbum(4235, "artist", "King Crimson"); runs.
-
value
is not a blank string, so the first condition of the else if statement fails. -
property
is equal to “artist”, not “tracks”, so the second condition of the else if statement fails. - in the ‘else’, artist: "King Crimson" is added to the 4235
id
.
How to do the same without using ||
operator
function updateAlbum(albumObj, id, property, value) {
if (property !== 'tracks' && value !== "") {
albumObj[id][property] = value;
} else if (property === "tracks" && albumObj[id].hasOwnProperty("tracks") === false) {
albumObj[id][property] = [value];
} else if (property === "tracks" && value !== "") {
albumObj[id][property].push(value);
} else if (value === "") {
delete albumObj[id][property];
}
return albumObj;
}
One more example.
This is a popular snippet of code from stack overflow:
var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';
var f = a || b || c || d || e;
console.log(f);
Look at the code above and think about what will be logged to the console. Got an idea? Scroll down for the answer…
Answer
Did you guess 4? Awesome! If not, its alright, lets break it down:
var a; // undefined (falsy value)
var b = null; // null (falsy value)
var c = undefined; undefined (falsy value)
var d = 4; // number (NOT falsy)
var e = 'five'; // assigment short circuits before reaching here
var f = a || b || c || d || e;
-
a
,b
,c
, all are assignedfalsy
values. - When Logical OR sees a falsy value, it continues evaluating.
- Once it reaches variable d with a value of 4, the equation short-circuits and the value of 4 is saved to variable f.
If this blog helped you or you have any feedback, let me know in the comments. If you any questions, you can find me on Twitter Instagram
Top comments (0)