0% found this document useful (0 votes)
21 views68 pages

JavaScript Expressions and Control Flow

This document provides an overview of expressions and control flow in JavaScript, including the use of literals, variables, operators, and conditionals. It explains how to create expressions, the differences between JavaScript and PHP, and the various types of operators available in JavaScript. Additionally, it covers error handling techniques such as onerror and try...catch, as well as conditional statements like if and else.

Uploaded by

skhulilena4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views68 pages

JavaScript Expressions and Control Flow

This document provides an overview of expressions and control flow in JavaScript, including the use of literals, variables, operators, and conditionals. It explains how to create expressions, the differences between JavaScript and PHP, and the various types of operators available in JavaScript. Additionally, it covers error handling techniques such as onerror and try...catch, as well as conditional statements like if and else.

Uploaded by

skhulilena4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Schools of Computing & Mathematical Sciences

Multimedia fundamentals 242

Expressions and control flow


in JavaScript
Objective
At the end of this session, you should be able to demonstrate an
understanding of expressions and control flow in the JavaScript
language

2
Expressions [1/3]
• JavaScript expressions are very similar to those in PHP.
• Below are some examples of simple Boolean expressions

<script>
[Link]("a:"+(42 > 3)+"<br>")
[Link]("b:"+(91 < 4)+"<br>")
[Link]("c:"+(8 == 2)+"<br>")
[Link]("d:"+(4 < 17)+"<br>")
</script>

3
Expressions [2/3]
• The output of this code (previous slide) is as follows:

a: true
b: false
c: false
d: true

• Notice that both expressions a: and d: evaluate to true. But b: and c:


evaluate to false. Unlike PHP (which would print the number 1 and
nothing, respectively), actual strings of true and false are displayed.

4
Expressions [3/3]
• Unlike in PHP, when referring to the Boolean literals, the JavaScript
strings true and false must be in lowercase.
• Therefore, considering the code given below, only the first statement
will display, printing the lowercase word true, because the second will
cause a 'TRUE' is not defined error:

if (1 == true) [Link]('true') // True


if (1 == TRUE) [Link]('TRUE') // Will cause an error

NB. Remember that any code snippets you wish to type and try for yourself in an HTML file need to be
enclosed within <script> and </script> tags.

5
Literals and variables [1/3]
• The simplest form of an expression is a literal, which means
something that evaluates to itself, such as the number 22 or the
string "Press Enter".
• An expression could also be a variable, which evaluates to the value
that has been assigned to it.
• Literal and variables are both types of expressions, because they
return a value.

6
Literals and variables [2/3]
The code below shows three different literals and two variables, all of
which return values, albeit of different types.
<script>
myname = "Peter"
myage = 24
[Link]("a:"+42 +"<br>") //Numeric literal
[Link]("b:"+"Hi" +"<br>") //String literal
[Link]("c:"+true +"<br>") //Constant literal
[Link]("d:"+myname+"<br>") //String variable
[Link]("e:"+myage +"<br>") //Numeric variable
</script>

7
Literals and variables [3/3]
The script (previous slide) outputs the following:

a: 42
b: Hi
c: true
d: Peter
e: 24

8
Operators [1/3]
• Operators enable the creation of more complex expressions that evaluate
to useful results.
• Assignments or control-flow constructs are combined with expressions to
create statements.
• Below is an example of two simple statements: the first assigns the result
of the expression 366 - day_number to the variable days_to_new_year,
and the second outputs a friendly message only if the expression
days_to_new_year < 30 evaluates to true.

<script>
days_to_new_year = 366 - day_number;
if (days_to_new_year < 30) [Link]("It's nearly New Year")
</script>

9
Operators [2/3]
JavaScript offers a lot of powerful operators that range from arithmetic,
string, and logical operators to assignment, comparison, and more. The
table below lists some of the JavaScript operator types.

