4 Javascript
4 Javascript
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
// 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
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");
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"
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"
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.
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;
}
};
____________
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" ];
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
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
};
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