0% found this document useful (0 votes)
38 views42 pages

4 Javascript

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

4 Javascript

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

ECC4217 & 4207

WEB AND DATABASE


JAVASCRIPT

Siti Mariam Shafie


[email protected]
▪ Understanding JavaScript Basics
▪ Working with Functions and Control
Structures
▪ Understanding Objects and Arrays
Learning ▪ Understanding the Document Object Model
Outcome (DOM)
▪ Using Event Handling

2
ECMAScript
▪ JavaScript was invented by Brendan Eich in 1995, and became an ECMA
standard in 1997.
▪ ECMA-262 is the official name of the standard. ECMAScript (ES) is the
official name of the language
▪ Each browser has its own JavaScript engine, which either interprets the
code, or uses some sort of lazy compilation
❑ V8: Chrome and Node.js
❑ SpiderMonkey: Firefox
❑ JavaScriptCore: Safari
❑ Chakra: Microsoft Edge/IE
▪ They each implement the ECMAScript standard, but may differ for anything
not defined by the standard
3
JavaScript
▪ JavaScript is an implementation of the ECMAScript standard and one
of the most popular programming languages in the world
▪ JavaScript is a scripting or programming language used for client-side
web development but can also be used on the server-side (e.g., with
Node.js)
▪ JavaScript evolves as ECMAScript standards evolve. For example,
when ECMAScript 6 (ES6) was released, it brought features like
let/const, arrow functions, promises, and classes to JavaScript
▪ JavaScript can create dynamic web page, display timely content
updates, create interactive maps, animated 2D/3D graphics, scrolling
video jukeboxes, etc.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript 4
Syntax

let x, y, z; // Declare Variables


x = 5; y = 6; // Assign Values
z = x + y; // Compute Values

