Sunday, October 20, 2019
Introduction to the JavaScript If Statement
Introduction to the JavaScript If Statement The JavaScript if statement performs an action based on a condition, a common scenario in all programming languages.The if statement tests a bit of data against a condition, and then specifies some code to be executed if the condition is true, like so: if condition {à à à execute this code} The if statement is almost always paired with the else statement because usually, you want to define an alternative bit of code to execute. Lets consider an example: if (Stephen name) {à à message Welcome back Stephen;} else {à à message Welcome name;} This code returns Welcome back Stephen if name is equal to Stephen; otherwise, it returns Welcome and then whatever value the variable name contains. A Shorter IF Statement JavaScript provides us with an alternative way of writing an if statement when both the true and false conditionsà just assign different values to the same variable. This shorter way omits the keyword if as well as the braces around the blocks (which are optional for single statements). We also move the value that we are setting in both the true and false conditions to the front of our single statement and embed this new style of if statement into the statement itself.à Heres how this looks: variable (condition) ? true-value : false-value; So our if statement from above could be written all in one line as: message (Stephen name) ? Welcome back Stephen : Welcome name; As far as JavaScript is concerned, this one statement is identical to the longer code from above. The only difference is that writing the statement this way actually provides JavaScript with more information about what the if statement is doing. The code can run more efficiently than if we wrote it the longer and more readable way. This is also called a ternary operator. Assigning Multiple Values to a Single Variable This way of coding an if statement can help avoid verbose code, particularly in nested if statements. For example, consider this set of nested if/else statements: var answer;if (a b) {à if (a c) {à à answer all are equal;à } else {à à answer a and b are equal;à }} else {à if (a c) {à à answer a and c are equal;à } else {à à if (b c) {à à à answer b and c are equal;à à } else {à à à answer all are different;à à }à }} This code assigns one of five possible values to a single variable. Using this alternative notation, we can considerably shorten this into just one statement that incorporates all of the conditions: var answer (a b) ? ((a c) ? all are equal :a and b are equal) : (a c) ? a and c are equal : (b c) ?b and c are equal : all are different; Note that this notation can be used only when all the different conditions being tested are assigning different values to the same variable.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment