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

7A Recap of Programming in JavaScript

Uploaded by

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

7A Recap of Programming in JavaScript

Uploaded by

Sophia Lindholm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Recap of Programming in JavaScript

Cosmin E. Oancea
[email protected]

Department of Computer Science (DIKU)


University of Copenhagen

October 2023
Teaching Plan & Format

For the next 5 weeks, we take a glance at concepts from 4


fields of study, which provide the necessary ingredients for
you to eventually become decent programmers.
How?
Teaching Plan & Format

For the next 5 weeks, we take a glance at concepts from 4


fields of study, which provide the necessary ingredients for
you to eventually become decent programmers.
How? Crawl before you walk, walk before you run!
Lectures: focus on how to reason about it (the big picture), but applied
to illustrative code examples;
Exercise: you practice on lecture’s code examples or similar. How?
Teaching Plan & Format

For the next 5 weeks, we take a glance at concepts from 4


fields of study, which provide the necessary ingredients for
you to eventually become decent programmers.
How? Crawl before you walk, walk before you run!
Lectures: focus on how to reason about it (the big picture), but applied
to illustrative code examples;
Exercise: you practice on lecture’s code examples or similar. How?
I by translating a detailed textual description of an algorithm
into a correct implementation of it;
I we gradually deliver larger code bases to you, in which you
will implement some of the cogs of a larger machinery;
I a lot can be learned by looking around, i.e., what is the design
of the larger machine, how does it relies on your cogs, how
does the javascript code interacts with the HTML + CSS code.
Pattern matching and reverse engineering are key methods to
understanding!
Teacher-Student Contract
Have continued to simplify the (last-year) material, as promised!

What is the student’s part?


come to lectures and exercise session;
give your best shot at solving the exercises;
most importantly discuss, ask for help, clarification!
we have common goals here (friends, not enemies)

What is the teacher’s part?


Teacher-Student Contract
Have continued to simplify the (last-year) material, as promised!

What is the student’s part?


come to lectures and exercise session;
give your best shot at solving the exercises;
most importantly discuss, ask for help, clarification!
we have common goals here (friends, not enemies)

What is the teacher’s part?


will try to adapt the teaching to the class;
we can talk about (extra) office hours, etc;
will come a bit earlier and stay a bit longer before/after class;
don’t send me e-mails unless in emergency: too many of you;
What else would you like? Let me know and we will try.
Programming Language
This lecture:
1st hour: we take a more theoretical look at the language grammar side of it:
to demystify some of the magic (now that you gained some
experience)
to demonstrate some common programming errors.
2nd hour: we implement the greatest-common divisor (GCD) algorithm:
as an exercise in translating a textual description into code;
demonstrates the usefulness of functions.

What I want to impress on you is that a programming language, such as Javascript, is a


very simple language in which you have to express yourself in a very precise way:
it has a (relatively-simple) grammar,
if you are not precise enough it may result in
1. a syntax error (if you are lucky), or
2. worse, in a program that does not do what you intend, i.e., hard to trace bugs
Possible Syntactic Categories of a Language

Variable/Function Names and Values (numbers, strings)


Expressions
I addition
I multiplication
I function call
I ...
Statements:
I variable declaration;
I assignment statement;
I Scope (block of statement enclosed in curly brackets)
I Loop statement (for/while)
I If-then-else statement
Function Declaration
Values and Variables
Example of values of different types/kinds:
integers: 10, 15, 100, . . .
real numbers: 10.0, 1000.98, 0.567, . . .
strings: "Hello World", "I love programming", . . .
booleans: true, false.

A variable is like a box in which you place a value:


an assignment statement — e.g., a = 10; — places a new
value in the box denoted by the variable (a) that sits on the
left-hand side of the assignment sign (=), and erases
whatever was previously in the box,
the value hold in the variable can be read in an expression,
e.g., a + 10 will now evaluate to 20.

Variables and functions are baptized by the programmer with


names, so that they may be called upon later on.
Names are case sensitive and have a grammar of their own!
Expressions: Grammar & Precedence Rules
An expression can be recursively defined as:
(0)
(0) a number or string value (literal), or Exp − → number | string
(1) a variable name, or (1)
Exp −→ name
(2) a sum of two expressions, or (2)
Exp −→ Exp + Exp
(3) a product of two expressions, or (3)
Exp −→ Exp * Exp
... ...
(4) an expression enclosed in (), or (4)
Exp −→ ( Exp )
(5) a function call. (5)
Exp −→ name ( Exp , . . . , Exp )