10
Operators [3/3]
Each operator takes a different number of operands:
• Unary operators, such as incrementing (a++) or negation (-a), take a
single operand.
• Binary operators, which represent the bulk of JavaScript operators –
including addition, subtraction, multiplication, and division—take two
operands.
• One ternary operator, which takes the form ? x : y. It is a terse single-
line if statement that chooses between two expressions depending on
the evaluation of the condition.

11
Operator precedence [1/2]
• As with PHP, JavaScript utilizes operator precedence, in which some
operators in an expression are considered more important than
others and are therefore evaluated first.
• The table on the next slide lists JavaScript’s operators and their
precedencies, from the highest to the lowest.

12
Operator precedence [2/2]
High to low

13
Associativity [1/2]
• Most JavaScript operators are processed in order from left to right in
an equation. But some operators require processing from right to left
instead.
• The direction of processing is called the operator’s associativity.
• This associativity becomes important in cases where you do not
explicitly force precedence. For example, consider the following
assignment operators, by which three variables are all set to the value
0:
level = score = time = 0

14
Associativity [2/2]
Operators and associativity

15
<intentionally left blank>

16
Relational operators
• Relational operators test two operands and return a Boolean result of
either true or false.
• There are three types of relational operators:
- equality
- comparison
- logical.

17
Equality operators [1/3]
• The equality operator == tests values for equality.
• Here is an example of assigning a value and testing for equality:
<script>
month = "July"
if (month == "October") [Link]("It's the Fall")
</script>
• The first statement assigns a value, and the second tests it for
equality. As it stands, nothing will be printed out, because month is
assigned the string value July, and therefore the check for it having a
value of October will fail.

18
Equality operators [2/3]
• If the two operands of an equality expression are of different types,
JavaScript will convert them to whatever type makes best sense to it.
• For example, any strings composed entirely of numbers will be
converted to numbers whenever compared with a number.
• Consider the example below:
<script>
a = 3.1415927
b = "3.1415927"
if (a == b) [Link]("1")
if (a === b) [Link]("2")
</script>
19
Equality operators [3/3]
• In the previous example, a and b are two different values (one is a
number and the other is a string), and we would therefore normally
expect neither of the if statements to output a result.
• However, if the script is run, it outputs the number 1, which means
that the first if statement evaluated to true. This is because the string
value of b was first temporarily converted to a number, and therefore
both halves of the equation had a numerical value of 3.1415927.
• In contrast, the second if statement uses the identity operator, three
equals signs in a row, which prevents JavaScript from automatically
converting types.

20
Comparison operators [1/2]
• Comparison operators, can be used to test for more than just equality and
inequality. JavaScript also provides > (is greater than), < (is less than), >= (is
greater than or equal to), and <= (is less than or equal to) to work with.
• The following code gives an example of the four comparison operators in
use:
<script>
a = 7; b = 11
if (a > b) [Link]("a is greater than b<br>")
if (a < b) [Link]("a is less than b<br>")
if (a >= b) [Link]("a is greater than or equal to b<br>")
if (a <= b) [Link]("a is less than or equal to b<br>")
</script>

21
Comparison operators [2/2]
In this example, where a is 7 and b is 11, the following is output
(because 7 is less than 11, and also less than or equal to 11):

a is less than b
a is less than or equal to b

22
Logical operators [1/3]
Logical operators produce true-or-false results, and are also known as
Boolean operators. There are three of them in JavaScript as shown
below

23
Logical operators [2/3]
• Below is an example of the logical operators in use:

<script>
a = 1; b = 0
[Link]((a && b) + "<br>")
[Link]((a || b) + "<br>")
[Link](( !b ) + "<br>")
</script>

• The above program outputs 0, 1, and true

24
Logical operators [3/3]
• In the previous example, the && statement requires both operands to
be true if it is going to return a value of true, the || statement will be
true if either value is true, and the third statement performs a NOT on
the value of b, turning it from 0 into a value of true.
• The table below shows all the possible variations of using the logical
operators. Also note that !true equals false, and !false equals true.

25
<Intentionally left blank>

