Conditional Statements in JavaScript
Part One
The basics what is a Conditional Statement in JavaScript.
we make decisions based on circumstances in our lives, deciding when we want to eat, sleep , shower etc.. A conditional statement checks a specific condition(s) and performs a task based on that condition(s). We can do the same to make decisions by evaluating conditions and introducing logic into our code! sound simple enough right , I will cover the basic concepts . with some examples.
if
,else if
, andelse
statements- comparison operators
- logical operators
In programming, we can also perform a task based on a condition using an if
statement: The if
statement is composed of:
- The
if
keyword followed by parentheses()
which is followed by a code block, (which just means the code in between the “if and console.log) or block statement, indicated by a set of curly braces{}
. - Inside the parentheses
()
, a condition is provided that evaluates totrue
orfalse
. - If the condition evaluates to
true
, the code inside the curly braces{}
runs, or executes. - If the condition evaluates to
false
, the block won’t execute.
the condition was met(true) and therefore it executed “wear sunglasses!. Let’s try an else statement.
Let’s try comparison operators, sometimes we need to use different types of operators to compare values.
Less than: <
- Greater than:
>
- Less than or equal to:
<=
- Greater than or equal to:
>=
- Is equal to:
===
- Is not equal to:
!==
you can play around with this and see what happens when you use the different operators.
Logical Operators.. what are they? In JavaScript, there are operators that work with boolean values known as logical operators. logical operators add more sophisticated logic to our conditionals. There are three logical operators we can use :
the and operator (&&
)
- the or operator (
||
) - the not operator, otherwise known as the bang operator (
!
)
When we use the &&
operator, we are checking that two things are true
using the &&
operator,
both conditions must evaluate to true
for the entire condition to evaluate to true
and execute. Otherwise, if either condition is false
, the &&
condition will evaluate to false
and the else
block will execute.
If we only care about either condition being
true
, we can use the||
operator: known as the “OR” operator.
admittedly this one is a bit trickier for me but lets use an example (visual leaner)
I played around with this one for a while changing the use of operators to see what I would get , don’t be afraid of playing around to learn what your code is doing for each condition. Logical operators are often used in conditional statements to add another layer of logic to our code.
Theres a lot to take in here so I decided to make this into two parts maybe more ?. I have been reviewing and relearning these concepts . in my next post on conditionals I will be looking at :
- truthy vs falsy values
- ternary operators
switch
statement
Stay tuned and thanks for dropping by .