a b or a + + b or 0.1234abc are not expressions!


( a + myfun(a * b) ) * b is a legal expression:
(3) (4) (2)
Exp −→ Exp * Exp −→ ( Exp ) * Exp −→ ( Exp + Exp ) * Exp
(1) (5)
−→ ( a + Exp ) * Exp −→ ( a + myfun (Exp) ) * Exp
(3) (1)
−→ ( a + myfun (Exp * Exp ) ) * Exp −→ ( a + myfun (a * b ) ) * Exp
(1)
−→ ( a + myfun (a * b ) ) * b
Expressions: Evaluation Order & Semantics of +
Evaluation Order: to what is 2 + 3 ∗ 5 evaluated?
(a) 25, as in (2 + 3) ∗ 5, or
(b) 17, as in 2 + (3 ∗ 5) ?

Semantics of +:
denotes addition when used on numbers, e.g., 5 + 7 = 12,
denotes concatenation when used on strings,
e.g., "Hello " + "World" = "Hello World"
What about on a string and a number: "hello 00" + 7?
Expressions: Evaluation Order & Semantics of +
Evaluation Order: to what is 2 + 3 ∗ 5 evaluated?
(a) 25, as in (2 + 3) ∗ 5, or
(b) 17, as in 2 + (3 ∗ 5) ?

Semantics of +:
denotes addition when used on numbers, e.g., 5 + 7 = 12,
denotes concatenation when used on strings,
e.g., "Hello " + "World" = "Hello World"
What about on a string and a number: "hello 00" + 7?
I equivalent with: "hello 00" + (7).toString()

More verbose is better if it is more clear to you!


1. if in doubt about the evaluation order, use parentheses to
make sure it computes what you want!
2. if you want to use + as string concatenation: it might be
better to explicitly convert the number argument to a string.
Short and Unfair Quiz about Expressions
Q1: Is this an expression: log("2 + 3*4 = " + 2 + 3*4)
True
False
Short and Unfair Quiz about Expressions
Q1: Is this an expression: log("2 + 3*4 = " + 2 + 3*4)
True
False

Q2: "2 + 3*4 = " + 2 + 3*4 evaluates to:


(a) The number value: 14
(b) The string value: ”2 + 3*4 = 14”
(c) The number value: 20
(d) The string value: ”2 + 3*4 = 20”
(e) The string value: ”2 + 3*4 = 212”
(f) The string value: ”2 + 3*4 = 234”
Short and Unfair Quiz about Expressions
Q1: Is this an expression: log("2 + 3*4 = " + 2 + 3*4)
True
False

Q2: "2 + 3*4 = " + 2 + 3*4 evaluates to:


(a) The number value: 14
(b) The string value: ”2 + 3*4 = 14”
(c) The number value: 20
(d) The string value: ”2 + 3*4 = 20”
(e) The string value: ”2 + 3*4 = 212”
(f) The string value: ”2 + 3*4 = 234”

Q3: Add parentheses in the expression


"2 + 3*4 = " + 2 + 3*4
so that it evaluates to string value
"2 + 3*4 = 20"
Variable Declaration & Assignment Statement
declare variables using Sep → ; | newline
let before using them:
Dec → let name
let a; (1)
... Assgn −→ name = Exp
a = 1; (2)
Assgn −→ let name = Exp
assignment statement: (0)
variable name, followed by Stm −→ ;
(1)
=, followed by expression, Stm −→ Dec Sep
ending in semicolon or (2)
Stm −→ Exp Sep
newline. Box Demo! (3)
Stm −→ Assgn Sep
a = a * 4 + 5; ...
you may declare and ; is the empty statement
assign (initialize) a (does nothing at all)
variable in one go:
a = 10 b = 20;
var b = (a + 3) * 5; is a syntax error.
Scopes: Syntax, Liveness
A scope is a block of statements enclosed by curly brackets:
let a = 5;
{
let b = a + a ;
a = b * a;
}

We advise to declare new variables at the beginning of a scope.