26
The with statement [1/3]
• The with statement is one of the statements exclusive to JavaScript.
• It is used to simplify some types of JavaScript statements by reducing many
references to an object to just one reference.
• Consider the following code in which the [Link]() function
references a variable called string:
<script>
string = "The quick brown fox jumps over the lazy dog"

[Link]("The string is " + [Link] + " characters<br>")


[Link]("In upper case it's: " +[Link]())
</script>

27
The with statement [2/3]
• The previous code can be rewritten using the with statement
• As shown below, using the with statement, the [Link] ()
function never references the variable string by name
<script>
string = "The quick brown fox jumps over the lazy dog"

with (string)
{
[Link]("The string is " + length + " characters<br>")
[Link]("In upper case it's: " + toUpperCase())
}
</script>

28
The with statement [3/3]
• The JavaScript interpreter recognizes that the length property and
toUpperCase() method have to be applied to some object.
• Because they stand alone, the interpreter assumes they apply to the
string object that is specified in the with statement.
• The code outputs the following:

The string is 43 characters


In upper case it's: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG

29
Using onerror [1/4]
• Onerror event or a combination of the try and catch keywords can be
used to catch JavaScript errors and take appropriate action.
• Events refer to actions that can be detected by JavaScript.
• Every element on a web page has certain events that can trigger
JavaScript functions. For example, the onclick event of a button
element can be set to call a function and make it run whenever a user
clicks the button.
• The next slide illustrates how to use the onerror event.

30
Using onerror [2/4]
A script employing the onerror event:
<script>
onerror = errorHandler
[Link]("Welcome to this website") // Deliberate error
function errorHandler(message, url, line)
{
out = "Sorry, an error was encountered.\n\n";
out += "Error: " + message + "\n";
out += "URL: " + url + "\n";
out += "Line: " + line + "\n\n";
out += "Click OK to continue.\n\n";
alert(out);
return true;
}
</script>

31
Using onerror [3/4]
• The first line of this script (previous slide) tells the onerror event to
use the new errorHandler function from that point onward.
• The function takes three parameters -a message, a url, and a line
number, which can all be displayed in an alert pop up quite easily.
• Then, to test the new function, a syntax error is deliberately placed in
the code with a call to [Link]() instead of [Link]().
• Using onerror this way can also be quite useful during the debugging
process. The next slide shows the result of running this script
(previous slide) in a browser.

32
Using onerror [4/4]
Using the onerror event with an alert method pop-up

33
Using try...catch [1/5]
• The try...catch construct is used to trap errors for a selected section of
code, rather than all scripts in a document.
• The try and catch keywords are more standard and more flexible than
the onerror technique shown in the previous section.
• But note that try...catch does not catch syntax errors, for which you
need onerror.
• The try...catch construct is supported by all major browsers and can
be used to catch certain conditions that you are aware could occur in
a specific part of the code.

34
Using try...catch [2/5]
• Some objects are not supported in some browsers.
• For example, the XMLHttpRequest object is not available in Internet
Explorer. Therefore, try...catch can be used to trap this case and do
something else if the function is not available.
• The script in the next slide illustrates how to trap an error with try
and catch.

35
Using try...catch [3/5]

<script>
try
{
request = new XMLHTTPRequest()
}
catch(err)
{
// Use a different method to create an XML HTTP Request object
}
</script>

36
Using try...catch [4/5]
• Note that detail of how to implement the missing object in Internet
Explorer is not include in the previous example. The example aims to show
how the system works.
• There is also another keyword associated with try and catch called finally
that is always executed, regardless of whether an error occurs in the try
clause.
• To use it, just add something like the following statements after a catch
statement:
finally
{
alert("The 'try' clause was encountered")
}

37
Using try...catch [5/5]
Example: using try...catch and finally keywords
<script>
try
{
request = new XMLHTTPRequest()
}
catch(err)
{
// Use a different method to create an XML HTTP Request object
}
finally
{
alert("The 'try' clause was encountered")
}
</script>

38
<intentionally left blank>

39
Conditionals
• Conditionals alter program flow. They enable asking questions about
certain things and responding in different ways depending on the
answers.
• There are three types of nonlooping conditionals:
- the if statement,
- the switch statement, and
- the ? operator.

