0% found this document useful (0 votes)
0 views

04-JavaScript-Basics

The document provides an overview of JavaScript basics, focusing on control statements, including simple, compound, and control statements like if, switch, while, and for loops. It explains Boolean expressions, operators, and the importance of functions, including predicate functions and the use of libraries like the Math library. Additionally, it includes examples and exercises to illustrate the concepts discussed.

Uploaded by

Goutam Paul
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

04-JavaScript-Basics

The document provides an overview of JavaScript basics, focusing on control statements, including simple, compound, and control statements like if, switch, while, and for loops. It explains Boolean expressions, operators, and the importance of functions, including predicate functions and the use of libraries like the Math library. Additionally, it includes examples and exercises to illustrate the concepts discussed.

Uploaded by

Goutam Paul
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

9/27/22

JavaScript Basics

Control Statements
Jerry Cain
CS 106AX
September 28, 2022
slides leveraged from those written by Eric Roberts

1 2

Statement Types in JavaScript Boolean Expressions


• JavaScript defines two types of operators that work with
• Statements in JavaScript fall into three basic types: Boolean data: relational operators and logical operators.
– Simple statements
• There are six relational operators that compare values of other
– Compound statements
types and produce a true/false result:
– Control statements
= == Equals !== Not equals
• Simple statements are typically assignments, function calls, or < Less than <= Less than or equal to
applications of the ++ or -- operators. Simple statements are > Greater than >= Greater than or equal to
always terminated with a semicolon.
• Compound statements (also called blocks) are sequences of For example, the expression n <= 10 has the value true if n is
statements enclosed in curly braces. less than or equal to 10 and the value false otherwise.
• There are also three logical operators:
• Control statements fall into two categories:
– Conditional statements that require some test be evaluated && Logical AND p && q means both p and q
– Iterative statements that specify repetition || Logical OR p || q means either p or q (or both)
! Logical NOT !p means the opposite of p

3 4

Notes on the Boolean Operators Short-Circuit Evaluation


• Remember that JavaScript uses = for assignment. To test • JavaScript evaluates the && and || operators using a strategy
whether two values are equal, you must use the = = = operator. called short-circuit mode in which it evaluates the right
• It is not legal in JavaScript to use more than one relational operand only if it needs to do so.
operator in a single comparison. To express the idea • For example, if n is 0, the right operand of && in
embodied in the mathematical expression
n !== 0 && x % n === 0
0 ≤ x ≤ 9
is not evaluated at all because n !== 0 is false. Because the
you need to make both comparisons explicit, as in expression
0 <= x && x <= 9 false && anything
• The || operator means either or both, which is not always is always false, the rest of the expression no longer matters.
clear in the English interpretation of or.
• One of the advantages of short-circuit evaluation is that you
• Be careful when you combine the ! operator with && and || can use && and || to prevent errors. If n were 0 in the earlier
because the interpretation often differs from informal English. example, evaluating x % n would result in a division by zero.

5 6

1
9/27/22

The if Statement Functions Involving Control Statements


• The simplest of the control statements is the if statement, • The body of a function can contain statements of any type,
which occurs in two forms. You use the first when you need including control statements. As an example, the following
to perform an operation only if a particular condition is true: function uses an if statement to find the larger of two values:
if (condition) { function max(x, y) {
statements to be executed if the condition is true if (x > y) {
} return x;
} else {
• You use the second form whenever you need to choose return y;
}
between two alternative paths, depending on whether the }
condition is true or false:

if (condition) { • As this example makes clear, return statements can be used


statements to be executed if the condition is true at any point in the function and may appear more than once.
} else {
statements to be executed if the condition is false
}

7 8

The switch Statement Example of the switch Statement


JavaScript
The
If none
When of then
evaluates
the
JavaScript
switch looks
statement
values statements
for
in a case
provides
executesthe
provides aain
acase clause
the case
that
convenient
clauses
convenient
switch matches
or default
match
syntax
statement, thefor
syntax expression.
clause
expression,
itforchoosing
begins
choosing
by The switch statement is useful when a function must choose
until
If expression
it reaches
JavaScript
evaluating
among ofis possible
aequal
evaluates
a setexpression. to or
the
break vstatements
2,aJavaScript
paths:returnin statement.
chooses
the the second
default clause.clause. among several cases, as in the following example:
function monthName(month) {
switch ( expression ) { switch (month) {
case 1: return "January";
case v 1:
case 2: return "February";
statements to be executed if expression is
= equal
v1 to v 1
case 3: return "March";
break; case 4: return "April";
case v 2: case 5: return "May";
statements to be executed if expression is
= equal
v2 to v 2 case 6: return "June";
break; case 7: return "July";
. . . more case clauses if needed . . . case 8: return "August";
default: case 9: return "September";
statements to be executed if no values match case 10: return "October";
case 11: return "November";
break;
case 12: return "December";
} default: return undefined;
}
}

