Working with conditions and loops in JavaScript
If Statement
The most fundamental of the conditional statements is the if statement. An if statement will evaluate whether a statement is true or false, and only run if the statement returns true. The code block will be ignored in the case of a false result, and the program will skip to the next section.
An if statement is written with the if keyword, followed by a condition in parentheses, with the code to be executed in between curly brackets. In short, it can be written as if () {}.
Here is a longer examination of the basic if statement.
The contents of an if statement are indented, and the curly brackets containing the block of code to run do not end in a semicolon, just like a function block.
As an example, let’s consider a shopping app. Say, for the functionality of this app, a user who has deposited a certain amount of funds into their account would then like to buy an item from the store.
OutputYou have enough money to purchase the item!
We have an account balance of 500, and want to buy a pair of jeans for 40. Using the less than or equal to operator, we can check if the price of jeans is less than or equal to the amount of funds we have. Since jeans <= balance evaluates to true, the condition will pass and the block of code will run.
In a new example, we will create a new shop item that costs more than the available balance.
This example will have no output, since phone <= balance evaluates to false. The code block will simply be ignored, and the program will proceed to the next line.
Else Statement
With if statements, we only execute code when a statement evaluates to true, but often we will want something else to happen if the condition fails.
For example, we might want to display a message telling the user which fields were filled out correctly if a form did not submit properly. In this case, we would utilize the else statement, which is the code that will execute if the original condition does not succeed.
The else statement is written after the if statement, and it has no condition in parentheses. Here is the syntax for a basic if...else statement.
Using the same example as above, we can add a message to display if the funds in the account are too low.
OutputYou do not have enough money in your account to purchase this item.
Since the if condition did not succeed, the code moves on to what’s in the else statement.
Else if Statement
With if and else, we can run blocks of code depending on whether a condition is true or false. However, sometimes we might have multiple possible conditions and outputs, and need more than simply two options. One way to do this is with the else if statement, which can evaluate more than two possible outcomes.
Here is a basic example of a block of code that contains an if statement, multiple else if statements, and an else statement in case none of the conditions evaluated to true.
JavaScript will attempt to run all the statements in order, and if none of them are successful, it will default to the else block.
You can have as many else if statements as necessary. In the case of many else if statements, the switch statement might be preferred for readability.
As an example of multiple else if statements, we can create a grading app that will output a letter grade based on a score out of 100.
The requirements of this app are as follows:
- Grade of 90 and above is an A
- Grade of 80 to 89 is a B
- Grade of 70 to 79 is a C
- Grade of 60 to 69 is a D
- Grade of 59 or below is an F
Below we will create a simple set of if, else, and else if statements, and test them against a given grade.
OutputB
In our example, we first check for the highest score, which will be greater than or equal to 90. After that, the else if statements will check for greater than 80, 70, and 60 until it reaches the default else of a failing grade.
Although our grade value of 87 is technically also true for C, D and F, the statements will stop at the first one that is successful. Therefore, we get an output of B, which is the first match.
Combining Conditions
- condition A AND Conditon B if true combinely , with AND, all must return True
- ConDtion A OR condition B OR condition C ,with OR whole condition return true if any subconditions return true.
- Javascript conditions with Boolean value(true or false)
- for eg :
- Boolean(0) >> false
- Boolean (" ") >> false
- null , undefined , NAN >> false
- any non-empty string >>false
- all object and any other num including negative numbers are true >> True
Ternary Operator
The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement.
A ternary operator is written with the syntax of a question mark (?) followed by a colon (:), as demonstrated below.
In the above statement, the condition is written first, followed by a ?. The first expression will execute on true, and the second expression will execute on false. It is very similar to an if...else statement, with more compact syntax.
In this example, we will create a program that checks if a user is 21 or older. If they are, it will print "You may enter" to the console. If they are not, it will print "You may not enter." to the console.
Output'You may not enter.'
Since the age of the user was less than 21, the fail message was output to the console. The if...else equivalent to this would be "You may enter." in the if statement, and "You may not enter." in the else statement.
addition to if...else, JavaScript has a feature known as a switch statement. switch is a type of conditional statement that will evaluate an expression against multiple possible cases and execute one or more blocks of code based on matching cases. The switch statement is closely related to a conditional statement containing many else if blocks, and they can often be used interchangeably.
In this tutorial, we will learn how to use the switch statement, as well as how to use the related keywords case, break, and default. Finally, we’ll go through how to use multiple cases in a switch statement.
Switch
The switch statement evaluates an expression and executes code as a result of a matching case. At first it can look a bit intimidating, but the basic syntax is similar to that of an if statement. It will always be written with switch () {}, with parentheses containing the expression to test, and curly brackets containing the potential code to execute.
Below is an example of a switch statement with two case statements, and a fallback known as default.
Following the logic of the code block above, this is the sequence of events that will take place.
- The expression is evaluated
- The first
case,x, will be tested against the expression. If it matches, the code will execute, and thebreakkeyword will end theswitchblock. - If it does not match,
xwill be skipped and theycase will be tested against the expression. Ifymatches the expression, the code will execute and exit out of theswitchblock. - If none of the cases match, the
defaultcode block will run.
Let’s make a working example of a switch statement following the syntax above. In this code block, we will find the current day of the week with the new Date() method, and getDay() to print a number corresponding to the current day. 1 stands for Monday, all the way through 7 which stands for Sunday. We’ll start by setting up our variable.
Using switch, we will send a message to the console each day of the week. The program will run in order from top to bottom looking for a match, and once one is found, the break command will halt the switch block from continuing to evaluate statements.
Output'Just one more day 'til the weekend!'
This code was tested on a Thursday, which corresponds to 4, therefore the console output was Just one more day 'til the weekend!. Depending on what day of the week you are testing the code, your output will be different. We have included a default block at the end to run in case of an error, which in this case should not happen as there are only 7 days of the week. We also could have, for example, only printed results for Monday to Friday, and the default block could have had the same message for the weekend.
If we had omitted the break keyword in each statement, none of the other case statements would have evaluated to true, but the program would have continued to check until it reached the end. In order to make our programs faster and more efficient, we include the break.
Switch Ranges
There might be an occasion in which you will need to evaluate a range of values in a switch block, as opposed to a single value as in our example above. We can do this by setting our expression to true and doing an operation within each case statement.
To make this easier to understand, we will use a familiar example. In the conditional statements tutorial, we made a simple grading app which would take a number score and convert it to a letter grade, with the following requirements.
- Grade of 90 and above is an A
- Grade of 80 to 89 is a B
- Grade of 70 to 79 is a C
- Grade of 60 to 69 is a D
- Grade of 59 or below is an F
Now we can write that as a switch statement. Since we’re checking a range, we will perform the operation in each case to check if each expression is evaluating to true then break out of the statement once the requirements for true have been satisfied.
Output'B'
The expression in parentheses to be evaluated is true in this example. This means that any case that evaluates to true will be a match.
Just like with else if, switch is evaluated from top to bottom, and the first true match will be accepted. Therefore, even though our grade variable is 87 and therefore evaluates to true for C and D as well, the first match is B, which will be the output.
Multiple Cases
You may encounter code in which multiple cases should have the same output. In order to accomplish this, you can use more than one case for each block of code.
In order to test this, we are going to make a small application matching the current month to the appropriate season. First, we will use the new Date() method to find a number corresponding to the current month, and apply that to the month variable.
The new Date().getMonth() method will output a number from 0 to 11, with 0 being January and 11 being December. At the time of this publication, the month is September, which will correspond to 8.
Our application will output the four seasons with the following specifications for simplicity:
- Winter: January, February, and March
- Spring: April, May, and June
- Summer: July, August, and September
- Autumn: October, November, and December
Below is our code.
When we run the code, we’ll receive output identifying the current season based on the specifications above.
OutputSummer
The current month at the time of publication was 8, which corresponded to one of the case statements with the "Summer" season output.
Introduction
Automation is the technique of making a system operate automatically; in programming, we use loops to automate repetitious tasks. Loops are one of the most useful features of programming languages, and in this article we will learn about the while and do...while loops in JavaScript.
The while and do...while statements in JavaScript are similar to conditional statements, which are blocks of code that will execute if a specified condition results in true. Unlike an if statement, which only evaluates once, a loop will run multiple times until the condition no longer evaluates to true.
Another common type of loop you will encounter is the for statement, which executes a set number of times. while and do...while loops are conditionally based, and therefore it is not necessary to know beforehand how many times the loop will run.
While Loop
In JavaScript, a while statement is a loop that executes as long as the specified condition evaluates to true.
The syntax is very similar to an if statement, as seen below.
The while statement is the most basic loop to construct in JavaScript.
As an example, let’s say we have an aquarium that has a population limit. For each iteration of the loop, we will add one fish. Once the aquarium has 10 fish, the population limit will be reached, and the program will cease to add more fish.
Once we run the above program, we’ll receive the following output, showing the iteration of the program through the while loop until the conditions are no longer evaluated as true.
OutputThere's room for 9 more fish.
There's room for 8 more fish.
There's room for 7 more fish.
There's room for 6 more fish.
There's room for 5 more fish.
There's room for 4 more fish.
There's room for 3 more fish.
There's room for 2 more fish.
There's room for 1 more fish.
There's room for 0 more fish.
In our example, we set our while loop to run as long as the number of fish was less than the population limit of the aquarium. For each iteration, one fish is added to the aquarium until all 10 spots are filled. At that point, the loop stops running.
We already learned about the while loop, which executes a block of code for as long as a specified condition is true. Building on that is the do...while statement, which is very similar to while with the major difference being that a do...while loop will always execute once, even if the condition is never true.
Below we will demonstrate the syntax of the do...while loop.
As you can see, the do portion of the loop comes first, and is followed by while (condition). The code block will run, then the condition will be tested as it is in a normal while loop.
To test this, we can set a variable to 0, increment it inside the do statement, and set our condition to false.
Output1
Our output came out to 1, meaning that the code block iterated through the loop once (from 0) before it was stopped by an unsuccessful while condition.
While keeping in mind that the loop will iterate at least once, the do...while loop can be used for the same purposes as a while loop.
Comments
Post a Comment