Conditional Statements in JavaScript
Welcome back, friends! In this week's language lesson, we're looking at how conditional statements are written in JavaScript. A lot of what I cover in this post will be similar to Java, with a few exceptions, like the comparison operators. We will take a look at those first before jumping into conditional statement syntax.
JavaScript Comparison Operators
In Java, we learned to use == (equal) or != (not equal) for comparisons of the same data type, with the exception being .equals for strings. However, in JavaScript that is not the case. There are actually two versions of the equal/not equal operators.Abstract Equality (==)
Using double equals for comparison in JavaScript is called abstract equality, which means that if you are comparing values of different data or object types, JS will attempt to convert them to similar types through "type coercion" before comparing.Type coercion - The process of converting value from one type to another (such as string to number, object to boolean, and so on). Any type, be it primitive or an object, is a valid subject for type coercion (freecodecamp.org).For example, if you were comparing a boolean and an integer, the boolean would be converted to an integer (false = 0, true = 1) before comparing.
Strict Equality (===)
Using three equals for comparison in JS is called strict equality, and in this case the value and data/object type must be equal for the statement to be true.The example below shows a comparison between the integer 3 and character "3". Using the Abstract Equality (==) operator returns true because the data type is coerced to match the other. Using the Strict Equality (===) operator returns false because the data types do not match.
The below examples show that undefined and null are different objects (same in value, different in type), that a boolean won't be converted to a String, and the difference between a String literal and a String object.
Conditional (ternary) Operator
An interesting addition to JavaScript's conditional operator library is the use of the ternary operator, which takes three operands and can used as a shortcut for an if statement.Syntax
The syntax for a ternary expression follows this format:condition ? expr1 : expr2
Parameters & Description
condition (or conditions) = an expression that evaluates to true or false.expr1 & expr2 = are expressions with values of any type.
If the condition evaluates true, it returns the value of expr1, otherwise it returns the value of expr2.
In the example below, the ternary expression returns true if the age variable value is at or above the legal drinking age of 21.
The condition expression is "age >= 21" with the true expression returning the String "True, over 21" and the false expression returning "False, under 21."
Conditional Statements
If...Else
The syntax for the if...else conditional in JavaScript is identical to Java. We even use the same logical operators:- AND - &&
- OR - ||
- NOT - !
- Not equal - !=
- Greater than - >
- Greater than or equal to - >=
- Less than - <
- Less than or equal to - <=
Syntax
It is best practice to use curly braces around the if and else code, but not necessary. It is also perfectly valid to leave out the else and just list the other code to run, though that code will execute regardless of whether the condition is met.if (condition) {
code to execute if true
}
else {
run some other code
}
Switch
A switch statement is utilized by most high level programming languages, including Java and JavaScript, though it is not a concept we covered in CS 228. It's a version of a conditional statement where an expression is passed in and evaluated against different cases (blocks of code) and if there is a match, that block is executed. It makes more sense when you look at the syntax and the example below.
Syntax
switch (expression) {
case choice1:
run this code
break;
case choice2:
run this code instead
break;
// include as many cases as you like
default:
actually, just run this code
}
The expression in the switch parameter is evaluated and compared with each case's value (choice1, choice2). If there is a match between the two values in one of the cases, that block of code is executed. After executing the code, the program reaches the break; line, and exits the switch. If none of the cases are a match, the default code is executed.
Note: The default block does not have to appear at the end of the switch block. If the default code is written above any of the cases, it must include a "break;" at the end.
Switch Example
In this example, the Date().getDay() function is called, which returns the day of the week as an integer (Sunday = 0, Monday = 1, etc.). That value is then compared with each case's value (0-6), and if/when a match is found, the variable day is assigned with a String containing that day's name.When an alert is called with the variable day's value, that String is displayed in the pop-up as shown below.
This example did not include a default block, because there are cases for all the possible values returned by the getDay() function. So, you can have a switch statement with/without a default, depending on your needs.
Combining Cases
Also, if you want the same block of code to be executed for multiple cases, they can be combined. In this example, if it is Thursday or Friday, the text variable is assigned "Soon it is the Weekend." On Saturday and Sunday it is assigned, "It is the Weekend," and on other days of the week, the default message, "Looking forward to the Weekend," is assigned to the text variable.Note: In this post I used JSBin.com for my code examples. It's a great browser-based scripting tool that allows you to test snippets of code in HTML, CSS and JavaScript and see the output without installing any software.









This post is very thorough and is a great example of the purpose of this assignment. You learned a bunch by preparing the post, and those of us who read it will also learn a bunch. Well done.
ReplyDelete