40
The if statement
• The code within an if statement is executed only if the given expression
evaluates to true.
• Multiline if statements require curly braces around them, but like in PHP,
the braces can be omitted for single statements. Therefore, the following
statements are valid:
if (a > 100)
{
b=2
[Link]("a is greater than 100")
}

if (b == 10) [Link]("b is equal to 10")

41
The else statement [1/2]
The else statement is used to execute an alternative when a condition
has not been met as shown below.

if (a > 100)
{
[Link]("a is greater than 100")
}
else
{
[Link]("a is less than or equal to 100")
}

42
The else statement [2/2]
Unlike PHP, JavaScript has no elseif statement, but that is not a problem, because
an else can be used followed by another if to form the equivalent of an elseif
statement, as illustrated below:
if (a > 100)
{
[Link]("a is greater than 100")
}
else if(a < 100)
{
[Link]("a is less than 100")
}
else
{
[Link]("a is equal to 100")
}

43
The switch statement [1/4]
• The switch statement is useful when one variable or the result of an
expression can have multiple values, and you want to perform a different
function for each value.
• Consider the following sample main menu code written using if...else if...
statements:
<script>
if (page == "Home") [Link]("You selected Home")
else if (page == "About") [Link]("You selected About")
else if (page == "News") [Link]("You selected News")
else if (page == "Login") [Link]("You selected Login")
else if (page == "Links") [Link]("You selected Links")
</script>

44
The switch statement [2/4]
The multiline if...else if... statement can be rewritten using a switch construct as illustrated below:
<script>
switch (page)
{
case "Home":
[Link]("You selected Home")
break
case "About":
[Link]("You selected About")
break
case "News":
[Link]("You selected News")
break
case "Login":
[Link]("You selected Login")
break
case "Links":
[Link]("You selected Links")
break
}
</script>

45
The switch statement [3/4]
• In the example given, the variable page is mentioned only once at the
start of the switch statement. Thereafter, the case command checks
for matches and the matching conditional statement is executed.
• Note that the code is illustrative, a real program would have code
here to display or jump to a page, rather than simply telling the user
what was selected.
• Also note the use of the break command inside the switch statement
to break out of the switch statement once a condition is met. The
break command should be included, except when it is required that
execution continues to the next case.

46
The switch statement [4/4]
• When no condition is satisfied, a default action for a switch statement
can be specified by using the default keyword.
• Below is code snippet that could be inserted into the previous
example:

default:
[Link]("Unrecognized selection")
break

47
The ? Operator [1/2]
• The ternary operator (?), combined with the : character, provides a
quick way of doing if...else tests.
• An expression to evaluate is written, followed by a ? (question mark
symbol) and the code to execute if the expression is true, and then a :
(full colon) followed by the code to execute if the expression
evaluates to false.
• The example on the next slide shows the ? ternary operator being
used to print out whether the variable a is less than or equal to 5, and
prints something either way.

48
The ? Operator [2/2]

<script>
[Link](
a <= 5 ?
"a is less than or equal to 5" :
"a is greater than 5"
)
</script>

In the above example, the statement has been broken up into several lines
for clarity, but such a statement is more likely to be used on a single line, in
this manner:
size = a <= 5 ? "short" : "long"
49
<intentionally left blank>

50
Looping
There are many close similarities between JavaScript and PHP when it
comes to looping. Both languages support while, do...while, and for
loops.

51
While loop [1/3]
• A JavaScript while loop first checks the value of an expression and
starts executing the statements within the loop only if that expression
is true. If it is false, execution skips over to the next JavaScript
statement (if any).
• Upon completing an iteration of the loop, the expression is again
tested to see if it is true, and the process continues until such a time
as the expression evaluates to false or until execution is otherwise
halted.

52
While loop [2/3]
A while loop example:

<script>
counter=0

while (counter < 5)


{
[Link]("Counter: " + counter + "<br>")
++counter
}
</script>

53
While loop [3/3]
This script outputs the following:
Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4