Scope variables can overshadow identically-named variables that
were declared in an outer scope, as in the case of variable a:
let a = 1;
l e t b = 7;
{
l e t a = 5 ; / / t h i s i s a new v a r i a b l e
a = a + a;
b = b * a;
co n s o l e . l o g ( a ) ; / / what d o e s t h i s p r i n t ?
}
co n s o l e . l o g ( b ) ; / / what d o e s t h i s p r i n t ?
co n s o l e . l o g ( a ) ; / / what d o e s t h i s p r i n t ?

What is it printed?
Scopes: Syntax, Liveness
A scope is a block of statements enclosed by curly brackets:
let a = 5;
{
let b = a + a ;
a = b * a;
}

We advise to declare new variables at the beginning of a scope.


Scope variables can overshadow identically-named variables that
were declared in an outer scope, as in the case of variable a:
let a = 1;
l e t b = 7;
{
l e t a = 5 ; / / t h i s i s a new v a r i a b l e
a = a + a;
b = b * a;
co n s o l e . l o g ( a ) ; / / what d o e s t h i s p r i n t ?
}
co n s o l e . l o g ( b ) ; / / what d o e s t h i s p r i n t ?
co n s o l e . l o g ( a ) ; / / what d o e s t h i s p r i n t ?

What is it printed? 10 70 1
Why var declaration is insane & Grammar
1. What is printed?
l e t anna = ” I am Anna One ! ” ;
{
l e t anna = ” I am Anna Two ! ” ;
co n s o l e . l o g ( anna ) ;
}
anna = anna +
” I r e p e a t : I am Anna One ! ” ;
co n s o l e . l o g ( anna ) ;
Why var declaration is insane & Grammar
1. What is printed?
l e t anna = ” I am Anna One ! ” ;
{
l e t anna = ” I am Anna Two ! ” ;
co n s o l e . l o g ( anna ) ;
}
anna = anna +
” I r e p e a t : I am Anna One ! ” ;
co n s o l e . l o g ( anna ) ;

I am Anna Two !
I am Anna One ! I r e p e a t : I am Anna One !

2. What is printed if one uses var


instead of let?
Why var declaration is insane & Grammar
1. What is printed? Sep → ; | newline
l e t anna = ” I am Anna One ! ” ; Dec → let name
{ (1)
l e t anna = ” I am Anna Two ! ” ;
Assgn −→ name = Exp
co n s o l e . l o g ( anna ) ; (2)
Assgn −→ let name = Exp
}
anna = anna +
” I r e p e a t : I am Anna One ! ” ; (1)
co n s o l e . l o g ( anna ) ; Block −→ 
(2)
Block −→ Stm Block
I am Anna Two !
I am Anna One ! I r e p e a t : I am Anna One !
(0)
Stm −→ ;
(1)
2. What is printed if one uses var Stm −→ Dec Sep
instead of let? (2)
Stm −→ Exp Sep
(3)
I am Anna Two !
Stm −→ Assgn Sep
I am Anna One ! I r e p e a t : I am Anna Two ! (4)
Stm −→ { Block }
...
Var declarations are insane!
If Statement: Syntax and Semantics
The syntax of an if statement is:
1. keyword if,
2. followed by a boolean expression enclosed in (open/close) parentheses,
3. followed by a (then) statement — can be a simple statement, or a scope, or . . .,
4. optionally followed by keyword else and by a (else) statement — as before.
The semantics of the if statement is:
the boolean expression (condition) is evaluated
if the result is true then the (then) statement is executed/evaluated;
otherwise the else statement is executed/evaluated (if one such exists).
Valid if statements:
i f ( i > 5 && i < 10 ) Sep → ; | newline
x = 2* i ; ...
(1)
IfStm −→ if ( Exp ) Stm
i f ( i > 5 && i < 10 ) { IfStm
(2)
−→ if ( Exp ) Stm else Stm
va r x = 2 * i ; ...
y = x + 10; (0)
} Stm −→ ;
(1)
Stm −→ Dec Sep
i f ( i > 5 && i < 10 ) (2)
Stm −→ Exp Sep
x = 2* i ; (3)
else { Stm −→ Assgn Sep
(4)
va r y = x + 1 0 ; Stm −→ { Block }
x = y* i ; (5)
Stm −→ IfStm
}
If Statement: Syntax and Semantics
I want to implement a code with the following semantics:
1. In case the value of variable a is less then 10, I want to update a with the addition
of 100 to whatever a holds;
2. Otherwise: I want to (i) set variable b to the addition of 10 to the value of a, and (ii)
to set variable a to value 1.
Find & fix the bugs in the code snippets below so they conform with the semantics above:

