COMPUTER SCIENCE CAFÉ
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
JAVASCRIPT | CONDITIONALS
ON THIS PAGE
SECTION 1 | IF STATEMETNS
SECTION 2 | THE STRUCTURE
SECTION 3 | NESTED IF STATEMENTS
SECTION 4 | THE TERNARY OPERATOR
SECTION 5 | THE SWITCH STATEMENT
ALSO IN THIS TOPIC
GETTING STARTED

 ​VARIABLES & USER INPUT
 OPERATORS
YOU ARE HERE | CONDITIONALS (IF STATEMENTS)
​ITERATION (LOOPS)
ARRAYS (LISTS)
FUNCTIONS

FURTHER JAVASCRIPT

Picture
WHAT ARE CONDITIONALS
Conditionals (also known as selection)are constructs in programming that allow you to make decisions in your code based on whether certain conditions are true or false. They let your program take different paths or actions depending on specific criteria.
' If it is sunny outside then we select to wear sun glasses
Or else if it is raining then we select to take an umbrella '
Imagine you're getting ready for the day and deciding what to wear. If it's raining, you'll wear a raincoat. If it's sunny, you'll wear sunglasses. This decision-making process is similar to how conditionals work in programming.
  • if Statement: This checks a condition and runs the code inside the statement if the condition is true.
  • else Statement: Used alongside if, this runs when the if condition is false.
  • else if Statement: This allows you to check multiple conditions. If the initial if is false, it checks the condition in else if.

Later we will look at using the 'ternary' and the 'switch' statements
  • Ternary Operator: A shorthand way to check a condition and return a value based on whether it's true or false.
  • switch Statement: Allows you to compare a value against multiple possible matches.

​Before we dive into JavaScript IF statements we need to remember the comparison operators. The use of three equal signs (===) represents the "strict equality" operator, where as the double equals (==) is known as the "loose equality" operator. When you use ==, JavaScript tries to help by converting (or coercing) the operands to a common type before making the comparison.

    
STEP 1 | IF STATEMETNS
The if statement allows us to make decisions based on specific conditions, much like how we make decisions in real life based on various factors. Consider the weather as an example. If it's raining outside, you might decide to wear a raincoat. If it's sunny, you might opt for sunglasses.

We can use the if statement in code to make such decisions. For instance, if we have a variable called weather  that stores the current weather condition, we can check its value. If the value of weather is "rainy", the program might display a message suggesting you wear a raincoat. If the value is "sunny", it might advise wearing sunglasses.

This decision-making process, facilitated by the if statement, allows our code to respond dynamically to different situations, ensuring that the program's actions are contextually relevant.
Code Editor

    
The code above shows the example of checking what the value of a variable is and outputting a message depended on that value. The code above explained.

The if Keyword
This keyword initiates the conditional statement, signalling to the program that a decision is about to be made based on a condition.

Parentheses ()
Parentheses (): These are essential because they clearly define the condition being tested. Without them, the program wouldn't know what to evaluate to determine whether to execute the code inside the curly braces.
  • The condition you're testing is placed inside these parentheses.
  • The condition is a statement that evaluates to either true or false. If the condition inside the parentheses evaluates to true, the code inside the curly braces {} will execute.

Curly Braces {}
Curly Braces {}: They are crucial for grouping the code that needs to be executed when the condition is true. Without them, the if statement would only consider the very next line of code as part of its block, which could lead to unintended behaviour.
  • These define the scope of the if statement.
  • Any code placed inside these braces will execute if the condition in the parentheses is true.
  • They help group multiple lines of code together, ensuring that all of them are executed as part of the condition.

Indents
Indents: While the program doesn't need them to run the code, they are vital for human readability. Proper indentation makes the code's structure visually clear, helping developers quickly understand the logic and flow.
  • While not strictly necessary for the code to run, indents (or whitespace) are crucial for readability.
  • Indenting the code inside the curly braces {} makes it clear that this code belongs to the if statement and will only run under the specified condition.
  • Consistent indentation helps other developers (and your future self) understand the flow and structure of your code.

​We could extent this code by asking the user to input the weather. 

    
SECTION 2 | THE STRUCTURE
The structure of conditional statements, especially when using if, else if, and else, plays a crucial role in the logic and flow of a program.

Sequential Evaluation
  • When using if, else if, and else, conditions are evaluated in sequence. Once a condition is found to be true, its corresponding block of code is executed, and the rest of the conditions are skipped.
  • This ensures that only one block of code is executed, even if multiple conditions are true.

Efficiency
  • By using else if after an if, you're telling the program that if the first condition is true, there's no need to check the subsequent conditions. This can make the code run faster, especially when there are multiple conditions to check.

Clarity and Readability
  • Using a structured if, else if, else format makes the code more readable. It clearly delineates the decision-making process and shows the hierarchy of conditions.