Note. If the variable counter were not incremented within the loop, it is
quite possible that some browsers could become unresponsive due to a
never-ending loop, and the page may not even be easy to terminate
with Escape or the Stop button. So be careful with JavaScript loops.

54
do...while loop [1/2]
• The do...while loop is used when it is required that a loop iterates at least
once before any tests are made.
• Below is an example do...while loop that outputs the first seven results in
the 7 times table.
<script>
count = 1

do
{
[Link](count + " times 7 is " + count * 7 + "<br>")
} while (++count <= 7)
</script>

55
do...while loop [2/2]
The loop in the previous slide outputs the following:

1 times 7 is 7
2 times 7 is 14
3 times 7 is 21
4 times 7 is 28
5 times 7 is 35
6 times 7 is 42
7 times 7 is 49

56
for loop [1/3]
• The for loop combines an initialization expression, a condition
expression, and a modification expression into a single looping
construct.
• These are separated by semicolons, like this: for (expr1 ; expr2 ;
expr3). At the start of the first iteration of the loop, the initialization
expression is executed.
• Then, each time around the loop, the condition expression is tested,
and the loop is entered only if the condition is true.

57
for loop [2/3]
Example: multiplication table for 7 using a for loop

<script>
for (count = 1 ; count <= 7 ; ++count)
{
[Link](count + "times 7 is " + count * 7 + "<br>");
}
</script>

58
for loop [3/3]
• Like in PHP, multiple variables can be assigned in the first parameter
of a for loop by separating them with a comma, like this:
for (i = 1, j = 1 ; i < 10 ; i++)
• Similarly, multiple modifications can be performed in the last
parameter, like this:
for (i = 1 ; i < 10 ; i++, --j)
• Alternatively, multiple variable assignment and modification can both
be done at the same time as shown belo:
for (i = 1, j = 1 ; i < 10 ; i++, --j)

59
Breaking out of a loop [1/3]
• The break command used inside a switch statement is also available
within for loops.
• Breaking out of a loop might be needed, for example, when
searching for a match of some kind. The break command can be
applied to terminate the search once the match is found.
• The next slide gives an example of how to use the break command.

60
Breaking out of a loop [2/3]

<script>
haystack = new Array()
haystack[17] = "Needle"
for (j = 0 ; j < 20 ; ++j)
{
if (haystack[j] == "Needle")
{
[Link]("<br>- Found at location " + j)
break
}
else [Link](j + ", ")
}
</script>

61
Breaking out of a loop [3/3]
This script outputs the following:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,


- Found at location 17

62
The continue statement [1/3]
• The continute command is used to skip the remaining statement of an
iteration, and go to the next iteration of the loop.
• The next slide gives an example to illustrate how to use the continue
command in a for loop.

63
The continue statement [2/3]
<script>
haystack = new Array()
haystack[4] = "Needle"
haystack[11] = "Needle"
haystack[17] = "Needle"
for (j = 0 ; j < 20 ; ++j)
{
if (haystack[j] == "Needle")
{
[Link]("<br>- Found at location " + j + "<br>")
continue
}
[Link](j + ", ")
}
</script>
64
The continue statement [3/3]
Notice how the second [Link] call does not have to be
enclosed in an else statement (as it did before), because the continue
command will skip it if a match has been found. The output from this
script is as follows:

0, 1, 2, 3,
- Found at location 4
5, 6, 7, 8, 9, 10,
- Found at location 11
12, 13, 14, 15, 16,
- Found at location 17
18, 19,

65
Explicit casting [1/2]
• Unlike PHP, JavaScript has no explicit casting of types such as (int) or
(float).
• Instead, one of JavaScript’s built-in type-changing functions shown
below, can be used for a value to be a certain type.

66
Explicit casting [2/2]
• For example, to change a floating-point number to an integer, you
could use code such as the following (which displays the value 3):

n = 3.1415927
i = parseInt(n)
[Link](i)

• Alternatively, the compound form could be used as illustrated below:


[Link](parseInt(3.1415927))

67
End

68

You might also like