i f a < 10 a = 100 + a
Sep → ; | newline
else {
...
(1)
b = 10 + a ;
IfStm −→ if ( Exp ) Stm a = 1;
(2) }
IfStm −→ if ( Exp ) Stm else Stm
...
(0)
Stm −→ ;
(1)
Stm −→ Dec Sep
(2)
Stm −→ Exp Sep
(3)
Stm −→ Assgn Sep
(4)
Stm −→ { Block }
(5)
Stm −→ IfStm
...
If Statement: Syntax and Semantics
I want to implement a code with the following semantics:
1. In case the value of variable a is less then 10, I want to update a with the addition
of 100 to whatever a holds;
2. Otherwise: I want to (i) set variable b to the addition of 10 to the value of a, and (ii)
to set variable a to value 1.
Find & fix the bugs in the code snippets below so they conform with the semantics above:

i f a < 10 a = 100 + a
Sep → ; | newline
else {
...
(1)
b = 10 + a ;
IfStm −→ if ( Exp ) Stm a = 1;
(2) }
IfStm −→ if ( Exp ) Stm else Stm
... The condition needs to be enclosed in parentheses
(0)
Stm −→ ; i f ( a < 1 0 ) a = 100 + a e l s e {
(1) b = 10 + a ; a = 1 ;
Stm −→ Dec Sep
(2)
}
Stm −→ Exp Sep
(3)
Stm −→ Assgn Sep
(4)
Stm −→ { Block }
(5)
Stm −→ IfStm
...
If Statement: Syntax and Semantics
I want to implement a code with the following semantics:
1. In case the value of variable a is less then 10, I want to update a with the addition
of 100 to whatever a holds;
2. Otherwise: I want to (i) set variable b to the addition of 10 to the value of a, and (ii)
to set variable a to value 1.
Find & fix the bugs in the code snippets below so they conform with the semantics above:

i f a < 10 a = 100 + a
Sep → ; | newline
else {
...
(1)
b = 10 + a ;
IfStm −→ if ( Exp ) Stm a = 1;
(2) }
IfStm −→ if ( Exp ) Stm else Stm
... The condition needs to be enclosed in parentheses
(0)
Stm −→ ; i f ( a < 1 0 ) a = 100 + a e l s e {
(1) b = 10 + a ; a = 1 ;
Stm −→ Dec Sep
(2)
}
Stm −→ Exp Sep Then statement must end with ; or newline
(3)
Stm −→ Assgn Sep i f ( a < 10) {
(4) a = 100 + a ;
Stm −→ { Block }
(5) } else
Stm −→ IfStm b = 10 + a ;
... a = 1;
If Statement: Syntax and Semantics
I want to implement a code with the following semantics:
1. In case the value of variable a is less then 10, I want to update a with the addition
of 100 to whatever a holds;
2. Otherwise: I want to (i) set variable b to the addition of 10 to the value of a, and (ii)
to set variable a to value 1.
Find & fix the bugs in the code snippets below so they conform with the semantics above:

i f a < 10 a = 100 + a
Sep → ; | newline
else {
...
(1)
b = 10 + a ;
IfStm −→ if ( Exp ) Stm a = 1;
(2) }
IfStm −→ if ( Exp ) Stm else Stm
... The condition needs to be enclosed in parentheses
(0)
Stm −→ ; i f ( a < 1 0 ) a = 100 + a e l s e {
(1) b = 10 + a ; a = 1 ;
Stm −→ Dec Sep
(2)
}
Stm −→ Exp Sep Then statement must end with ; or newline
(3)
Stm −→ Assgn Sep i f ( a < 10) {
(4) a = 100 + a ;
Stm −→ { Block }
(5) } else
Stm −→ IfStm b = 10 + a ;
... a = 1;
Statement a = 1; is not inside the else branch!
For Loop: Syntax and Semantics
The syntax of a for-loop statement is:
1. keyword for, followed by (, followed by
2. an optional assignment (Assgn) followed by ; followed by
3. an optional boolean expression, followed by ; followed by
4. an assignment or expression, followed by
5. ), i.e., close parenthesis, followed by
6. a (block of) statement(s) denoting the loop’s body.

The semantics of the for-loop statement is:


