Conditionals in Javascript

Sam Hall
3 min readSep 21, 2021

You’ve probably seen keywords like if, else if and else in code. These are conditionals: bits of code that only run if a specified condition is met! Conditionals are handy when you want to interpret some data and do something with that data via your code if the data meets whatever standard you set. If the data does not meet that standard, you can do something else with it.

Here is an explainer on the syntax and usage of conditionals in JavaScript. In JavaScript, conditionals are written starting with the keyword if followed immediately by parentheses containing whatever the condition is for the dataset — the standard that you need met. The parentheses are then followed by curly braces that contain the code — whatever you want to do with the data that meets the standard you’ve previously set. Confused? Me too. Here’s an example:

In this example we have one variable: a boolean indicating that perhaps someone we know is athletic. In our code, if athletic is true, our console will log “Invite to join the basketball team!” Because this boolean value is true, this is what our console returns.

If the variable “athletic” is false, the code after keyword else will run instead, as shown above.

Conditionals can also be paired with logical operators to determine if a dataset meets multiple standards at once, like so:

The addition of the variable “height” and its integer value adds another layer to this conditional. The data must meet both conditions within the parentheses to run the first bit of code. The Logical AND (&&) will only read true if both conditions are met. Because our person in question is athletic, but not at least 72 inches tall, they’ll have to join chess club. Bummer!

But what if these two stark options are not nuanced enough for our code? Or for our acquaintances of varying height and sportiness? This is where else if comes in to save the day! Else if specifies a new condition if the first condition is not met by the data, and therefore reads false (the condition following if is the priority condition).

The Logical OR (||) indicates a partial condition — if either standard on either side of || are met, the following code will run, as shown above. In this case, our friend is on the short side at 60 inches, but they’re still athletic! Every volleyball team needs a setter!

Further Reading

All examples created with repl.it.

--

--