Using “Guard Clause”

Andrew Park
Jul 4, 2021

I tend to use if statements “if (true) {do something}”a lot. And sometimes I end up with too many nested blocks that is not easy to read.

Below, I have a code where a user enters a like count in “Enter Likes Count” field, and then increase the Likes Count by entered amount.

Line 17 converts the string (user entered value) to a number. And Lines 19–22 update total Likes Count if user entered value is an integer and the value is greater than 0.

This code works, but with Guard Clause, we can eliminate if block.

Line 19 is Guard Clause. The function will exit at line 19 if “if (condition)” is false.

It is personal preference, but to me, not having “if {block}” makes code a lot easier to read and simple to write.

--

--