loop starts by executing the (optional) assignment (i.e., item 2.) once — this
typically initializes the loop index.
the for loop executes for as long as the boolean expression holds (i.e., item 3.) —
this typically compares the loop counter with a bound.
each iteration executes the loop body (i.e., item 6.);
at the very end of each iteration, the assignment (item 4.) is executed – this
typically increases/decreases the loop index;
at the very beginning of each iteration the boolean expression (item 3.) is evaluated
to determine whether a new iteration should be executed or the loop has ended!
For Loop: Examples and Grammar
We want to sum up the numbers from 1 to N.
Exp → ... Find and fix the bugs:
Sep → ; | newline
(1) l e t sum = 0 ; l e t i = 0 ;
Assgn −→ name = Exp
(2)
f o r ( i = 1 ; i <= N ; i = i + 1 ) ;
Assgn −→ let name = Exp sum = sum + i ;
...
(1)
ForStm −→ for ( Assgn ; Exp ; Assgn ) Stm
(2)
ForStm −→ for ( Assgn ; Exp ; Exp ) Stm
...
(0)
Stm −→ ;
(1)
Stm −→ Dec Sep
(2)
Stm −→ Exp Sep
(3)
Stm −→ Assgn Sep
(4)
Stm −→ { Block }
(5)
Stm −→ IfStm
(6)
Stm −→ ForStm
...
For Loop: Examples and Grammar
We want to sum up the numbers from 1 to N.
Exp → ... Find and fix the bugs:
Sep → ; | newline
(1) l e t sum = 0 ; l e t i = 0 ;
Assgn −→ name = Exp
(2)
f o r ( i = 1 ; i <= N ; i = i + 1 ) ;
Assgn −→ let name = Exp sum = sum + i ;
... Sum is updated once (body of the loop is ;)
(1)
ForStm −→ for ( Assgn ; Exp ; Assgn ) Stm
(2)
l e t sum = 0 ;
ForStm −→ for ( Assgn ; Exp ; Exp ) Stm f o r ( l e t i = 1 ; i <= N ; I + + ; ) {
... sum = sum + i ;
(0) }
Stm −→ ;
(1)
Stm −→ Dec Sep
(2)
Stm −→ Exp Sep
(3)
Stm −→ Assgn Sep
(4)
Stm −→ { Block }
(5)
Stm −→ IfStm
(6)
Stm −→ ForStm
...
For Loop: Examples and Grammar
We want to sum up the numbers from 1 to N.
Exp → ... Find and fix the bugs:
Sep → ; | newline
(1) l e t sum = 0 ; l e t i = 0 ;
Assgn −→ name = Exp
(2)
f o r ( i = 1 ; i <= N ; i = i + 1 ) ;
Assgn −→ let name = Exp sum = sum + i ;
... Sum is updated once (body of the loop is ;)
(1)
ForStm −→ for ( Assgn ; Exp ; Assgn ) Stm
(2)
l e t sum = 0 ;
ForStm −→ for ( Assgn ; Exp ; Exp ) Stm f o r ( l e t i = 1 ; i <= N ; I + + ; ) {
... sum = sum + i ;
(0) }
Stm −→ ;
(1) Loop index named i not I & semicolon in
Stm −→ Dec Sep
(2)
I++; is not according to grammar.
Stm −→ Exp Sep
(3) l e t sum = 0 ;
Stm −→ Assgn Sep f o r ( l e t i = 1 ; i <= N ; i + + )
(4)
Stm −→ { Block } co n s o l e . l o g ( ” I n i t e r a t i o n : ”
(5) + i + ” sum : ” + sum ) ;
Stm −→ IfStm
(6)
sum = sum + i ;
Stm −→ ForStm
...
For Loop: Examples and Grammar
We want to sum up the numbers from 1 to N.
Exp → ... Find and fix the bugs:
Sep → ; | newline
(1) l e t sum = 0 ; l e t i = 0 ;
Assgn −→ name = Exp
(2)
f o r ( i = 1 ; i <= N ; i = i + 1 ) ;
Assgn −→ let name = Exp sum = sum + i ;
... Sum is updated once (body of the loop is ;)
(1)
ForStm −→ for ( Assgn ; Exp ; Assgn ) Stm
(2)
l e t sum = 0 ;
ForStm −→ for ( Assgn ; Exp ; Exp ) Stm f o r ( l e t i = 1 ; i <= N ; I + + ; ) {
... sum = sum + i ;
(0) }
Stm −→ ;
(1) Loop index named i not I & semicolon in
Stm −→ Dec Sep
(2)
I++; is not according to grammar.
Stm −→ Exp Sep
(3) l e t sum = 0 ;
Stm −→ Assgn Sep f o r ( l e t i = 1 ; i <= N ; i + + )
(4)
Stm −→ { Block } co n s o l e . l o g ( ” I n i t e r a t i o n : ”
(5) + i + ” sum : ” + sum ) ;
Stm −→ IfStm
(6)
sum = sum + i ;
Stm −→ ForStm
... sum = sum+i; not part of the loop body.
Advise for how to use For Loops
For loops have a very permissive grammar!

