0% found this document useful (0 votes)
1 views48 pages

L04-JavaScript

The document provides a comprehensive overview of the history and features of JavaScript, detailing its evolution from its inception in 1995 to its current state, including key milestones such as the introduction of ECMAScript. It covers fundamental concepts such as variables, types, arithmetic operations, and the use of objects and arrays, as well as the introduction of functions and anonymous functions. The document also highlights the significance of AJAX in revitalizing JavaScript and the emergence of modern frameworks and environments like Node.js.

Uploaded by

stephen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views48 pages

L04-JavaScript

The document provides a comprehensive overview of the history and features of JavaScript, detailing its evolution from its inception in 1995 to its current state, including key milestones such as the introduction of ECMAScript. It covers fundamental concepts such as variables, types, arithmetic operations, and the use of objects and arrays, as well as the introduction of functions and anonymous functions. The document also highlights the significance of AJAX in revitalizing JavaScript and the emergence of modern frameworks and environments like Node.js.

Uploaded by

stephen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

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

⚫ LiveScript was shipped as part of a Navigator release in


September 1995, then the name was changed to JavaScript three
months later.
⚫ Microsoft debuted Internet Explorer in 1995, leading to a
browser war with Netscape.
⚫ On the JavaScript front, Microsoft reverse-engineered the
Navigator interpreter to create its own, called JScript.
⚫ In November 1996, Netscape submitted JavaScript to ECMA
International, as the starting point for a standard specification
that all browser vendors could conform to.
⚫ This led to the official release of the first ECMAScript
language specification(c) in June 1997.
Paul Fodor (CS Stony
Brook)
A brief history
⚫ European Computer Manufacturers Association (ECMA) is a
of standards
JS organization for information and communication
systems.
⚫ The organization was founded in 1961 to standardize computer systems
in Europe.
⚫ ECMA-6 – 7-bit Coded Character Set (based on ASCII), also approved as
ISO/IEC 646
⚫ ECMA-107 – FAT12/FAT16 file system
⚫ ECMA-119 – CD-ROM volume and file structure
⚫ ECMA-262 – ECMAScript Language Specification
⚫ ECMA-334 – C# Language Specification
⚫ ECMA-335 – Common Language Infrastructure (CLI)
⚫ ECMA-363 – Universal 3D File Format
⚫ ECMA-372 – C++/CLI Language Specification
⚫ ECMA-376 – Office Open XML
⚫ ECMA-404 – JSON
⚫ ECMA-408 – Dart language specification
(c) Paul Fodor (CS Stony
Brook)
A brief history
⚫ Microsoft gained an increasingly dominant position in
oftheJS browser market - by the early 2000s, Internet
Explorer's market share reached 95%
⚫ MS stopped collaborating on ECMA work
⚫ During the period of Internet Explorer dominance in the early
2000s, client-side scripting was stagnant.
⚫ The successor of Netscape, Mozilla, released the Firefox browser
in 2004.
⚫ In 2005, Mozilla joined ECMA International
⚫ In 2005, AJAX started a renaissance for JS (see next slide)
⚫ Google debuted its Chrome browser in 2008, with the V8
JavaScript engine
⚫ ECMAScript 6 was published in 2015.
⚫ 11th Edition – ECMAScript 2020
(c) Paul Fodor (CS Stony
Brook)
A brief history of JS
⚫ In 2005, Jesse James Garrett released a white paper in which
he coined the term Ajax ( "Asynchronous JavaScript and
XML") and described a set of technologies, of which
JavaScript was the backbone, to create web applications
where data can be loaded in the background, avoiding the
need for full page reloads.

(c) Paul Fodor (CS Stony


Brook)
Overview of
JavaScript
⚫ Language used in making web pages more
dynamic
⚫ Typically runs in the browser
⚫ See Chrome -> Settings -> More tools ->
Developer tools
⚫ Recentextensions (Node.js) allows JavaScript to
run independent of a web environment
⚫ node

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

>console.log(add5(6) Call add5() with


an argument of 6
); 11
> function average(arg1, arg2) { Takes 2 parameter

var avg = (arg1 + arg2) / 2;


return avg;
}
Call average() with
>console.log(average(10,17) arguments of 10 and
); 13.5 17

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:

const <varname> = () => {


/ / code for function
}
⚫ If code only returns a value, you can skip the return keyword and
curly braces!

29
(c) Paul Fodor (CS Stony
Brook)
JavaScript - Arrow functions
examples
const arrow1 = () = >
{ console.log("An arrow
func!");
}
arrow1();

const squareArrow = (x) = > x * x;


console.log(squareArrow(5));

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

newnums = nums.filter(x = > x > = 0).map(x = > Math.sqrt(x));


console.log("newnums: " + newnums);
newnums: 2.23606797749979, 3.1622776601683795, 5,
3.1622776601683795,10

Red text are arrow functions passed into other functions


Output of filter() which is passed into map() is: [5,10,25,10,100]
map() then runs Math.sqrt() on each element

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

35 } (c) Paul Fodor (CS Stony


Brook)
JavaScript – switch statement
example
function analyzeResponse(resp) {
switch (resp) {
case 1:
retValue = "New York";
break;
case 2:
retValue = "Los Angeles";
break;
case 3:
retValue = "Chicago";
break;
default:
ret
Value
= "No
joy –
I'm
36
not
seein (c) Paul Fodor (CS Stony
Brook)
JavaScript – for

Similar to C and Java's for-loop
loops
Format:

for (initialization; loop-end-test; end of loop code) {


loop body
}

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) {

// Code to execute as long as the condition evaluates to true

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 {

// Code to execute as long as the condition evaluates to true

} 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)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy