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

IFN666Lecture2 2

This document provides an overview of JavaScript functions including normal functions, anonymous functions, arrow functions, and higher order functions. It also covers JavaScript data types, scope, and asynchronous JavaScript. The document is intended as lecture material for an advanced JavaScript class.

Uploaded by

Office SoeM
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)
44 views

IFN666Lecture2 2

This document provides an overview of JavaScript functions including normal functions, anonymous functions, arrow functions, and higher order functions. It also covers JavaScript data types, scope, and asynchronous JavaScript. The document is intended as lecture material for an advanced JavaScript class.

Uploaded by

Office SoeM
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/ 83

IFN666 Web and Mobile Development

Lecture 2 – Advanced JavaScript

Faculty of Science

CRICOS No. 00213J


Queensland University of Technology
Last Week - JavaScript
• for Client side (React, React Native) and Server side processing (Node)
• Weakly typed: allows implicit conversion between unrelated types.
value = 21 + “Hello"; // returns “21Hello”
• Dynamically typed
– Type checking happens at run time.
– The same variable can hold different data types
let x = 21;
x = ‘Hello’;
• Prototype-based
• Functional
• Interpreted
• Just-In-Time compiled

https://www.interviewbit.com/javascript-interview-questions/#is-
javascript-a-statically-typed-or-a-dynamically-typed-language

a university for the real world


R
2
CRICOS No. 00213J
Last Week
• JavaScript Data Types
– Numbers: 3.14, 3 (only one type of number: double)
– Boolean: true, false (5 == 6) // Returns false
let car = ‘ BMW’; // single quotes
– Strings let car = “BMW"; //double quotes
let car = `BMW`; // back tick

– Arrays const cars = ["Saab", "Volvo", "BMW"];

– Objects const person = {firstName:"John", lastName:"Doe", age:50};


– Undefined, Null
• Scope: Global, function, block (code inside curly braces { … })
• Use let and const, not var

a university for the real world


R
3
CRICOS No. 00213J
Agenda

• Functions
– Normal function
– Anonymous functions
– Arrow functions
– Higher order functions
• More on Objects, Arrays, and Functions
• JSON
• Asynchronous JavaScript
• Modules
• JavaScript Engine

a university for the real world


R
4
CRICOS No. 00213J
Fun with Functions

FUNCTIONS

a university for the real world


R
5
CRICOS No. 00213J
Function declarations
• Declared with function keyword // regular function
• Don’t declare return type or types
function multiply(a, b) {
for parameters
return a * b;
• Assign to an identifier through an }
assignment statement //invoke function
– Needs to be defined before the let x = multiply(5,10);
identifier is used
console.log(x);
• Or operate directly through a
function declaration
• Similar to a function in
• The usual rules apply
any C-like language
– Don’t place a function declaration of
any type in a conditional
• Why Functions?

a university for the real world


R
6
CRICOS No. 00213J
let cube = function (x) {
return x * x * x;
JS Hoisting
} • cube is declared through assignment of a
function value.
console.log(quartic(2)); • Works as expected
console.log(cube(3));
console.log(square(12)); • square is declared in the same way, but we try
to use it before it is defined
let square = function(x) { • Leading to the error shown.
return x * x;
};
• The quartic is declared using a function
statement
function quartic(x) { • hoisted to the top of the scope by the
return x * x * x * x;
}
interpreter
• Can use it successfully (16) despite the
declaration coming later.

let carName;
carName = "Volvo"; 
carName = "Volvo";
let carName; 
To avoid bugs, always declare all variables at the 7
a university for the real world
R

beginning of every scope. CRICOS No. 00213J


{
const cube = function (x) { Block scope function
return x * x * x;
} • cube is declared through assignment of a
console.log(quartic(2));
function value with a const qualifier.
console.log(cube(3)); • Both quartic and cube are visible within
the block scope, with quartic available
function quartic(x) { globally.
return x * x * x * x;
} • The const cube declaration restricts the
scope of the identifier to the braces (Block).
}