We advise to keep it simple by always using the following pattern:


f o r ( l e t i = i n i t e x p ; i <= bound exp ; i = i + s t e p e xp ) {
. . . s t a t e m e n t o r body o f s t a t e m e n t s . . .
}

or
f o r ( l e t i = i n i t e x p ; i >= bound exp ; i = i − s t e p e xp ) {
. . . s t a t e m e n t o r body o f s t a t e m e n t s . . .
}
where init exp, bound exp and step exp are expressions that do not contain i:
init exp is used to initialize i for the first iteration of the loop;
bound exp is the maximal/minimal value of i upon which the loop is allowed to
iterate;
step exp is the value by which i is incremented/decremented at each iteration.
While Loop: Syntax and Semantics
The syntax of a while-loop statement is:
1. keyword while
2. followed by a boolean expression enclosed between parentheses, e.g., (i < 100)
3. followed by a (block of) statement(s), i.e., denoting the loop’s body.

The semantics of a while-loop statement is:


the while loop executes for as long as the boolean expression holds (i.e., item 2.)
each iteration executes the loop body (i.e., item 3.)
While Loop: Grammar and Examples
We want to sum up the numbers from 1 to N.
Exp → ... Find and fix the bugs:
Sep → ; | newline
(1) l e t i = 1 ; l e t sum = 0 ;
Assgn −→ name = Exp
(2)
wh i l e ( i <= N )
Assgn −→ let name = Exp sum = sum + i ;
...
(1)
ForStm −→ for ( Assgn ; Exp ; Assgn ) Stm
(2)
ForStm −→ for ( Assgn ; Exp ; Exp ) Stm
WhileStm → while ( Exp ) Stm
...
(0)
Stm −→ ;
(1)
Stm −→ Dec Sep
(2)
Stm −→ Exp Sep
(3)
Stm −→ Assgn Sep
(4)
Stm −→ { Block }
(5)
Stm −→ IfStm
(6)
Stm −→ ForStm
(7)
Stm −→ WhileStm
...
While Loop: Grammar and Examples
We want to sum up the numbers from 1 to N.
Exp → ... Find and fix the bugs:
Sep → ; | newline
(1) l e t i = 1 ; l e t sum = 0 ;
Assgn −→ name = Exp
(2)
wh i l e ( i <= N )
Assgn −→ let name = Exp sum = sum + i ;
... Non-terminating loop:
(1)
ForStm −→ for ( Assgn ; Exp ; Assgn ) Stm i is not incremented
(2)
ForStm −→ for ( Assgn ; Exp ; Exp ) Stm l e t i = 1 ; l e t sum = 0 ;
WhileStm → while ( Exp ) Stm wh i l e ( I < N )
... sum = sum + i ;
(0) i = i + 1;
Stm −→ ;
(1)
Stm −→ Dec Sep
(2)
Stm −→ Exp Sep
(3)
Stm −→ Assgn Sep
(4)
Stm −→ { Block }
(5)
Stm −→ IfStm
(6)
Stm −→ ForStm
(7)
Stm −→ WhileStm
...
While Loop: Grammar and Examples
We want to sum up the numbers from 1 to N.
Exp → ... Find and fix the bugs:
Sep → ; | newline
(1) l e t i = 1 ; l e t sum = 0 ;
Assgn −→ name = Exp
(2)
wh i l e ( i <= N )
Assgn −→ let name = Exp sum = sum + i ;
... Non-terminating loop:
(1)
ForStm −→ for ( Assgn ; Exp ; Assgn ) Stm i is not incremented
(2)
ForStm −→ for ( Assgn ; Exp ; Exp ) Stm l e t i = 1 ; l e t sum = 0 ;
WhileStm → while ( Exp ) Stm wh i l e ( I < N )
... sum = sum + i ;
(0) i = i + 1;
Stm −→ ;
(1) I not declared and
Stm −→ Dec Sep
(2)
i = i + 1 is not part of the loop
Stm −→ Exp Sep body!
(3)
Stm −→ Assgn Sep let i = 1;
(4)
Stm −→ { Block } l e t sum = 0 ;
(5) wh i l e ( i < N ) {
Stm −→ IfStm
(6)
sum = sum + i ;
Stm −→ ForStm i = i + 1;
(7) }
Stm −→ WhileStm
...
While Loop: Grammar and Examples
We want to sum up the numbers from 1 to N.
Exp → ... Find and fix the bugs:
Sep → ; | newline
(1) l e t i = 1 ; l e t sum = 0 ;
Assgn −→ name = Exp
(2)
wh i l e ( i <= N )
Assgn −→ let name = Exp sum = sum + i ;
... Non-terminating loop:
(1)
ForStm −→ for ( Assgn ; Exp ; Assgn ) Stm i is not incremented
(2)
ForStm −→ for ( Assgn ; Exp ; Exp ) Stm l e t i = 1 ; l e t sum = 0 ;
WhileStm → while ( Exp ) Stm wh i l e ( I < N )
... sum = sum + i ;
(0) i = i + 1;
Stm −→ ;
(1) I not declared and
Stm −→ Dec Sep
(2)
i = i + 1 is not part of the loop
Stm −→ Exp Sep body!
(3)
Stm −→ Assgn Sep let i = 1;
(4)
Stm −→ { Block } l e t sum = 0 ;
(5) wh i l e ( i < N ) {
Stm −→ IfStm
(6)
sum = sum + i ;
Stm −→ ForStm i = i + 1;
(7) }
Stm −→ WhileStm
... Finally correct!
Values and Variables