const arr = ['teaching', 42, true, function() {


console.log('hi’)
}];

// hi I'm a comment
Note:
for (let i = 0; i < arr.length; i++) { Since ES6, there are two new
console.log(arr[i]); keywords, const and let.
} Avoid using var.
5
Data Types
▪ Primitive types (immutable, hardcoded cannot be changed)
❑ Undefined
❑ Null
❑ Boolean
❑ number
❑ String

▪ Objects – can contain:


❑ An object
❑ An array
❑ A date

Note: When adding a number and a string, JavaScript will treat the number as a string 6
Examples
// Numbers:
let length = 16;
let weight = 7.5;

// Strings:
let color = "Yellow";
let lastName = "Johnson";

// Booleans
let x = true;
let y = false;

// Object:
const person = {firstName:"John", lastName:"Doe”, , age:50, eyeColor:"blue"};

// Array object:
const cars = ["Saab", "Volvo", "BMW"];

// Date object:
const date = new Date("2022-03-25");

//JavaScript evaluates expressions from left to right


let x = 16 + 4 + "Volvo";
let x = "Volvo" + 16 + 4;
7
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String

// Using double quotes:


let carName1 = "Volvo XC60";

// Using single quotes:


let carName2 = 'Volvo XC60’;

// Single quote inside double quotes:


let answer1 = "It's alright";

// Single quotes inside double quotes:


let answer2 = "He is called 'Johnny'";

// Double quotes inside single quotes:


let answer3 = 'He is called "Johnny”’;

let y = 123e5; // 12300000


let z = 123e-5; // 0.00123

let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false

8
Control flow if (condition1) {
statement1;
} else if (condition2) {
▪ if...else statement statement2;
} else if (conditionN) {
statementN;
} else {
statementLast;
}

switch (expression) {
case label1:
▪ switch statement statements1;
break;
case label2:
statements2;
break;
// …
default:
statementsDefault;
9
}
Error Handling
• throw statement
• try...catch statement

https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling

10
Loop and iteration
const arr = [3, 5, 7];
▪ for...in statement arr.foo = ‘hello’;
▪ for...of statement for (const i in arr) {
console.log(i);
} // "0" "1" "2" "foo"

for (const i of arr) {


console.log(i);
} // Logs: 3 5 7

▪ More loops and details:


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
11
JavaScript Where To
▪ In HTML, JavaScript code is inserted between <script> and </script>
tags
▪ You can place any number of scripts in an HTML document
▪ Scripts can be placed in the <body>, or in the <head> section of an
HTML page, or in both
▪ Scripts can also be placed in external files with extension .js.
Advantages:
❑ It separates HTML and code
❑ It makes HTML and JavaScript easier to read and maintain
❑ Cached JavaScript files can speed up page loads.
<script src="myScript.js"></script>
12
Using let and const (2015)
▪ The 2015 version of JavaScript (ES6 - ECMAScript 2015) allows the use of
the const keyword to define a variable that cannot be reassigned, and
the let keyword to define a variable with restricted scope
▪ Variables declared with the let keyword can have Block Scope
{
let x = 2;
}
// x can NOT be used here
▪ Variables declared with var and let are quite similar when declared inside a
function
▪ Variables declared with var and let are quite similar when declared outside
a block.
13
Declare Your Variables At the Top !
▪ Hoisting is (to many developers) an unknown or overlooked behavior of
JavaScript.
▪ Hoisting means that a variable or function is moved to the top of their
scope of where we defined the variable or function.
▪ If a developer doesn't understand hoisting, programs may contain bugs
(errors).
▪ To avoid bugs, always declare all variables at the beginning of every
scope.
▪ Since this is how JavaScript interprets the code, it is always a good rule.
Note:
Variables created without a declaration keyword (var, let, or const) are always global,
even if they are created inside a function 14
15
Function
▪ Syntax
Invoking a Function as a Function

▪ A JavaScript function is executed when "something" invokes it (calls


it)
❑ When an event occurs (when a user clicks a button)
❑ When it is invoked (called) from JavaScript code
❑ Automatically (self invoked)

16
Function Call
▪ With the call() method, you can write a method that can be used
on different objects
▪ Syntax
//applies object to function and calls the function, object applied
only for that call functionName.call(assignedObject, passedParams);

var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
person.fullName.call(person1, "Oslo", "Norway"); 17
Function Invocation
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
Invoking a Function as a Method
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // Will return "John Doe"

// This is a function constructor:


function myFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2; Invoking a Function with a
} Function Constructor

// This creates a new object


var x = new myFunction("John", "Doe");
x.firstName; // Will return "John" 18
Function Apply
▪ With the apply() method, you can write a method that can be
used on different objects. Accepts arguments in an array.

var person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
person.fullName.apply(person1, ["Oslo", "Norway"]);

19
Example: factorial
function fac(x) {
if (x <= 1){
return 1;
}
return x * fac(x - 1);
}

fac();

20
JavaScript Scope
▪ Scope determines the accessibility (visibility) of
variables.
▪ JavaScript has 3 types of scope:
• Block scope
• Function scope
• Global scope
▪ Example:
https://www.javatpoint.com/javascript-scope

https://javascript.plainenglish.io/javascript-interview-questions-functions-and-scope-8c8793f2ef5d
21
Objects
▪ Objects are variables too. But objects can contain many values
▪ Objects can have properties and/or methods
▪ There are different ways to create new objects:
❑ Define and create a single object, using an object literal Note:
For readability,
var car = {type:"Fiat", model:"500", color:"white"}; simplicity and
❑ Define and create a single object, with the keyword new execution speed,
use the object
var person = new Object(); literal method
person.firstName = "John";

❑ Define an object constructor, and then create objects of the constructed type.

▪ Displaying a JavaScript object will output [object Object]


22
23
Object Example

24
Object Accessors
▪ ECMAScript 5 (2009) introduced Getter and Setters.
▪ This example uses a lang property to get the value of
the language property.
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
language : "en", access lang as a property
get lang() {
return this.language;
}
};

// Display data from the object using a getter:


25
document.getElementById("demo").innerHTML = person.lang;
Object Constructor and Prototypes
▪ A constructor function is just a blueprint for “constructing” other
objects
▪ All JavaScript objects inherit properties and methods from a
prototype
▪ You can not add a new property to an existing object constructor
▪ To add a new property to a constructor, you must add it to the
constructor function
▪ The JavaScript prototype property also allows you to add new
methods to objects constructors
https://www.w3schools.com/js/js_object_constructors.asp
https://www.w3schools.com/js/js_object_prototypes.asp 26
Exercise
▪ Use comments to describe the correct data type of the
following variables:

let length = 16; // ________


let lastName = "Johnson"; // ________
const x = { firstName: "John", lastName: "Doe" }; // ________

▪ Execute the function named myFunction


function myFunction() {
alert("Hello World!");
};

____________
27
Events
▪ When JavaScript is used in HTML pages, JavaScript can "react" on
events such as
❑ An HTML web page has finished loading
❑ An HTML input field was changed
❑ An HTML button was clicked

28
JavaScript Output
▪ JavaScript can "display" data in different ways:
❑ Writing into an HTML element, using innerHTML.
❑ Writing into the HTML output using document.write().
❑ Writing into an alert box, using window.alert().
❑ Writing into the browser console, using console.log()

29
Array
▪ Using an array literal is the easiest way to create a JavaScript Array
var cars = [ "Saab", "Volvo", "BMW" ];

▪ Another way to create an Array is using keyword new


var cars = new Array("Saab", "Volvo", "BMW");

▪ Access an array element by referring to the index number