console.log(quartic(3));
console.log(cube(4));

a university for the real world


R
8
CRICOS No. 00213J
Anonymous Function
- A function without a name
- aka Function Expression
const m = function(a, b) {
return a * b;
Using const is safer than using var, because a
} function expression is always constant value.
m(5,10);

• Anonymous functions are commonly used for


– Passing as an argument to other functions
– Event handling
setTimeout(function() {
console.log("hello");
}, 5000);

a university for the real world


R
9
CRICOS No. 00213J
Arrow Functions (ES6)
const x = (a, b) => {return (a * b)};
const x = (a, b) => a * b;
• Arrow Function With Parentheses (for multiple Parameters)
hello = (val) => "Hello " + val;
• Arrow Function Without Parentheses (for single parameter)
hello = val => "Hello " + val;
• Arrow functions are an alterative way of declaring functions
• Shorthand for anonymous functions
• Not to be confused with <= (less than or equal)
• Arrow functions are not hoisted. They must be
defined before they are used.

a university for the real world


R
10
CRICOS No. 00213J
Recursive Functions by Example
function factorial(n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}

• We need the function to call itself


• We need to reduce the size of the problem
• We need to reach a base case…

a university for the real world


R
11
CRICOS No. 00213J
Higher order functions (a chain of functions )

FUNCTIONAL JAVASCRIPT

a university for the real world


R
12
CRICOS No. 00213J
JS higher order functions

• Functions that operate on other functions, either by


taking them as arguments or by returning them
• JS supports a wide range of higher order functions on
data structures such as arrays
• Chapter 4 of Eloquent JS provides a good introduction
– http://eloquentjavascript.net/05_higher_order.html
• We show some examples on the next slide
– map – apply the specified function to each element of the array
– filter – use a specified function to filter the array
– reduce – use a specified function to accumulate the elements
across the array

a university for the real world


R
13
CRICOS No. 00213J
Map()
map – apply the specified function to each element of the
array

const numbers = [1,2,3,4,5,6,7,8,9];


function double(num) {
return 2 * num;
}

let doubles = numbers.map(double);


console.log(doubles);

[ 2, 4, 6, 8, 10, 12, 14, 16, 18]

a university for the real world


R
14
CRICOS No. 00213J
Filter()
filter – use a specified function to filter the array

const numbers = [1,2,3,4,5,6,7,8,9];


function even(num) {
return (num % 2) === 0;
}
let evens = numbers.filter(even);
console.log(evens);
[ 2, 4, 6, 8 ]

a university for the real world


R
15
CRICOS No. 00213J
Reduce()
reduce – use a specified function to accumulate the
elements across the array

const numbers = [1,2,3,4,5,6,7,8,9];


function getSum(total,num) {
return total + num;
}
let total = numbers.reduce(getSum);
console.log(total);

45

a university for the real world


R
16
CRICOS No. 00213J
Map with Arrow Functions

var elements = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];

// This statement returns the length of elements in the array:


[8, 6, 7, 9]
elements.map(function(e) {
return e.length;
});

elements.map((e) => {
return e.length;
}); // [8, 6, 7, 9]

a university for the real world


R
17
CRICOS No. 00213J
Map with Arrow Functions

// When there is only one parameter, we can remove the surrounding


parentheses
elements.map(e => {
return e.length;
}); // [8, 6, 7, 9]

// When the only statement in an arrow function is `return`, we can


remove `return` and remove the surrounding curly brackets
elements.map(e => e.length); // [8, 6, 7, 9]

a university for the real world


R
18
CRICOS No. 00213J
Array Sort()
sort – sorts an array alphabetically

// Create and display an array:


let fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits); // [ 'Banana', 'Orange', 'Apple', 'Mango' ]

// First sort the array


fruits.sort();
console.log(fruits); // [ 'Apple', 'Banana', 'Mango', 'Orange’ ]
// Then reverse it:
fruits.reverse();
console.log(fruits); // [ 'Orange', 'Mango', 'Banana', 'Apple' ]