Avoiding Unintended Behaviour
  • If you use multiple if statements consecutively without else if or else, there's a possibility that multiple blocks of code will execute, which might not be the intended behaviour.

EXAMPLE
Imagine you're coding a grading system:​
CORRECT STRUCTURE USED

    
In the above structure, if a student scores 95, only the first condition is true, and they get an "A". The other conditions are skipped.
Now, if you were to use consecutive if statements:
WRONG STRUCTURE USED

    
In this case, if a student scores 95, they would first get an "A", but as the program continues to check the next conditions, their grade would be overwritten to "B" and then "C", which is clearly not the intended outcome.

REMEMBER
An if statement starts with one if to check a condition. If that's not met, you can use multiple else if to check other conditions. At the end, you can have one else which acts without its own criteria; it simply says "if none of the above conditions are true, then do this.". Only one if, one optional else, but as many else if as needed. 
SECTION 3 | NESTED IF STATEMENTS
Nested if statements refer to an if statement inside another if statement. It allows for more specific or additional conditions to be checked within a broader condition. By nesting if statements, you can create a hierarchy or multi-level decision structure, enabling more complex logic and decision-making in your code.

    
In this example:
  • The outer if statement checks if it's rainy.
  • If it is rainy, the nested (inner) if statement then checks the temperature to decide between a warm or light raincoat.
  • If it's not rainy, the nested if statement checks the temperature to decide between a warm jacket or a t-shirt.
​
This structure allows for more detailed decisions based on multiple factors (in this case, rain and temperature
SECTION 4 | THE TERNERY OPERATOR
The ternary operator is a shorthand way of writing a simple if-else statement. It's called "ternary" because it involves three operands: a condition, a result for true, and a result for false. And has the following syntax
​condition ? valueIfTrue : valueIfFalse;
  1. condition: This is the condition to be tested.
  2. valueIfTrue: This value is returned if the condition is true.
  3. valueIfFalse: This value is returned if the condition is false.
Below is an example of this in use.
THE TERNARY OPERATOR

    
In this example:
  • The condition checks if the number is even (number % 2 === 0).
  • If the condition is true, the string "even" is assigned to the result variable.
  • If the condition is false, the string "odd" is assigned to the result variable.
​
The ternary operator provides a concise way to perform a simple if-else check and assign a value based on the result. It's especially useful for simple decisions in your code where a full if-else structure might be more verbose than necessary.
SECTION 5 | THE SWITCH STATEMENT
​The switch statement is used to perform multiple checks against a single expression. Instead of using multiple if-else conditions, you can use the switch statement to make your code more organized and readable when dealing with many possible cases for a single value.
SWITCH STATEMETN SYNTAX

    
  1. expression: This is the value you want to compare against multiple cases.
  2. case: Represents a possible value for the expression. If the expression matches a case, the code within that case is executed.
  3. break: Exits the switch statement. Without it, the program would continue to the next case, executing its code as well.
  4. default: (Optional) If none of the cases match the expression, the code inside the default block is executed.

Example: Determine the day of the week based on a number:

    
  • The switch statement checks the value of dayNumber.
  • The prompt function asks the user to enter a day number.
  • The entered value is then converted to an integer using parseInt and stored in the dayNumber variable.
  • The Switch statement is determining the day name based on the entered number
  • The console.log is displaying it to the user using an alert.

Picture
SKI TEAMS
TASK 1 | CREATE A PROGRAM THAT DOES THE FOLLOWING

1: Ask the user for the time it took to complete the ski course
2: IF they complete the course in less than 2 minutes then they are in team A. Output ' Congratulations - You are in Team A' 3: If they complete the course in 2 minute or more and less than 3 minutes then they are on team B. Output ' Congratulations - You are in Team B'
​4: Otherwise they are on team C. Output ' Congratulations - You are in Team C'

TASK 2 | CREATE A PROGRAM THAT DOES THE FOLLOWING
A Ski company sells lift passes and wants you to create a program that does the following
1: Ask the user if they want a day pass or week pass
2: If the user wants a day pass then ask the user how old they are
    2b: If the user is less that 11 years old the the day pass is $40
    2c: If the user is greater than 64 years old then the day pass is $20
    2d: Otherwise the day pass is $60
3: If the user wants a week pass then ask the user how old they are
    3b: If the user is less that 11 years old the the week pass is $100
    3c: If the user is greater than 64 years old then the day pass is $100
    3d: Otherwise the day pass is $200
4: Output the cost of the correct pass in a user friendly statement
Picture
NAVIGATION
GETTING STARTED
​VARIABLES & USER INPUT
 OPERATORS
CONDITIONALS (IF STATEMENTS)
 ​ITERATION (LOOPS)
ARRAYS (LISTS)
FUNCTIONS

FURTHER JAVASCRIPT
Picture
SUGGESTIONS
We would love to hear from you
SUBSCRIBE 
To enjoy more benefits
We hope you find this site useful. If you notice any errors or would like to contribute material then please contact us.