var name = cars[0];

30
https://www.w3schools.com/js/js_array_methods.asp 31
Array Iteration Methods
▪ The forEach() method
calls a function (a callback
function) once for each
array element

https://www.w3schools.com/js/js_array_iteration.asp
32
JavaScript Arrow Function
▪ Arrow functions were introduced in ES6.
▪ Arrow functions allow us to write shorter function syntax:
hello = function() {
return "Hello World!";
}

hello = () => {
return "Hello World!";
}
▪ It gets shorter! If the function has only one statement, and the statement
returns a value, you can remove the brackets and the return keyword
hello = () => "Hello World!";
33
Asynchronous JavaScript
▪ Functions running in parallel with other functions are called
asynchronous
▪ In the real world, callbacks are most often used with asynchronous
functions.
▪ A typical example is JavaScript setTimeout()

setTimeout(myFunction, 3000);

function myFunction() {
document.getElementById("demo").innerHTML = "I love Coding !!";
}

34
JS HTML Document Object Model (DOM)
▪ HTML DOM (created when a page is loaded) allow
JavaScript to access and manipulate document objects
(HTML elements) that is displayed in a browser window
▪ Each object has:
❑ methods - actions you can perform (on HTML Elements) for
example: document.getElementById(),
document.createElement(), document.write(), etc
❑ properties - values (of HTML Elements) that you can set or
change for example: element.innerHTML, element.style.color,
element.attribute, etc
▪ To access any element in an HTML page, you always
start with accessing the document object for example:
❑ document.getElementById(id)
❑ document.getElementsByTagName(tag)
❑ document.getElemenstByClassName(classname)
▪ You can also access using CSS selectors for example:
❑ document.querySelector(‘#id’)
❑ document.querySelectorAll(’.classname’)

https://www.w3schools.com/js/js_htmldom.asp
35
JavaScript Can
▪ With the object model, JavaScript gets all the power it needs to
create dynamic HTML
❑ JavaScript can change all the HTML elements in the page
❑ JavaScript can change all the HTML attributes in the page
❑ JavaScript can change all the CSS styles in the page
❑ JavaScript can remove existing HTML elements and attributes
❑ JavaScript can add new HTML elements and attributes
❑ JavaScript can react to all existing HTML events in the page
❑ JavaScript can create new HTML events in the page

36
DOM Events
▪ A JavaScript can be executed when an event occurs, like when a user
clicks on an HTML element
▪ Examples of HTML events:
❑ When a user clicks the mouse
❑ When a web page has loaded
❑ When an image has been loaded
❑ When the mouse moves over an element
❑ When an input field is changed
❑ When an HTML form is submitted
❑ When a user strokes a key

37
How to trigger JavaScript code on an event?
▪ Add event attribute in HTML element for example: Only the function
❑ <p id=“demo” onclick=“myFunction();”>Hello</p> name without the
bracket

▪ Register an event handler to an element using


the addEventListener() method for example:
❑ Syntax: element.addEventListener(event, function, useCapture);
❑ document.querySelector(‘#demo’).addEventListener(‘click’, myFunction);

▪ Assign anonymous function to event property for example:


❑ document.querySelector(‘#demo’).onclick = function(){myFunction();};

https://www.w3schools.com/jsref/event_onclick.asp
38
How to execute JavaScript after page load?
▪ Approach 1: Using the window.onload Event
❑ The window.onload event is triggered when the entire page, including all assets (such as
images, stylesheets, and scripts), has finished loading.
window.onload = function() {
// Your JavaScript code here
};

▪ Approach 2: Using the DOMContentLoaded Event


❑ The DOMContentLoaded event fires as soon as the initial HTML document has been
completely loaded and parsed, without waiting for stylesheets, images, or subframes to finish
loading.
document.addEventListener('DOMContentLoaded', function() {
// Your JavaScript code here
});
39
JS Animations
▪ JavaScript animations are done by programming gradual changes in an element's style
▪ The changes are called by a timer. When the timer interval is small, the animation looks
continuous
A function to be executed every 5 milliseconds
▪ The basic code is:

id = setInterval(frame, 5);

function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}

https://www.w3schools.com/js/tryit.asp?filename=tryjs_dom_animate_3 40
Exercise
▪ Write JavaScript code to execute two functions when hovering a
mouse cursor on a button element.
❑ The first function will get the current object as a parameter and set the
background color to cyan.
❑ The second function will get the current object as a parameter and set the
font color to white.
▪ Write three different html documents to implement different ways of
executing the functions.

41
Reference
▪ https://www.w3schools.com/jsref/default.asp
▪ https://www.w3schools.com/js
▪ Jordan Hayashi, CS50M EDX

42

You might also like