[ 'Banana', 'Orange', 'Apple', 'Mango' ]


[ 'Apple', 'Banana', 'Mango', 'Orange' ]
[ 'Orange', 'Mango', 'Banana', 'Apple' ]

a university for the real world


R
19
CRICOS No. 00213J
Numeric Sort
• sort – By default, sorts values as strings and sort them
alphabetically
• "25" is bigger than "100", as "2" is bigger than "1“
• incorrect result when sorting numbers !
• fix this by providing a compare function

let points = [40, 100, 1, 5, 25, 10];
points.sort(); // wrong sorting result
points.sort(function(a, b){return a - b});

[ 1, 10, 100, 25, 40, 5 ] // wrong sorting result


[ 1, 5, 10, 25, 40, 100 ] // // correct sorting result

a university for the real world


R
20
CRICOS No. 00213J
Array Iteration - forEach()
- method that operates on every array item

• Like the foreach loop in Java (similar ideas elsewhere)


• The idea is to loop over the elements without indexing.
txt = "";
let journal = ["I", "love", "you"];

function myFunction(value) {
txt = txt + value +"\t" ;
console.log(txt);
}
I
for (let i = 0; i < journal.length; i++) { I love
myFunction (journal[i]); // Do something with entry I love you
}
I
txt = ""; I love
journal.forEach(myFunction); // Do something with entry I love you

a university for the real world


R
21
CRICOS No. 00213J
Iteration - For…of statement (ES6)
• The for …of statement loops through the values of an
iterable object such as arrays, strings, and more.

// display Array I
let text = ""; love
let journal = ["I", "love", "you"]; you
for (let x of journal) {
text += x + "\n";
}
J
a
// display String
v
let text = "";
a
let language = "JavaScript";
S
for (let x of language) {
c
text += x + "\n";
r
}
i
p
a university for the real world
R
22
t
CRICOS No. 00213J
MORE ON ARRAY, FUNCTION,
AND OBJECT
a university for the real world
R
23
CRICOS No. 00213J
Functions
Defining a function to create an object

function house(rms, stl, yr, gar){


this.rooms = rms;
this.style = stl;
this.yearBuilt = yr;
this.hasGarage = gar;
}
let myhouse = new house(8, “Ranch”, 1990, true)

real world
R
a university for the
24
CRICOS No. 00213J
Objects

• Every object is an array of its property values and every


array is an object
– 0-based indexing
• Thus,
– myhouse[0] = 8
– myhouse[1] = “Ranch”
– myhouse[2] = 1990
– myhouse[3] = true

real world
R
a university for the
25
CRICOS No. 00213J
Objects

• Every object is also an associative array (name-value


pairs)
• Thus,
– myhouse[“rooms”] = 8
– myhouse[“style”] = “Ranch”
– myhouse[“yearBuilt”] = 1990
– myhouse[“hasGarage”] = true

real world
R
a university for the
26
CRICOS No. 00213J
Functions

• Can dynamically extend an object instance


yourHouse = new house(12, “Tudor”, 1934, true);
yourHouse.hasPorch = “false”;
yourHouse.windows = 46;
– Doesn’t affect other object instances nor the object itself

real world
R
a university for the
27
CRICOS No. 00213J
Functions
function house(rms, stl, yr, garp) {
this.length = 5;
this.rooms = rms;
this.style = stl;
this.yearBuilt = yr;
this.hasGarage = gar;
this.show = mshowHouse;
}

real world
R
a university for the
28
CRICOS No. 00213J
Functions
function mshowHouse( ) {
var nprops = this.length;
for (let iter = 1; iter < nprops; iter++) {
console.log(“Property ” + iter + “ is ” +
this[iter]);
}
}
myhouse.show( );

real world
R
a university for the
29
CRICOS No. 00213J
Date, RegExp, JSON

MORE ON JS OBJECTS

a university for the real world


R
30
CRICOS No. 00213J
Objects

Built-in objects Custom objects


