Control Flow Statements
Total Page:16
File Type:pdf, Size:1020Kb
Control Flow Statements Christopher M. Harden Contents 1 Some more types 2 1.1 Undefined and null . .2 1.2 Booleans . .2 1.2.1 Creating boolean values . .3 1.2.2 Combining boolean values . .4 2 Conditional statements 5 2.1 if statement . .5 2.1.1 Using blocks . .5 2.2 else statement . .6 2.3 Tertiary operator . .7 2.4 switch statement . .8 3 Looping constructs 10 3.1 while loop . 10 3.2 do while loop . 11 3.3 for loop . 11 3.4 Further loop control . 12 4 Try it yourself 13 1 1 Some more types 1.1 Undefined and null The undefined type has only one value, undefined. Similarly, the null type has only one value, null. Since both types have only one value, there are no operators on these types. These types exist to represent the absence of data, and their difference is only in intent. • undefined represents data that is accidentally missing. • null represents data that is intentionally missing. In general, null is to be used over undefined in your scripts. undefined is given to you by the JavaScript interpreter in certain situations, and it is useful to be able to notice these situations when they appear. Listing 1 shows the difference between the two. Listing 1: Undefined and Null 1 var name; 2 // Will say"Hello undefined" 3 a l e r t( "Hello" + name); 4 5 name= prompt( "Do not answer this question" ); 6 // Will say"Hello null" 7 a l e r t( "Hello" + name); 1.2 Booleans The Boolean type has two values, true and false. Booleans can be used to represent conditions such as \is the user signed in", or \is the input valid". If a non-boolean value is used when JavaScript expects a boolean value, JavaScript will perform type coercion. The rules for this type coercion is fairly simple. There are six expressions that convert to false, and all other expressions become true. These six \falsy" values are: • false • null • 0 • undefined • "" • NaN 2 1.2.1 Creating boolean values By far the most common way of obtaining booleans is by performing a com- parison. This allows you to ask questions such as \are these two things equal?" and \which value is larger?". Since = is used to assign to variables, we must use a different symbol to test equality. There are actually two of these, == and ===, called the loose equality operator and the strict equality operator respectively. The difference between the two concerns type coercion. If given two different types to compare, the loose equality operator will attempt to coerce one or both types until they match, whereas the strict equality operator will immediately return false without attempting to coerce. It is preferable to use the strict equality operator whenever possible. However, the loose equality operator will often be seen in legacy code. Listing 2 shows some examples. Listing 2: Using the equality operators 1 5 == 5 ; // true 2 5 === 5 ; // true 3 1 == "1" ; // true, string becomesa number 4 1 === "1" ; // false, two different types 5 null == undefined ; // true, both falsy values 6 null === undefined ; // false, two different types 7 true == "true" ; // false, this coerces weirdly! The unique number NaN has some interesting properties when it comes to equality. NaN is the only value,x, such thatx ==x andx ===x are both false. NaN is returned if Number(x) fails to convertx into a number, which can be used to detect failed conversions. Due to the unique nature of NaN, we can use Number.isNaN(x) to check ifx is NaN more obviously. The equality operators both have equivalent inequality operators, namely != and !==, in loose and strict forms. These operators return the opposite of the corresponding equality operators. For example, if === returns true then !== returns false for the same values. For numbers, we can also check if a value is less than or greater than another value. Unsurprisingly, these are represented by < and >. We also have <= and >= to represent `less than or equal to' and `greater than or equal to'. It is important to remember that = always comes after < or > in these operators. 3 1.2.2 Combining boolean values More complicated tests can be created by combining simpler tests. To do this we need a logical operator. There are three of these: the AND oper- ator represented by &&, the OR operator represented by jj , and the NOT operator represented by !. • x&&y returns true if bothx andy are true, and false otherwise. • x jj y returns true if eitherx andy are true, and false otherwise. • !x returns true ifx is false, and true otherwise. Since ! always returns a boolean value, it is possible to use !!x to convert x into a boolean. For consistency with String() and Number(), there exists a Boolean() that also converts values to boolean values. The AND and OR operators also work on non-boolean values. They coerce values like normal to check the condition; however they are not guar- anteed to return a boolean. Instead they act slightly differently in this case. • x&&y returnsx ifx converts to false, andy otherwise. • x jj y returnsx ifx converts to true, andy otherwise. This is sometimes seen when input is taken from the user, and there exists a default value. For example, if a user refuses to answer a prompt(), you will receive as an answer null if the user clicked Cancel, and "" if the user clicked OK. Since both of these are falsy values, and are the only falsy values prompt() can return, you can assign a default value with code such as in listing 3. Listing 3: Using AND/OR with non-boolean values 1 var name= prompt( "What is your name?" ) j j "unknown person" ; 2 a l e r t( "Hello" + name); Since false &&x and true jj x can be determined without checkingx, JavaScript will not checkx at all. This property is called short-circuit evalua- tion. This is usually just an optimisation used to make your script run faster. However, ifx had any effects other than returning a value, those effects will not occur. For reasons of clarity, avoid such effects whenever possible. 4 2 Conditional statements It is often required to run code only under specific circumstances. For exam- ple, we can convert values into numbers with Number(). If the conversion fails, we get NaN. However, while we can detect a failed conversion, we can- not do anything about it. To do something about it, we need to be able to run code if and only if a conversion fails. 2.1 if statement The if statement is the most common conditional statement. Indeed, all decisions made by your scripts will eventually use an if statement to do it. It takes the form if (condition) statement;, and runs the statement if and only if the condition is true. Listing 4 shows if statements being used to get a person's age, and to adjust the value such that it is always guaranteed to be a number greater than or equal to zero. Listing 4: Using if statements 1 var age= prompt( "How old are you?" ); 2 3 i f (Number.isNaN(age)) age=0; 4 5 i f (age < 0) 6 age= −age; Listing 4 also explicitly demonstrates a property of JavaScript that has previously been left implicit. Note that lines 5 and 6 represent the same if statement. That is because white space is ignored in general. As long as the JavaScript interpreter can understand your script, it cares not for any extra white space you insert. As you write more and more scripts, you should insert white space as you please to make the script easier for you to read. Any style is acceptable as long as you remain consistent throughout a script. 2.1.1 Using blocks Sometimes you cannot express what you need to in a single statement. For example, if you have two numbers,a andb, and you need to make sure thata is the lesser number, then you need to be able to swap the variables. However, you need at least three statements to do this: one to hold the contents ofb so you have a copy, one to eraseb and fill it with the contents ofa, and one to erasea and fill it with the copy you held previously. 5 JavaScript gives you a way to group multiple statements and use it as if it was a single statement. To do this, collect the statements inside f and g. Listing 5 uses a block to perform the swapping procedure mentioned above, after detecting the problem with an if statement. Listing 5: Swapping variables 1 var a= 5; 2 var b= 3; 3 4 i f (a > b) f 5 let tmp=b; 6 b=a; 7 a=b; 8 g Inside a block, the effects of let and const change. Any variables declared by let and const inside a block disappear outside of the block. Additionally, if you declare a variable that is already defined outside the block, that variable will be hidden from you inside the block and restored when you leave the block. Thus we cannot accidentally trample over variables required in other parts of your script. Thus in listing 5, tmp is no longer usable outside of the if statement, and other tmp variables will be left untouched. Of course, since this tmp variable no longer serves a purpose after completing the swap, this is the correct thing to do. It is good practice to keep variables around only as long as you need them, and to never perform `actions at a distance'.