L04-JavaScript
L04-JavaScript
Paul Fodor
CSE316: Fundamentals of Software
Development
Stony Brook University
http://www.cs.stonybrook.edu/~cse316
1
A brief history
ofNavigator.
JS
⚫ In 1995, Netscape decided to add a scripting language to
6
(c) Paul Fodor (CS Stony
Brook)
JavaScri
Basic Features
pt
⚫
⚫Variables
⚫Constants
⚫Types
⚫Arithmetic
Operations
⚫Compound
Operators
7 ⚫Bitwise Operations
(c) Paul Fodor (CS Stony
Brook)
JavaScri
Variables
ptNames
⚫
⚫
⚫ Alph
anu
meri
c
⚫ Starti
ng
with
an
alph
a
8
⚫ Nam (c) Paul Fodor (CS Stony
Brook)
JavaScri
> var a =
pt 1>
a
1
>a =
22
> let b
=1
>b
1
9
(c) Paul Fodor (CS Stony
Brook)
JavaScript -
⚫Constants
Names holding values
⚫ Valuesdo not change during
execution
⚫ Declared with 'const' keyword
10
(c) Paul Fodor (CS Stony
Brook)
JavaScript -
>Constants
const c = 1
>c
1
>c
2
Th
ro
11
wn (c) Paul Fodor (CS Stony
Brook)
JavaScript -
⚫ Simple types:
Types
⚫ Number (Note: there is no 'integer' and 'float'. All
are numbers)
⚫ String – A series of characters (inside of quotes ""
or '')
⚫ Boolean – Holds the values true or false
⚫ Undefined – No value has been assigned to the
variable yet
⚫ null
12
(c) Paul Fodor (CS Stony
Brook)
JavaScript -
Examples:
Types
> var a;
variable a
// Declare
>a
null
>a
> a= = "Paul"
>
1.a
"Paul"
1
>> aa
>a= // Boolean value
1.1true
;
>a
13
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Arithmetic
Operations
// Operators: +, -, *, /, %,
> a = 5;
> b = 11;
> c = 33;
>d = a +
b; 16
>e = c %
b; 0
>f = a * a * pi;
78.53750000000001
14
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Bitwise
Operators
// Operators &, |, ~, ^, <<, >>
> aa = 5;
> bb = 11;
> cc = 12;
> dd = 201;
> ee = 2;
>ff = bb << // 11 shift left 2 bits => 44
ee; 44
>gg = bb & // 12 and 11 => 8
cc; 8
>hh = cc | // 12 or 5 => 13
aa; 13
15
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Compound
Operators
// Operators +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
// Combine assignment and an operation. Operation
stores into the first operand (to the left of the operator!)
>a +=
b; 16
>c %=
b; 0
>a *= a *
pi; 804.224
> bb <<= // 11 shift left 2 bits => 44
ee; // 12 and 11 => 15
> bb &=aa;cc; // 12 or 5 => 13
cc |=
16
(c) Paul Fodor (CS Stony
Brook)
JavaScript – String
> str1 = 'Hello';
Operations
> str2 = 'World';
> greeting = str1 + ', ' + str2 + '!'; // String
concatenation
Hello, World!
// Length of string (.length is a 'property' not a 'method')
> lengthOfString = greeting.length; // Assigns 13
// Strings may be indexed with squarebrackets to return a
specific character
> theComma = greeting[5]; // puts a , in theComma
// Strings are immutable! Cannot be changed (but can be
replaced!)
1
> greeting
greeting[5] = ';' World!";
= "Hello; // This produces an error
// This is
(c) Paul Fodor (CS Stony
7
fine! Brook)
JavaScript – String
// Strings are 'objects' and have associated methods
Operations
• .indexOf(substring, <start_position>) – Return the index of where the
first matching substring starts
• .lastIndexOf(substring, <start_position>) – Return index of where
last matching substring starts.
• .slice(startpos, enpos) – Extracts and returns a substring from positions
startpos to (endpos – 1). Position can be negative meaning they are
counted from the end of the string.
• .substring(startpos, endpos) – Same as slice but negative positions are
disallowed.
• .substr(startpos, length) – Extracts a substring from startpos for given
length.
• .replace(substring, newstring) – Searches the string and replaces the
first argument value, if found, with the value newstring.
• .toUpperCase() – Converts the entire string to uppercase characters
• .toLowerCase() – Converts the entire string to lowercase characters
• .charAt(position) – Returns the character at the location given by
position
• .charCodeAt(position) – (c)Returns
Paul Fodor the UTF-16 value (0-65535) of the
(CS Stony
Brook)
JavaScript – String
>a =
Operations
'Paul' 'Paul'
>a.indexOf('a',
1) 1
>a.lastIndexOf('a
') 1
>a.slice(1,
3) 'au'
>a.slice(-3,-
1) 'au'
>a.substr(0,
2) 'Pa'
>a.replace("a","e
") "Peul"
> a.charCodeAt(1)
1
9 97 (c) Paul Fodor (CS Stony
Brook)
JavaScript -
Objects
⚫ Objects contain multiple related values
⚫ Values indexed by a property name or
string
var student1 =
{ "firstName" :
Properties "John", Values
"lastName" : "Smith",
"year" : "sophomore",
"major" : "CSE"
};
20
(c) Paul Fodor (CS Stony
Brook)
JavaScript -
⚫ Property values can be set or accessed using:
Objects
⚫ Dot notation
⚫ Bracket notation – Must use this method if
the 'property' contains a space
// Dot notation
fName = student1.firstName;
student1.year = "Junior";
// Bracket notation
lName = student1["lastName"];
student1["major"] = "ISE";
property = "gradYear";
21
student1[property] = 2020;
(c) Paul Fodor (CS Stony
Brook)
JavaScript -
⚫ Arrays hold multiple values
Arrays
⚫ Collections are specified in square brackets
with comma separated values
array1 = [0, 1, 4, 9 ,16, 25]
array2 = ["John", 1, "Mary", 2]
/ / Arrays in JavaScript can be
heterogeneous array3 = [[2, 3, 4], [1, 5, 10],
[2, 20]]
/ / Arrays can hold arrays!
22
(c) Paul Fodor (CS Stony
Brook)
JavaScript -
Arrays
⚫ Element values can be indexed with a single integer
in square brackets
> array1 = [0, 1, 4, 9 ,16, 25]
[ 0, 1, 4, 9, 16, 25 ]
>array1[0] =
11
> array1
[ 1, 1, 4, 9, 16,
25 ]
> array2 =
["John", 1,
"Mary", 2]
23
> aName = (c) Paul Fodor (CS Stony
Brook)
JavaScript – Arrays (array
methods)
Array is an object (reference type) and has methods that do certain operations on
the
array.
• .push(newelement) – Adds an item to the end of the array
• .pop() – Removes the last array element and returns it
• .shift() – This removes the first element of an array and returns it
• .unshift(newelement) – This adds an element to the beginning of an array
>array1 = [0, 1, 4, 9 ,16, 25]
>array1.push(
7) 7
>console.log(array
1) [ 0, 1, 4, 9, 16, 25,
7]
>array1.po
p() 7
>array1.shif
t() 0
>array1
[6 1, 4, 9, 16, // lenght
> array1
25 ]
2
4 >[ 8,
array1.unshif
1, 4, 9, 16, 25 ] (c) Paul Fodor (CS Stony
Brook)
JavaScript – Functions
⚫ Functions can hold related code
⚫ Defined with the function keyword
⚫ Can take arguments
⚫ Can return a value to the caller with the
return
keyword
25
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Examples:
> function add5(arg1) {
Functions
return arg1+5;
Takes 1 parameter
Returns the sum of
} the argument and 5
26
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Anonymous
⚫ Anonymous functions are unnamed
functions
⚫ Can perform same tasks as a named function
⚫ Can take arguments
⚫ Syntax:
Declaration:
const <varname> = function(<params>) {
// <varname> is any legal JavaScript variable name
// <params> is a list of 0 or more parameters)
// code for function
}
Calling:
<varname>();
27
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Anonymous functions
example
const myfunc = function() {
console.log("This is a nameless (anonymous) function!");
}
const myfunc2 = function(x) {
return x*x;
}
myfunc();
myfunc2(5);
Output:
This is a nameless (anonymous) function!
25
28
(c) Paul Fodor (CS Stony
Brook)
JavaScript - Arrow
functions
⚫
Shorthand way to write anonymous functions
⚫
No function keyword
⚫ Syntax:
29
(c) Paul Fodor (CS Stony
Brook)
JavaScript - Arrow functions
examples
const arrow1 = () = >
{ console.log("An arrow
func!");
}
arrow1();
Output:
An arrow func!
25
30
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Higher order arrow
functions
⚫ Arrow functions can be passed to other
functions that will apply them to a
number of inputs
⚫map()
⚫filter()
⚫reduce()
31
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Higher order arrow functions -
Example
nums = [5, 10, 25, -4, 10, -13, 100]
console.log("nums: " + nums);
nums: 5,10,25,-4,10,-13,100
32
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Control Flow
statements
⚫ Control flow
statements
⚫if/else
⚫switch
⚫for
⚫while
33
(c) Paul Fodor (CS Stony
Brook)
JavaScript – if/else
⚫ If/else is similar to other languages
⚫ Format:
if (condition) {
/ / Code to run if condition is
true
} else if (condition2) {
/ / Code to run if condition2 is
true
} else {
}
34
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Switch
statement
⚫ Switch statement is like a chained 'if'
⚫ Similar to other languages like 'C'.
⚫ Syntax:
switch (value)
{ case
<value_1>:
// code if value
= = value_1
break; // causes JavaScript to skip remaining case clauses
case <value_2>:
// code if value = = value_2
break;
….
default:
// code if no cases match
37
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Example:
> for (i = 0; i < 10; i++) {
for console.log(i
loop + " : " + i*i);
}
0:0
1:1
2:4
3:9
4 : 16
5 : 25
6 : 36
7 : 49
8 : 64
38
9 : 81
(c) Paul Fodor (CS Stony
Brook)
JavaScript – while
⚫ Iterates while a condition is true
loops
⚫ Syntax:
while (condition) {
39
(c) Paul Fodor (CS Stony
Brook)
JavaScript – while loop
example
function generateTable(tableSize) {
let i = 0;
if ((tableSize > 0) && (tableSize < =
10000)) { console.log("num : num^2");
while (i < tableSize)
{ console.log(i + " : " +
i*i); i++;
}
}
}
40
(c) Paul Fodor (CS Stony
Brook)
JavaScript – do while
loops
⚫ Iterates while a condition is true
⚫ Always iterates at least 1 time since test is at the
end!
⚫ Syntax:
do {
} while (condition)
41
(c) Paul Fodor (CS Stony
Brook)
JavaScript – do while loop
example
function generateTable(tableSize) {
let i = 0;
if( (tableSize > 0) && (tableSize < =
10000)) { console.log("num : num^2");
do {
I
console.log(i + " : " + i*i);
} while (i < tableSize)
}
}
42
(c) Paul Fodor (CS Stony
Brook)
JavaScript – rest
⚫ Used to handle variable number of arguments to a function
operator (…)
⚫ Using '…' + a variable name gathers all remaining
arguments
into a list with the given name
const test = (...rest) = > {
console.log(rest);
}
test(1, 2, 'a', 'b');
test(1, 2, 'a', 'b', 3, 4);
Output:
[ 1, 2, 'a', 'b' ]
43 [ 1, 2, 'a', 'b', 3, 4 ]
(c) Paul Fodor (CS Stony
Brook)
JavaScript – spread
operator (…)
⚫ Spreads elements from an array apart into individual members
⚫ Can use it to 'copy' an array rather than having an 'alias' to an
array
anArray = ['a', 'b', 'c', 'd', 'e']
let arr2;
let arr3;
(function() {
arr2 =
anArray; /
/ This is
an alias
arr3 = [...anArray]; // This spreads out the elements in anArray and builds a new array
anArray[0] = 'z';
})();
Output:
arr2: z,b,c,d,e
console.log("arr2: " + Note: arr2 is affected by
arr2); assignment since it is
arr3: a,b,c,d,e
an 'alias' of anArray, but
console.log("arr3: " + arr3); arr3 is a separate 'copy'
of the array due to using the spread operator.
44
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Destructuring
objects
⚫ Easy way to extract fields of an object into separate variables
⚫ Previously, needed a separate assignment for each field or member
⚫ Syntax:
const {fieldname1 : targetvar1, fieldname2 : targetvar2, …} = objectname;
Example:
let personInfo = {name:"Sam", age: 55, gender: "Female"};
const { name : pDataName, age : pDataAge, gender : pDataGender } = personInfo;
console.log ("Name: " + pDataName);
console.log ("Age: " + pDataAge);
console.log ("Gender: " + pDataGender);
Output:
Name: Sam
Age: 55
Gender:
Female
45
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Destructuring
arrays
⚫ Arrays can similarly be 'destructured'
⚫ Elements are 'positional' so…
⚫ must assign elements in order they are in the array
⚫ can 'skip' values from array by just adding commas ','
⚫ Syntax:
const [varname1, varname2, …] = arrayName;
⚫ Example:
const myArr = [1, 2, 3, 4, 5]
const [a, b, , , c] = myArr; // Puts 1 into a, 2 into b and 5 into
c console.log("a=" + a + ",b="+ b + ",c=" + c);
Output:
Extra commas skip
a=1,b=2,c=5 elements 3 and 4!
46
(c) Paul Fodor (CS Stony
Brook)
JavaScript – Web
pages
⚫ So how does JavaScript make web pages dynamic?
⚫ It manipulates objects on the page accessing them
via the DOM – The Document Object Model
⚫ Next lecture will show more
47
(c) Paul Fodor (CS Stony
Brook)
Summa
⚫ Java/cript
ry
⚫ Helps make web pages dynamic
⚫ Extensive language similar to languages like
Java and C
⚫ Next Lecture:
⚫ The DOM – Document Object Model
⚫ jQuery
48
(c) Paul Fodor (CS Stony
Brook)