9 10

The while Statement The digitSum Function


• The while statement is the simplest of JavaScript’s iterative
control statements and has the following form:

while ( condition ) {
statements to be repeated
}
n result
n1729 sum
19
• When JavaScript encounters a while statement, it begins by 1729
172
17
1
0 11
18
19
9
0
evaluating the condition in parentheses.
• If the value of condition is true, JavaScript executes the
statements in the body of the loop.
• At the end of each cycle, JavaScript reevaluates condition to
see whether its value has changed. If condition evaluates to digitSum(1729) = 19
false, JavaScript exits from the loop and continues with the
statement following the end of the while body.

11 12

2
9/27/22

The for Statement Exercise: Reading for Statements


• The for statement in JavaScript is a powerful tool for Describe the effect of each of the following for statements:
specifying the structure of a loop independently from the
operations the loop performs. The syntax looks like this: 1. for (let i = 1; i <= 10; i++)

This statement executes the loop body ten times, with the control
for ( init ; test ; step ) { variable i taking on each successive value between 1 and 10.
statements to be repeated
} 2. for (let i = 0; i < n; i++)

This statement executes the loop body n times, with i counting from
• JavaScript evaluates a for statement as follows: 0 to n - 1 . This version is the standard Repeat-n-Times idiom.
1. Evaluate init, which typically declares a control variable.
2. Evaluate test and exit from the loop if the value is false. 3. for (let n = 99; n >= 1; n -= 2)

3. Execute the statements in the body of the loop. This statement counts backward from 99 to 1 by twos.
4. Evaluate step, which usually updates the control variable.
4. for (let x = 1; x <= 1024; x *= 2)
5. Return to step 2 to begin the next loop cycle.
This statement executes the loop body with the variable x taking on
successive powers of two from 1 up to 1024.

13 14

The factorial Function The factorialTable Function


• The factorial of a number n (which is usually written as n! in
mathematics) is defined to be the product of the integers from
1 up to n. Thus, 5! is equal to 120, which is 1 x 2 x 3 x 4 x 5.
5040
1
• The following function definition uses a for loop to compute
the factorial function:
min max i
n 0 result
7 i 6
8
0
1
7
function fact(n) {
let result = 1; 0
7 5040
120
720
24
1
2
6 1
2
3
4
5
6
7
8
for (let i = 1; i <= n; i++) {
result = result * i; -> factorialTable(0, 7);
} 0! = 1
return result; 1! = 1
} 2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
->

15 16

Comparing for and while


• The for statement

for ( init ; test ; step ) {


statements to be repeated
}

is functionally equivalent to the following code using while:


Functions Mechanics
init;
while ( test ) {
statements to be repeated
step;
}

• The advantage of the for statement is that everything you


need to know to understand how many times the loop will run
is explicitly included in the header line.

17 18

3
9/27/22

A Quick Review of Functions Review: Syntax of Functions


• The concept of a function should be familiar to you from prior • The general form of a function definition is
programming experience. All modern programming
languages allow functions to be defined. function name(parameter list) {
• At the most basic level, a function is a sequence of statements statements in the function body
that has been collected together and given a name. The name }
makes it possible to execute the statements much more easily;
instead of copying out the entire list of statements, you can where name is the name of the function, and parameter list is
just provide the function name. a list of variables used to hold the values of each argument.

• The following terms are useful when working with functions: • You can return a value from a function by including one or
more return statements, which are usually written as
– Invoking a function by name is known as calling that function.
– The caller passes information to a function using arguments. return expression;
– When a function completes its operation, it returns to its caller.
– A function gives information to the caller by returning a result. where expression is an expression that specifies the value you
want to return.

19 20

Nonnumeric Functions Exercise: Console Pyramid


• Although functions return a single value, that value can be of • Write a program that uses the concatNCopies function to
any type. display a pyramid on the console in which the bricks are
represented by the letter x. The number of levels in the
• Even without learning the full range of string operations
pyramid should be defined as the constant N_LEVELS.
covered in Chapter 7, you can already write string functions
that depend only on concatenation, such as the following • For example, if N_LEVELS is 10, the console output should
function that concatenates together n copies of the string str: look like this:
function concatNCopies(n, str) { ConsolePyramid
let result = ""; x
for (let i = 0; i < n; i++) { xxx
result += str; xxxxx
} xxxxxxx
xxxxxxxxx
return result;
xxxxxxxxxxx
}
xxxxxxxxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxx

21 22

Predicate Functions Using Predicate Functions Effectively


• Functions that return Boolean values play a central role in • New programmers often seem uncomfortable with Boolean
programming and are called predicate functions. As an values and end up writing ungainly code. For example, a
example, the following function returns true if the first beginner might write isDivisibleBy like this:
argument is divisible by the second, and false otherwise: function isDivisibleBy(x, y) {
if (x % y === 0) {
function isDivisibleBy(x, y) {
return true;
return x % y === 0;
} else {
}
return false;
}
• Once you have defined a predicate function, you can use it }
any conditional expression. For example, you can print the
integers between 1 and 100 that are divisible by 7 as follows: While this code is technically correct, it is inelegant and
should be replaced by return x % y === 0.
for (let i = 1; i <= 100; i++) {
if (isDivisibleBy(i, 7)) { • A similar problem occurs when novices explicitly check to
println(i); see whether a predicate function returns true. You should be
} careful to avoid such redundant tests in your own programs.
}

23 24

4
9/27/22

The Purpose of Parameters Libraries


“All right, Mr. Wiseguy,” she said, “you’re so clever, • To make programming easier, all modern languages include
you tell us what color it should be.”
— Douglas Adams, The Restaurant collections of predefined functions. Those collections are
at the End of the Universe, 1980 called libraries.
• In general, functions perform some service to their callers. In • For programming that involves mathematical calculations, the
order to do so, the function needs to know any details most useful library is the Math library, which includes a
required to carry out the requested task. number of functions that will be familiar from high-school
mathematics (along with many that probably aren’t). A list of
• Imagine that you were working as a low-level animator at the most important functions appears on the next slide.
Disney Studies in the days before computerized animation
and that one of the senior designers asked you to draw a filled • In JavaScript, each of the functions in the Math library begins
circle. What would you need to know? with the library name followed by a dot and then the name of
the function. For example, the function that calculates square
• At a minimum, you would need to know where the circle roots is named Math.sqrt.
should be placed in the frame, how big to make it, and what
color it should be. Those values are precisely the information • You call library functions just like any other function, so that
conveyed in the parameters. calling Math.sqrt(16) returns the value 4.

25 26

Useful Functions in the Math Library


Math.PI The mathematical constant π
Math.E The mathematical constant e
Math.abs(x) The absolute value of x
Math.max(x, y, . . .) The largest of the arguments
Math.min(x, y, . . .) The smallest of the arguments
Math.round(x)
Math.floor(x)
The closest integer to x
The largest integer not exceeding x
Decomposition
Math.log(x) The natural logarithm of x
Math.exp(x) The inverse logarithm (e x)
Math.pow(x, y) The value x raised to the y power (x y)
Math.sin(q ) The sine of q, measured in radians
Math.cos(q ) The cosine of q, measured in radians
Math.sqrt(x) The square root of x
Math.random() A random value between 0 and 1

27 28

Decomposition Criteria for Choosing a Decomposition


• The most effective way to solve a complex problem is to 1. The proposed steps should be easy to explain. One
break it down into successively simpler subproblems. indication that you have succeeded is being able to find
• You start by breaking the whole task down into simpler parts. simple names.

• Some of those tasks may themselves need subdivision. 2. The steps should be as general as possible. Programming
• This process is called stepwise refinement or decomposition. tools get reused all the time. If your methods perform
general tasks, they are much easier to reuse.
Complete Task
3. The steps should make sense at the level of abstraction at
which they are used. If you have a method that does the
right job but whose name doesn’t make sense in the context
Subtask #1 Subtask #2 Subtask #3 of the problem, it is probably worth defining a new method
that calls the old one.

Subsubtask #2a Subsubtask #2b

29 30

5
9/27/22

Exercise: Ruth-Aaron Pairs


• Write a program that lists the first NUM_PAIRS Ruth-Aaron
pairs. In recreational mathematics, a Ruth-Aaron pair
consists of two neighboring integers—e.g. 714 and 715—for
which the sum of the distinct prime factors of each are equal.
• The pairs are named Ruth-Aaron as a nod to baseball greats
Babe Ruth and Hank Aaron. Ruth held the record for most The End
career home runs at 714 until
Aaron’s hit his 715th on
April 8th, 1974.
• If NUM_PAIRS equals 15, the
program should publish the
output presented on the right.

31 32

You might also like