– Number
– String – constructed from
– Array "prototypes"
– Function – constructed directly
– Object
– Math
using JavaScript
– Date Object Notation
– RegExp (JSON)
– BigInt (ES6)
– Symbol (ES6)

real world
R
a university for the
31
CRICOS No. 00213J
JavaScript built-in objects
http://www.w3schools.com/js/

String Array
• length • length
• charAt() • concat()
• concat() • sort()
• indexOf()
• reverse()
• replace()
• shift()
• substr()
• pop()
• split()
• push()
str = "this is a string";
i = str.indexOf('a'); let a = [banana, apple,
pear];
a = "[email protected]".split('@'); a.sort();

real world
R
a university for the
32
CRICOS No. 00213J
JavaScript built-in objects - Date
http://www.w3schools.com/js/
• Date objects are static.
• Date objects are created with the new Date() constructor
• There are 4 ways to create a new date object:
1. new Date()
2. new Date(year, month, day, hours, minutes, seconds, milliseconds)
3. new Date(milliseconds)
4. new Date(date string)

let d = new Date(2021); // 1 number will be treated as milliseconds

d = new Date("October 13, 2014 11:13:00");


// 1 string will be treated as date string

let d = new Date(); // creates a new date object with the current date and time
console.log(d); // output ISO date 2021-02-28T03:56:16.268Z

JavaScript stores dates as number of milliseconds since January 01,


1970, 00:00:00 UTC (Universal Time Coordinated).

real world
R
a university for the
33
CRICOS No. 00213J
JavaScript built-in objects - Date
http://www.w3schools.com/js/

let d = new Date(2021, 2, 24, 10, 33, 30, 0);
// 7 numbers specify year, month, day, hour, minute, second, and millisecond
 d = new Date(2021, 2, 24, 10, 33, 30);
// 6 numbers specify year, month, day, hour, minute, second
 d = new Date(2021, 2, 24, 10, 33);
//5 numbers specify year, month, day, hour, and minute
 d = new Date(2021, 2, 24, 10);
// 4 numbers specify year, month, day, and hour
 d = new Date(2021, 2, 24);
// 3 numbers specify year, month, and day
 d = new Date(2021, 2); // 3 numbers specify year, month

real world
R
a university for the
34
CRICOS No. 00213J
JSON

a university for the real world


R
35
CRICOS No. 00213J
What is JSON?
• JSON stands for JavaScript Object Notation
• JSON is a lightweight format for storing and transporting data
• JSON is language independent *
• JSON - A compact notation using associative arrays to build up
a JavaScript object.
• JSON is "self-describing" and easy to understand

JavaScript Object JSON text


{ let text = ‘{"employees":[‘ +
"employees":[   ’{"firstName":"John", "lastName":"Doe"},’ +
  {"firstName":"John", "lastName":"Doe"},   ’{"firstName":"Anna", "lastName":"Smith"},’+
  {"firstName":"Anna", "lastName":"Smith"},   ‘{"firstName":"Peter", "lastName":"Jones"}]}’
  {"firstName":"Peter", "lastName":"Jones"}
]
}

a university for the real world


R
36
CRICOS No. 00213J
Convert a JSON string into a JavaScript object
• The JSON format is syntactically identical to the code for creating
JavaScript objects
• To convert the JSON format string into a JavaScript object :
let obj = JSON.parse(text);

JavaScript Object JSON text


{ Let text = ‘{"employees":[‘ +
"employees":[   ’{"firstName":"John", "lastName":"Doe"},’ +
  {"firstName":"John", "lastName":"Doe"},   ’{"firstName":"Anna", "lastName":"Smith"},’+
  {"firstName":"Anna", "lastName":"Smith"},   ‘{"firstName":"Peter", "lastName":"Jones"}]}’
  {"firstName":"Peter", "lastName":"Jones"}
]
}

a university for the real world


R
37
CRICOS No. 00213J
Converting a JavaScript Object to a JSON Text

• Nested JSON Objects

