Every day, we make decisions based on certain conditions. For example, we may say, 'If it rains, I will stay inside; if not, I will go outside.' The condition there is the weather. This is one of the decisions we make every single day. Although the decision above is very simple, we make complex decisions sometimes. In this article, you will learn about conditional statements in JavaScript using if
and else
. The JavaScript if
and else
statements are one of the JavaScript statements for a beginner to master as part of the fundamentals.
Ok, let's get started!
If
Key Takeaways
- The
if
is used to execute a block of code if the condition is true. -
else
is used to execute a block statement if theif
the condition is false - A block statement can be a statement or a group of statements(for a group of statement, curly brackets are used).
-
if
andelse
are all in lowercase letters. - The default statement (if no other statement is triggered) is
undefined
if the condition is false.
The condition is what we want to check if it is true or not. This is similar to the JavaScript Boolean value which can possible be of two values : truth or false. If the condition evaluates to be true, the if statement will be executed. If not, the statement will be passed to the next statement. However, if there is no statement to passed on, the default statement will be executed.
the syntax for if statement goes thus:
if (condition){
statement //the block of code to be executed if the condition is true.
}
How if statement works:
You first declare and initialize the variable name. For example:
declare and initialize variable name:
let votingAge = 18;
or
Let say the constitution says 'you are eligible to vote' if you are eighteen (18) and above.
then check if the condition matches the if
statement. For example:
if (votingAge >=18){
console.log ('you are eligible to vote')
}
output:
'You are eligible to vote'
or
However, if the condition is not true, the output will be:
undefined
The undefined
is the default value if the condition is not true.
Unless another statement is else or else if is triggered, the default will be undefined
.
else
As stated above, the if statement is used to execute a block of code. If the condition is false, the default statement is nothing which is undefined.
let votingAge = 17;
if (votingAge >= 18) //condition
{
console.log('you are eligible to vote'); //statement
}
// the condition is false. The default is undefined (nothing).
However, with else statement, you can write a new block of code to execute if the if condition is false.
else is used to execute another statement to execute.
let votingAge = 17;
if (votingAge >= 18) //condition
{
console.log('you are eligible to vote'); //statement
}
else {
console.log('you are not eligible to vote') //else statement will be executed
}
Top comments (0)