04 JavaScript
04 JavaScript
1. Introduction to JavaScript
2. Data Types in JavaScript
3. Operators in JavaScript
4. Conditional Statements
5. Loops
6. Functions
7. Arrays
8. Arrow Function (aka Lambda)
2
Introduction to JavaScript
Dynamic Behavior at the Client Side
Or Server-Side Web applications
3
JavaScript
• JavaScript is a platform independent scripting language
o Lightweight but a powerful interpreted language
o Supports both functional and object-oriented
programming style
o Current Version ES 2023 (ECMAScript 2023)
o Can be used for:
• Client-side scripting: embedded in HTML pages and interpreted
by the Web browser
• Server-side programming using Node.js
• Desktop app development (e.g., https://electronjs.org)
• Mobile app development (e.g., https://reactnative.dev/)
4
What Can JavaScript Do?
• Web Client-side Dynamic Behavior
o Handle client-side events such as button clicked event
• e.g., Changing an image on moving mouse over it
o Manipulate the Document Object Model (DOM) of the page:
read, modify, add, delete HTML elements
o Validate form input values before being submitted to the server
o Perform computations, sorting and animation
o Perform asynchronous server calls (AJAX) to load new page
content or submit data to the server without reloading the page
• Server-side Web applications development using Node.js
• Other usage such as desktop apps, mobile apps and
game development
5
Data Types in JavaScript
6
Declaring Variables
• Declare variables using const. If you intend to
change the variable value, then use let.
o Variable names in JavaScript is case-sensitive
• The syntax is the following:
const <identifier> [= <initialization>];
9
Primitive types
• There are 7 data types in JavaScript:
o number
o bigint
o string
o boolean
o undefined
o function
o object (everything else is an object)
• Use typeof to find out the variable type
• A string is a sequence of characters enclosed in single (' ')
or double quotes (" ")
const str1 = "Some text saved in a string variable";
const str2 = 'text enclosed in single quotes';
10
String Methods
• str.length returns the number of characters
• Indexer (str[index]) or str.charAt(index)
o Gets a single-character string at location index
o If index is outside the range of string characters, the
indexer returns undefined
• e.g., string[-1] or string[string.length]
• str3 = str1.concat(str2) or str3 = str1 + str2;
o Returns a new string containing the concatenation of
the two strings
• Other String methods
http://www.w3schools.com/jsref/jsref_obj_string.asp
11
Convert a number to a string
• Use number’s method (toString)
str = num.toString()
• Use String function
str = String(num)
13
13
undefined vs. null Values
• In JavaScript, undefined means a variable has been
declared but has not been assigned a value, e.g.,:
let testVar; console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined
14
NaN
• NaN (Not a Number) is an illegal number
/*
slash star
block
comment
*/
16
Operators in JavaScript
Arithmetic, Logical, Comparison, Assignment,
Etc.
17
Categories of Operators in JS
Category Operators
Arithmetic + - * / % ++ --
Logical && || !
Binary & | ^ ~ << >>
Comparison == != < > <= >= === !==
= += -= *= /= %= &= |=
Assignment
^= <<= >>=
String
+
concatenation
Other . [] () ?: new
http://www.w3schools.com/js/js_operators.asp
18
Comparison Operators
• Comparison operators are used to compare
variables
o ==, <, >, >=, <=, !=, ===, !==
• Comparison operators example:
const a = 5;
const b = 4;
console.log(a >= b); // True
console.log(a != b); // True
console.log(a == b); // False
console.log(0 == ""); // True
console.log(0 === ""); //False
19
== vs. ===
• See Examples
http://www.w3schools.com/js/js_comparisons.asp
20
Conditional Statements
21
if-else Statement – Example
• Checking a number if it is odd or even
const number = 10;
if (number % 2 === 0)
{
console.log('This number is even');
}
else
{
console.log('This number is odd');
}
22
switch-case Statement
• Selects for execution a statement from a list
depending on the value of the switch expression
switch (day)
{
case 1: console.log('Monday'); break;
case 2: console.log('Tuesday'); break;
case 3: console.log('Wednesday'); break;
case 4: console.log('Thursday'); break;
case 5: console.log('Friday'); break;
case 6: console.log('Saturday'); break;
case 7: console.log('Sunday'); break;
default: console.log('Error!'); break;
}
23
False-like conditions
• These values are always false (when used in a
condition)
o false
o 0 (zero)
o "" (empty string)
o null
o Undefined
o NaN
24
while (…)
do { … }
for { … }
Loops
Execute Blocks of Code Multiple Times
25
While Loop – Example
let counter = 0;
while (counter < 10){
console.log(`Number : ${counter}`);
counter++;
}
26
Other loop structures
• Do-While Loop:
do {
statements;
}
while (condition);
• For loop:
for (initialization; test; update) {
statements;
}
// Compute n!:
let factorial = 1;
for (let i = 1; i <= n; i++){
factorial *= i;
}
27
For-of loop
• For-of loop iterates over a list of values
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let sum = 0;
for (const n of nums) {
sum += n;
}
29
function (parameter) {
return expression;
}
function double (number) { return number * 2; }
double(212); // call function
// Function expression
const average = function (a, b) {
return (a + b) / 2;
}
average(10, 20); // call function
Arrow Function
Also called LAMBDA
OR expressions
31
Arrays
Processing Sequences of Elements
https://sdras.github.io/array-explorer/
32
Declaring Arrays
• Declaring an array in JavaScript
// Array holding integers
const numbers = [1, 2, 3, 4, 5];
// Array holding strings
const weekDays = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"]
// Array of different types
const mixedArr = [1, new Date(), "hello"];
// Array of arrays (matrix)
const matrix = [
[1,2],
[3,4],
[5,6]
];
33
Processing Arrays Using for Loop
• The for-of loop iterates over a list of values
let sum = 0;
for(const number of [1, 2, 3])
sum+= number;
• Initialize an array:
for (const index = 0; index < array.length; index++)
{
array[index] = index;
}
Dynamic Arrays
• All arrays in JavaScript are dynamic
o Their size can be changed at runtime
o New elements can be inserted to the array
o Elements can be removed from the array
• Methods for array manipulation:
o array.push(element)
• Inserts a new element at the tail of the array
o array.pop()
• Removes the element at the tail
• Returns the removed element
35
Insert/Remove at the head of the array
• array.unshift(element)
o Inserts a new element at the head of the array
• array.shift()
o Removes and returns the element at the head
36
Deleting Elements
• Splice removes item(s) from an array and returns
the removed item(s)
• This method changes the original array
• Syntax:
array.splice(index,howmany)
37
Destructuring assignment
• The destructuring assignment makes it easier to extract
data from arrays or objects into distinct variables
38
Spread Operator
• Spread Operator (3 dots ... ) allows converting an array
into consecutive arguments in a function call
const nums = [5, 4, 23, 2];
//Spead could be used to convert the array
//into multiple arguments
const max = Math.max(...nums);
console.log("max:", max);
40
Maps
• Map is a collection of key-value pairs
const map = new Map();
map.set(1, 'One');
map.set(2, 'Two');
42
Imperative vs. Declarative
Imperative Programming
Declarative Programming
45
Common operations on arrays
.map
o Applies a function to each array element
.filter(condition)
oReturns a new array with the elements that satisfy
the condition
.find(condition) / findIndex(condition)
o Returns the first array element that satisfy the
condition
.reduce
o Applies an accumulator function to each array
element to reduce them to a single value
46
Operations Pipeline
• A pipeline of operations: a sequence of
operations where the output of each operation
becomes the input into the next
o e.g., .filter -> .map -> .reduce
• Operations are either Intermediate or Terminal
Map
Transform elements by applying a Lambda to each element
n => n **
2
48
Reduce
Apply an accumulator function to each element of the
array to reduce them to a single value
//Declarative
// Imperative const total = numbers.reduce ( (sum, n) => sum + n
let sum = 0 )
for(const n of numbers)
sum += n Accumulation
Variable Accumulation
Lambda
1
Collapse the multiple 2
elements of an array 3
into a single element 4
reduce 36
5
6
7
8 49
49
Reduce
50
Flat
51
flatMap
Do a map and flatten the results into 1 list
Each book has a list of authors. flatMap combines them to
produce a single list of all authors
const books = [
{title: "Head First JavaScript", authors: ["Dawn Griffiths", "David Griffiths"]},
{title: "JavaScript in Action", authors: ["Dmitry Jemerov", "Svetlana Isakova"
]
const authors = books.flatMap(b => b.authors);
console.log(authors);
5252
Other Array Functions
• nums.sort((a, b) => a – b)
o Sorts the elements of the nums array in ascending order
• nums.sort((a, b) => b – a)
o Sorts the elements of the nums array in descending order
• array.reverse()
o Returns a new array with elements in reversed order
• array.concat(elements)
o Inserts the elements at the end of the array and
returns a new array
• array.join(separator)
o Concatenates the elements of the array
53
Summary
• To start thinking in the functional style avoid
loops and instead use Lambdas
o Widely used for array processing and UI events
handling
• An array can be processed in a pipeline
o Typical pipeline operations are filter, map and
reduce
54
JavaScript Resources
• Mozilla JavaScript learning links
o https://developer.mozilla.org/en-US/learn/javascript
• JavaScript features
o https://github.com/mbeaudru/modern-js-cheatsheet
o https://exploringjs.com/
79
Multi-line lambda
80
Map, Filter and Reduce Examples
let arr = [1, 2, 3];
let sum = arr Use an arrow
function for a
.map(x => x * 2)
more concise
.reduce( (sum, x) => sum + x );
syntax
console.log(sum); // ==> 12
let fullnames =
people.filter(function (p) {
return p.age >= 18;
}).map(function (p) {
return p.fullname;
});
Becomes
let fullnames =
people.filter(p => p.age >= 18)
.map(p => p.fullname); 81