let you = {
"firstName": "John",
. JSON.stringify()
"lastName": "Smith",
"isAlive": true, obj = JSON.stringify(you);
"age": 25,
"height_cm": 167.64,
"phone": [
{ "type": "home",
"number": "07 1234 5678" },
{"firstName":"John","lastName":
{ "type": "mobile", "Smith","isAlive":true,"age":25,"
"number": "0408 123 456" } height_cm":167.64,"phone":
],
"toString": function() {
[{"type":"home","number":"07
return this.firstName + this.lastName; 1234 5678"},
}
{"type":"mobile","number":"040
};
8 123 456"}]}
console.log(you.phone[0].number); //07 1234 5678

real world
R
a university for the
38
CRICOS No. 00213J
JSON Data Types

• Valid Data Types • Invalid Data Types


• a string • a function
• a number • a date
• an object (JSON object) • undefined
• an array
• a boolean
• null

a university for the real world


R
39
CRICOS No. 00213J
Looping an Object – for…in loop statements

• loop through object properties

myObj = { "name":"John", "age":30, "car":null };
for (key in myObj) {
  console.log(key, myObj[key]);

• Modify any value in a JSON object


myObj.name = "Jane";

• Delete object properties


delete myObj.age;

a university for the real world


R
40
CRICOS No. 00213J
“this” keyword

• The “this” keyword refers to the object that the


function is a property of.

• “this” keyword refers to the object that is invoking


the function
// “this” refers to local object obj // “this” refers to the Global object
let obj = { function doSomething() {
name: "vivek", console.log(this);
getName: function(){ }
console.log(this.name); doSomething();
}
}
obj.getName(); output: everything about the global
output: vivek. object.

a university for the real world


R
41
CRICOS No. 00213J
async and wait

ASYNCHRONOUS JAVASCRIPT

a university for the real world


R
42
CRICOS No. 00213J
Synchronicity
• Synchronous model
– Things happen one at a time.
– Program will wait for a slow process to finish (yawn!)
• Asynchronous model
– Multiple things to happen at the same time
– Program runs when an action is started.
– When action is finished program is:
• Is notified
• gets access to the result

a university for the real world


R
43
CRICOS No. 00213J
To Thread or not to Thread

• Multiple paths of execution


• Some things just take a long time to run

• Do we just stop everything and wait?


– [Single thread, can take a while]
• Do we run lots of threads at once?
– [Multiple threads, efficient but very complicated].
• Or do we run fewer threads and notify?
– [We callback to tell the main thread that we are finished]

a university for the real world


R
44
CRICOS No. 00213J
Why do we care?

• Because JavaScript environments are single threaded.


– If you don’t share time - one task will dominate
• We use callbacks or promises to do this.
• Callbacks and promises mean we wait without blocking

a university for the real world


R
45
CRICOS No. 00213J
To Thread or not to Thread

• Synchronous vs Asynchronous Execution


• JS hosts support asynchronous model
– In the browser
– In node.js
• Processing relies on an overall event loop
• We will see this mainly in event handling

a university for the real world


R
46
CRICOS No. 00213J
I promise a result

PROMISES, PROMISES

a university for the real world


R
47
CRICOS No. 00213J
Promises

• Events and callbacks work fine for some instances


• Button clicks are a perfect example
– There is no real waiting period
– We click the button again and again
– We are pretty much only interested in the present time

• But state can be more complex


– An image may not have fully loaded
– Something might have already happened
– Our callback response may not be the right one for the state

a university for the real world


R
48
CRICOS No. 00213J
The Problem

• We want to call loaded()when the image has loaded


– But we aren’t sure of its state
• We are catering for multiple possibilities
– The image is loaded or loading-and-soon-to-be-loaded
– Or maybe it has already failed with an error
• We would prefer a more elegant solution to all of this
– We want a single call or set of calls to handle all of the problems

• Promises are the answer we are looking for

a university for the real world


R
49
CRICOS No. 00213J
A (Fictitious) Alternative

img1.ready()
.then(function() {
// loaded, so do stuff
})
.catch(function(error) {
// report on an error
});

Here we are assuming that the image has a ready method that returns a
promise. It doesn’t.

But if it did, the then would allow us to do stuff if it resolves successfully.


Otherwise, we will fire off some sort of error.

a university for the real world


R
50
CRICOS No. 00213J
Promise Creation Example
let promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…

if (/* everything turned out fine */) {


resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});

This is the skeleton for the creation of a Promise. Initially we will just consume
them, as we do in the fetch()examples that will appear soon.

a university for the real world


R
51
CRICOS No. 00213J
Promises

• A promise is kept forever…


• Promises can succeed or fail, but…
– They can only do one or the other, and they can only do it once
– Once a promise succeeds it stays successful
– Once a promise fails, it remains a failure

• The more formal terminology is:


– fulfilled - The action relating to the promise succeeded
– rejected - The action relating to the promise failed
– pending - Hasn't fulfilled or rejected yet
– settled - Has fulfilled or rejected

a university for the real world


R
52
CRICOS No. 00213J
Async/Await


async and await make promises easier to write. async function myFunction() {
async makes a function return a Promise
• await makes a function wait for a Promise   return "Hello";
• The await keyword can only be used inside an async }
function

Is the same as:


async function myFunction() {
Waiting for a Timeout   return Promise.resolve("Hello");
async function myDisplay() {
}
  let myPromise = new Promise(function(myResolve,
myReject) { myFunction().then(
    setTimeout(function() { myResolve("I love You !!"); },
3000);   function(value) { /* code if successful
  }); */
let value = await myPromise;
} myDisplayer(value);
myDisplay();
});

a university for the real world


R
53
CRICOS No. 00213J
MODULES

a university for the real world


R
54
CRICOS No. 00213J
Modules
• A module is a bit of code encapsulated in a file, and
exported to another file.
• JS had no explicit support for modules prior to ES6
• We will consider CommonJS and ES6 Modules
• Modules of both types may be managed using npm
– Npm is the node package manager (Later)
– For new modules you write, use the ES6 standards

a university for the real world


R
55
CRICOS No. 00213J
Modules
• The js file is the modular unit.
– Node provides that wrapper for handling scope
– The node environment provides a special object called exports
– We add the identifiers we need
• We need to export identifiers selectively
– Only exported the core services provided by our module
– Local only should be hidden from the world.
• Modules are well documented at the node API Docs
– https://nodejs.org/dist/latest-v10.x/docs/api/modules.html

a university for the real world


R
56
CRICOS No. 00213J
circle.js
const { PI } = Math;

exports.area = (r) => PI * r * r;

exports.circumference = (r) => 2 * PI * r;


https://stackoverflow.com/questions/26999820/javascript-object-bracket-notation-navigation-on-left-side-of-assign

foo.js
const circle = require('./circle.js');

console.log(`The area of a circle of radius 4 is $


{circle.area(4)}`);

Module circle defined in the circle.js file in the same directory.


https://nodejs.org/dist/latest-v10.x/docs/api/modules.html

a university for the real world


R
57
CRICOS No. 00213J
module.exports

• Add properties to module.exports


– E.g. return an object containing the area method
– When it gets imported, we create an object of type square, and
call the area method on that object

square.js
module.exports = (side) => {
return {
area: () => side * side
};
};

a university for the real world


R
58
CRICOS No. 00213J
bar.js
const square = require('./square.js');
const mySquare = square(2);
console.log(`The area of my square is ${mySquare.area()}`);

Here we see square exposed as the module type. Use this approach
if you wish to have a particular function as the root export.

a university for the real world


R
59
CRICOS No. 00213J
Import and Export (ES2015/ES6)

• The changes for ES2015/ES6 allow us to label identifiers


directly with an export qualifier
• These are then made available in other modules via an
import syntax which is very similar to other languages
• There are two approaches
– Named export – multiple export labels in the module
– Default export – a single function for export

a university for the real world


R
60
CRICOS No. 00213J
lib.js
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}

main.js
//------ main.js ------
import { square, diag } from './lib';
const str = "Square: " + square(11) + "<br>" + "Diag: " + diag(4,3);
document.getElementById("app").innerHTML = str;

Square: 121
Diag: 5

a university for the real world


R
61
CRICOS No. 00213J
V8, Node.js

JAVASCRIPT ENGINE

a university for the real world


R
62
CRICOS No. 00213J
JavaScript Engine
• The V8 JavaScript Engine: open source, developed by
Google
• V8 is developed for Chrome web browser.
Microsoft Edge 95, Opera 80 also use V8
• V8 is also used in Node.js and MongoDB.
• V8 is written in C++
• Many other JavaScript Engines exist

• We will use Chrome and Node.js as the testing


environment

a university for the real world


R
63
CRICOS No. 00213J
Client-Side vs Server-Side JavaScript

• Client-side JavaScript scripts operate on a client


• Browsers are client-side applications
– Chrome, Firefox, Safari
• You can also write your own client-side applications
• Server-Side JavaScript scripts run on the server
– Node.js

real world
R
a university for the
64
CRICOS No. 00213J
Client Scripts

• To display error or information boxes


• To validate user input
• To display confirmation boxes
• To process server data, such as aggregate calculations
• To add programmable logic to HTML
• To perform functions that don’t require information from
the server
• To produce a new HTML page without making a request
to the server

real world
R
a university for the
65
CRICOS No. 00213J
Server Scripts

• To maintain data shared among applications or clients


• To maintain information during client accesses
• To access a database
• To access server files
• To access other libraries

real world
R
a university for the
66
CRICOS No. 00213J
CONCLUSION

a university for the real world


R
67
CRICOS No. 00213J
Summary

• Functions
– Normal functions
– Anonymous and arrow functions
– Chaining in functions
• More on Objects, Arrays, and Functions
• JSON
• Asynchronous JavaScript
• Modules
• We will learn event handling and error handling in later
weeks.

a university for the real world


R
68
CRICOS No. 00213J
Practical

1. Objects
2. Arrays
3. Functions

a university for the real world


R
69
CRICOS No. 00213J
Thank You

CRICOS No. 00213J


Queensland University of Technology 70
SELF-STUDYING SLIDES

a university for the real world


R
71
CRICOS No. 00213J
Basic Javascript Interview Questions
- Self test
• What are the different data types present in Javascript?
• What is the difference between undefined and null in Javascript?
• What is the difference between == and ===?
• What is NaN in JavaScript?
• Is JavaScript a strongly typed or a weakly typed language?
• Is JavaScript a statically typed or a dynamically typed language?
• Explain Scope in Javascript
• Describe var, let and const in JavaScript typeof "John"                 // Returns "string"
typeof 3.14                   // Returns "number"
typeof NaN                    // Returns "number"
typeof false                  // Returns "boolean"
typeof [1,2,3,4]              // Returns "object"
typeof {name:'John', age:34}  // Returns "object"
typeof new Date()             // Returns "object"
typeof function () {}         // Returns "function"
typeof myCar                  // Returns "undefined" *
typeof null                   // Returns "object"
https://www.interviewbit.com/javascript-interview-questions/

https://www.codingame.com/work/javascript-interview-questions/

a university for the real world


R
72
CRICOS No. 00213J
Reference versus Value variables

• Variables to hold data in several different formats


• Primitive data types can store only a single value - Value
variables:
– Number
– Boolean
– String
– Undefined
– Null
• Non-primitive data types can store multiple and complex
values - Reference variables:
– Object
– Array

https://www.interviewbit.com/javascript-interview-questions/#javscript-data-types

a university for the real world


R
73
CRICOS No. 00213J
JSON

• JSON stands for JavaScript Object Notation


• JSON is "self-describing" names and values
• JSON is often used when data b/t a server to a web
page

• {
"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]
}

a university for the real world


R
74
CRICOS No. 00213J
{ JSON
"first name": "John",
"last name": "Smith",
"age": 25,
"address": {
"street address": "21 2nd Street",
"city": "New York",
},
"phone numbers": [ https://en.wikipedia.org/wiki/JSON
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
],
}

a university for the real world


R
75
CRICOS No. 00213J
JSON functions

• JS provides a number of useful functions for working


with JSON, translating to and from JSON and String
representations
• Interactive examples are available at W3Schools
• JSON.stringify()
– https://www.w3schools.com/js/js_json_stringify.asp
– Convert JS object to string
• JSON.parse()
– https://www.w3schools.com/js/js_json_parse.asp
– Convert string to JS object

• For others see the sidebar at the left of these pages

a university for the real world


R
76
CRICOS No. 00213J
JavaScript built-in objects - Date
https://www.w3schools.com/js/js_date_methods.asp
Date objects are static.
Date objects are created with the new Date() constructor
new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string) //Date(year, month, day, hours,
Date minutes, seconds, milliseconds);
– getFullYear() – get year let date = new
Date(1978,4,1,0,0,0,0);
as yyyy let dayNames = ["Sunday",
– getDate() // day as a "Monday", "Tuesday",
number (1-31) "Wednesday","Thursday",
"Friday", "Saturday"];
– getTime() // milliseconds since
January 1, 1970
let today =
– getDay() // weekday as a
dayNames[date.getDay()];
number (0-6)
– …
real world
R
a university for the
CAB230 - Lecture 5 77
CRICOS No. 00213J
JavaScript built-in objects - Math
http://www.w3schools.com/js/

• E, PI, abs(), cos(), pow(), log(), floor(), sqrt(), round(), …

• the Math object has no constructor.


•  Methods and properties are static.

let r = Math.floor(Math.random()*12); // 0-11


console.log(r);
Math.PI; // returns 3.141592653589793
Math.ceil(4.4);     // returns 5
Math.floor(4.7);    // returns 4
Math.min(0, 150, 30, 20, -8, -200);  // returns -200

real world
R
a university for the
CAB230 - Lecture 5 78
CRICOS No. 00213J
AMS Exercises
https://sefams01.qut.edu.au/IFN666/

a university for the real world


R
79
CRICOS No. 00213J
AMS Exercises

• 4 Questions
• 10 Marks
– 2,2,3,3
• 15 chances per question
• average: Write a basic function to calculate and return
the average of two numbers.

• compare: Write a simple JavaScript function that takes


two parameters and compares them considering their
VALUE and TYPE, returning the boolean result of this
comparison. [HINT: This is not a complicated exercise.]

a university for the real world


R
80
CRICOS No. 00213J
AMS Exercises

• countUnique: Write a simple JavaScript function that


counts the number of unique items in an array and
returns that value. Example dataset: ['hi','hello','hi'],
unique items: 2

a university for the real world


R
81
CRICOS No. 00213J
AMS Exercises

bookSearch: Write a JavaScript function to find ALL the


books in a 'library' written by a specific author. You should
return:

The list of the book titles as a string, with titles separated


by a comma; OR 'NOT FOUND' if there is no match.

Note that there should be no trailing comma and no


additional space(s) surrounding the comma(s) - see the
examples below for details.

a university for the real world


R
82
CRICOS No. 00213J
AMS Exercise
Example dataset, input and expected output:
library = [
{ author: 'Bill Gates', title: 'The Road Ahead', libraryID: 1254},
{ author: 'Carolann Camilo', title: 'Eyewitness', libraryID: 32456},
{ author: 'Carolann Camilo', title: 'Cocky Marine', libraryID: 32457}
];
Input: [library, 'Bill Gates']
Expected Output: 'The Road Ahead'
Input: [library, 'Carolann Camilo']
Expected Output: 'Eyewitness,Cocky Marine'
Input: [library, 'Lala']
Expected Output: 'NOT FOUND'

a university for the real world


R
83
CRICOS No. 00213J

You might also like