04-JavaScript-Basics
04-JavaScript-Basics
JavaScript Basics
Control Statements
Jerry Cain
CS 106AX
September 28, 2022
slides leveraged from those written by Eric Roberts
1 2
3 4
5 6
1
9/27/22
7 8
9 10
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
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
15 16
17 18
3
9/27/22
• 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
21 22
23 24
4
9/27/22
25 26
27 28
• 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.
29 30
5
9/27/22
31 32