JavaScript Control Flow Conditionals
If
An if statement executes a code block if the specified condition is
truthy.
if (condition) {// execute the code within this code block}
We can omit the curly braces if we only want to execute a single statement as shown below.
if (condition) singleStatement()
Statements
Up until this point we've mostly worked with something called expressions or values that can be assigned to constants and variables (numbers, strings, arrays, objects, etc).
Statements do things. They do not necessarily give us a value back. An if statement is an example of a statement that has no return value.
// this is invalidconst x = if (cond1) {return a} else {return b}
Running the code above will give us
SyntaxError: expected expression, got keyword 'if'
because an if statement is not an expression.
A function call is also often referred to as a call statement. In
JavaScript (and most other langauges) a call statement ends up
returning a value, and is therefore completely valid to use in
situations where expressions are expected. Even a function that
doesn't explicitly return anything returns undefined.
Did you know?
Some old languages like Fortran make a distinction between subroutines and functions where functions can be used as expressions while subroutines cannot.
Code example
const greetMessage = user = {if (user.authenticated) {return `Welcome back, ${user.firstName}!`}return `Welcome!`}
In the greetMessage function we return different messages based on
the user's authentication status. The last return statement acts as
a catch-all in case the condition of the if statement is falsy.
Beginner mistake: redundant returns
A common beginner mistake is to explicitly return true or false
where directly returning the result of the calculation would have done
the same thing and been easier to read.
const isScreenLarge = width => {if (width >= 1024) {return true} else {return false}}
The above isScreenFunction can be written as a one-line function as
shown below.
const isScreenLarge = width => width >= 1024
Read more on MDN
if...else
Test yourself
Description
Define a new function with the name
oddOrEven
that takes an integer input parameter and returns
even
if the integer is even and
odd
otherwise.
Tips:
- An even integer number divided by two has no remainder.
Tests
- 1
You should define a function named
oddOrEven. - 2
oddOrEven(1)should return"odd". - 3
oddOrEven(154)should return"even". - 4
oddOrEven(7)should return"odd". - 5
oddOrEven(0)should return"even". - 6
oddOrEven(-1)should return"odd". - 7
oddOrEven(-4)should return"even".