Expressions: Grammar, Order of Evaluation & Semantics of +

Statements
Variable Declaration & Assignment Statement
Scopes
If Statements (Branches)
For and While Loops

Function Declaration and Function Call

Longer and Clear Minimizes What You Need to Memorize


Function Declaration and Function Call
Syntax:
1. keyword function, followed by
2. the name of the function, followed by
3. a comma-separated sequence of names enclosed between parentheses denoting
the formal parameters of the function,
4. followed by a body of one or several statements enclosed in curly brackets.

Semantics:
The function declaration just implements the intended behavior in terms of some
generic (formal) parameters, but does not executes anything just yet.
The function call instantiates the formal parameters (item 3.) with some evaluated
actual arguments/parameters, and executes the body of the function (item 4.)
The return statement, which has the syntax return Exp; makes sense only inside a
function, and upon execution it terminates the function execution and returns as
the result (of the function call) the evaluated expression.

Why Functions?
Functions are a way to build new functionality that you can re-use multiple times,
Ideally, should be possible to summarize what a function does in a simple way,
Minimizes the number of bugs by eliminating code clones and enabling unit testing,
Allows the user to create customized more-powerful building blocks.
Function Declaration and Function Call
Exp → ...
(5)
Exp −→ name ( Exp , . . . , Exp ) Declaration of a function that computes
... the sum of squares of its two formal
Sep → ; | newline arguments a and b:
Dec → let name f u n c t i o n sumOfSquares ( a , b ) {
Assgn
(1)
−→ name = Exp l e t a sq = a * a ;
(2) l e t b sq = b * b ;
Assgn −→ let name = Exp return a sq + b sq ;
}
(0)
Stm −→ ; Function is called several times:
(1)
Stm −→ Dec Sep
(2) let x = 3;
Stm −→ Exp Sep let y = 4;
(3)
Stm −→ Assgn Sep l e t z = sumOfSquares ( x , y ) ;
(4) / / z = 3 * 3 + 4 * 4 = 25
Stm −→ { Block } l e t w = sumOfSquares ( x + 1 , y + 1 ) ;
... / / w = 4 * 4 + 5 * 5 = 16 + 25 = 41
(8)
Stm −→ return Exp Sep l e t q = sumOfSquares ( z * y , x + 7 ) ;
Block
(1)
−→  / / q = 100 * 100 + 10 * 10 = 10100
(2)
Block −→ Stm Block

