Member-only story

Coding Tip: Try to Code Without If-statements

You might uncover better solutions

Samer Buna
EdgeCoders
Published in
5 min readSep 7, 2017

--

Code from a Facebook project. Please don’t sue them.

Update: This article is now part of my book “Learn Coding with Modern JavaScript”.

Read the updated version of it at jscomplete.com/no-ifs.

When I teach beginners to program and present them with code challenges, one of my favorite follow-up challenges is: Now solve the same problem without using if-statements (or ternary operators, or switch statements).

You might ask why would that be helpful?

Well, I think this challenge forces your brain to think differently and in some cases, the different solution might be better.

There is nothing wrong with using if-statements, but avoiding them can sometimes make the code a bit more readable to humans. This is definitely not a general rule as sometimes avoiding if-statements will make the code a lot less readable. You be the judge.

Avoiding if-statements is not just about readability. There is some science behind the concept. As the challenges below will show, not using if-statements gets you closer to the code-as-data concept, which opens the door for unique capabilities like modifying the code as it is being executed!

--

--

EdgeCoders
EdgeCoders

Published in EdgeCoders

jsComplete’s Medium Publication — jsComplete is a FREE software educational library focused on JavaScript, Node, React & GraphQL. It has video courses, books, articles, and interactive lessons.

Samer Buna
Samer Buna

Written by Samer Buna

Author for Pluralsight, O'Reilly, Manning, and LinkedIn Learning. Curator of jsComplete.com

Responses (54)