(0)
FunDec −→ function name (name,..., name ) { Block }
Longer and Clear Minimizes What You Need to Memorize
A word of advice about how you can keep things simple and clear:
Declare all variables that you are planning to use in a scope at the beginning of
that scope. Also initialize them and remember the type of the value that they are
supposed to hold, e.g., this variable stores a string, another stores an integer, etc.
Use let declaration for variables; var is evil!
Remember that variable and function names are case sensitive: a variable named
anna is different than a variable named Anna.
Explicitly cast values to the intended type, e.g., so that you add two numbers or
concatenate two strings, but you do not add a number to a string.
Always enclose within curly brackets the body of the for/while loop or the bodies of
the then or else branches of an if statement.
Use semicolon after each variable declaration, assignment or expression statement.
Indent properly: all the statements of a scope should be indented by the same
amount – which is a small multiple of the depth at which that scope appears
indent by one tab the statements appearing directly inside a function;
indent by two tabs the statements appearing inside a loop that appears directly
inside a function;
indent by three tabs the statements of the then body of an if appearing inside the
body of a loop that appears directly inside a function . . .
Beware of the grammar rules, e.g., if statements and for and while loops!
Example of proper indentation

let global int = 0;


...
f u n c t i o n demo ( n ) {
l e t sum = 0 ;
f o r ( l e t i = 0 ; i <n ; i = i + 1 ) {
sum = sum + i ;

i f ( ( i % 2 ) == 0 ) {
/ / i f i i s e ve n add one
sum = sum + 1 ;
} else {
/ / i f i i s odd s u b t r a c t one
sum = sum − 1 ;
}
}
r e t u r n sum ;
}
...
co n s o l e . l o g ( ” R e s u l t o f demo ( 1 0 ) : ” + demo ( 1 0 ) . t o S t r i n g ( ) ) ;
co n s o l e . l o g ( ” R e s u l t o f demo ( 3 3 ) : ” + demo ( 3 3 ) . t o S t r i n g ( ) ) ;
The (Approximate) Grammar that we have derived so far
The lexical tokens are bolded. They include (i) keywords such as return or function,
operators (+,-), punctuation (;,()), values (numbers and strings), and names. The latter two
have a grammar of their own.

(0) (1)
Exp −→ number | string Block −→ 
(1) (2)
Exp −→ name Block −→ Stm Block
(2)
Exp −→ Exp + Exp
(0)
(3) Stm −→ ;
Exp −→ Exp * Exp
(1)
... Stm −→ Dec Sep
(4) (2)
Exp −→ ( Exp ) Stm −→ Exp Sep
(5) (3)
Exp −→ name ( Exp , . . . , Exp ) Stm −→ Assgn Sep
(4)
Stm −→ { Block }
Sep → ; | newline (5)
Stm −→ IfStm
(1) (6)
IfStm −→ if ( Exp ) Stm Stm −→ ForStm
(2) (7)
IfStm −→ if ( Exp ) Stm else Stm Stm −→ WhileStm
(8)
Stm −→ return Exp Sep
(1)
ForStm −→ for ( Assgn ; Exp ; Assgn ) Stm
(2) (0)
ForStm −→ for ( Assgn ; Exp ; Exp ) Stm FunDec −→ function name (name,..., name )
WhileStm → while ( Exp ) Stm { Block }
Greatest-Common Divisor (GCD) Algorithm
Given two positive integrals a and b,
the GCD of a and b can be computed in the following way:
For as long as a is different than b do the following:
I in the case when a is greater than b assign to a the (positive)
value resulted from subtracting b from a;
I in the other case, assign to b the (positive) value resulted
from subtracting a from b.
After the previous step finishes, a and b hold the value of the
greatest common divisor.

Online Programming:
Implement this textual specification in a function, then add
unit testing for it, i.e., a set of tests that validate the
implementation on some instances for which the result is
known. We will also make the implementation look nice and
readable by using function!
Conclusions

program are built as puzzles by composing horizontally and


vertically (in a nested fashion) a set of language primitives,
such as scopes, if statements, loops;

being aware of grammar rules and being organized (longer


and clearer) allows one to avoid nasty bugs, whose
debugging might otherwise waste a lot of time;

functions are an essential ingredient that allows one to


I modularize the implementation,
I minimize the number of code clones,
I create higher abstractions, i.e., more-powerful basic blocks;
I test and validate the new implementation.

You might also like