Download presentation
Presentation is loading. Please wait.
1
Tutorial 4 JavaScript as OOP Li Xu
Department of Systems Engineering and Engineering Management
2
JavaScript and Objects
Technically, ”Everything” in JavaScript is Object Array, String, Number, … An object contains properties and methods Property has a name and value Methods are actions that can be performed on the object
3
Some Important JavaScript Keywords
Description String To manipulate text strings Number To manipulate numbers Operators To assign values, compare values, perform arithmetic operations … Statements “Instructions" to be "executed" by the web browser in HTML Math To manipulate calculations Date Retrieves and manipulates dates and times Array Creates new array objects Boolean Creates new Boolean objects Error Returns run-time error information Global Represents global variables and contains various built-in JS methods Conversion Converts different JS values to Number, String, Boolean
4
String Case sensitive String Methods: s.length; s.indexOf(“to”) ;
s.slice(3,7); s.replace(“CUHK”,”HongKong”); s.toLowerCase(); s.concat(" ", "Campus"); s.charAt(1); …… var s = “Welcome to CUHK”
5
Number Numbers can be written with scientific notation
e.g. var y = 123e-5; Number Methods Number.isFinite(x) ; Number.isInteger(x); Number.isNaN(x); x.toPrecision(3); x.toString(); ……. var x = 2.017;
6
Statements JavaScript statements often start with a statement identifier while (i < 10){ … } if (i < 10){ … } else if{ } else{ } for (i =0; i < 10; i++ ){ … }
7
Statements try { switch (i){ … //code to try to run case 1: } …
catch(error){ …// code to handle errors finally{ … // code executed regardless of the try / catch result switch (i){ case 1: … break; case 2: default: }
8
Math Math object allows you to perform mathematical tasks.
Math methods: Math.PI; Math.pow(2,3); Math.sqrt(64); Math.abs(-3.17); Math.ceil(3.17); Math.floor(3.17); Math.random(); Math.max(0,10,6,55); ……
9
Date Date object works with dates and times
Four ways to instantiate a date: var d = new Date(); var d = new Date(milliseconds); //zero time is 01 Jan :00:00 UTC var d = new Date(dateString); var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
10
Date Methods …… d.getDate(); //get day as a number(1-31)
d.getFullYear(); //get the four digit year(yyyy) d.setDate(15); //set day as a number(1-31) d.setFullYear(2100,0,14); //sets a date object to a specific date Date.parse("March 21, 2012"); // returns the number of milliseconds between the date and January 1, 1970 ……
11
Array Array object is used to store multiple values in a single variable. e.g. var fruits = [“banana”,”apple”,”orange”]; Array indexes are zero-based. e.g. fruits[0] = “banana”; Array elements can be objects, like functions or arrays. e.g. myArray[0] = Date.getDay(); myArray[1] = fruits;
12
Array Methods Popping and Pushing Shifting Elements Deleting Elements
x=fruits.pop(); // removes the last element, return the last element y=fruits.push(“Mango”); // adds element “Mango” to array fruits, return the length of new array Shifting Elements x=fruits.shift(); // removes the first element, return the first element. y=fruits.unshift(“Lemon”); // add element “Lemon” to array fruits, return the length of new array Deleting Elements delete fruits[1]; // change the second element in fruits to undefined Using delete may leave undefined holes in the array. Use pop() or shift() instead. var fruits = [“Banana”,”Apple”,”Orange”];
13
Array Methods Splicing an Array Merging Arrays
var fruits = [“Banana”,”Apple”,”Orange”]; var color = [“red”,”blue”]; var points = [21,14,17,61,8]; Splicing an Array fruits.splice(1,2,”Lemon”); The first parameter defines the position where to add new elements The second parameter defines how many elements should be removed The rest parameters define the new elements to be added Merging Arrays new_arr=fruits.concat(color); // concatenates array fruits and color Sorting an Array By default, sort() function sorts value as strings fruits.sort(); // sort an array alphabetically fruits.reverse(); // sort an array in descending order points.sort(function(a,b){ return a-b}); //numeric sort points.sort(function(a,b){ return b-a}); //numeric sort in descending order fruits don’t change here!!!
14
Conversion The table below shows the result of converting JS values to Number, String, and Boolean Original Value Converted to Number Converted to String Converted to Boolean false "false" true 1 "true" "0" "1" "20" 20 "twenty" NaN [ ] "" [20] [10,20] "10,20" ["ten","twenty"] "ten,twenty"
15
JavaScript Common Mistakes
Mistake Types Accidentally Using the Assignment Operator Expecting Loose Comparison Confusing Addition & Concatenation Misunderstanding Floats Breaking a JavaScript String Misplacing Semicolon Breaking a Return Statement Accessing Arrays with Named Indexes Ending Definitions with a Comma Undefined is Not Null Expecting Block Level Scope
16
Accidentally Using the Assignment Operator
Description JavaScript programs may generate unexpected results if a programmer accidentally uses an assignment operator (=), instead of a comparison operator (==) in an if statement. Examples: var x = 0; if (x = 10) // returns true, bec 10 is true if (x == 10) // returns false, bec x is not equal to 10 if (x = 0) // returns false, bec 0 is false
17
Expecting Loose Comparison
Description In regular comparison, data type does not matter. In strict comparison, data type does matter. It is a common mistake to forget that switch statements use strict comparison. Examples: var x = 10; var y = “10”; if (x == y) // returns true if (x === y) // returns false switch(x) { case “10”: alert(“Hello”); // not display case 10: alert(“Hello”); // display }
18
Confusing Addition & Concatenation
Description Addition is about adding numbers. Concatenation is about adding strings. In JavaScript both operations use the same + operator. Because of this, adding a number as a number will produce a different result from adding a number as a string Examples: var x = ; // x = 15 var y = 10 + “5”; // y = “105”
19
Misunderstanding Floats
Description All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats). All programming languages, including JavaScript, have difficulties with precise floating point values Examples: var x = 0.1; var y = 0.2; var z = x+y; // z will not be exactly 0.3 To solve the problem, using var z = (x*10+y*10)/10; // z will be 0.3
20
Breaking a JavaScript String
Description JavaScript will allow you to break a statement into two lines But, breaking a statement in the middle of a string will not work You must use a "backslash" if you must break a statement in a string Examples: var x = “Hello World”; //correct var x = “Hello World”; //wrong var x = “Hello \ World”; //correct
21
Misplacing Semicolon Description Examples: if (x == 19); {
Because of a misplaced semicolon, this code block will execute regardless of the value of x Examples: if (x == 19); { //code block }
22
Breaking a Return Statement
Description It is a default JavaScript behavior to close a statement automatically at the end of a line Examples: function myFunction(a) { var power = 10 return a * power } function myFunction(a) { var power = 10; return a * power; } function myFunction(a) { var power = 10; return a * power; } function myFunction(a) { var power = 10; return a * power; } function myFunction(a) { var power = 10; return; a * power; } Same reults Same reults
23
Explanation If a statement is incomplete like:
var JavaScript will try to complete the statement by reading the next line: power = 10; But since this statement is complete: return JavaScript will automatically close it like this: return; This happens because closing (ending) statements with semicolon is optional in JavaScript. JavaScript will close the return statement at the end of the line, because it is a complete statement.
24
Accessing Arrays with Named Indexes
Description Many programming languages support arrays with named indexes Arrays with named indexes are called associative arrays (or hashes) JavaScript does not support arrays with named indexes In JavaScript, arrays use numbered indexes Examples: var person = []; person[0] = "John"; person[1] = "Doe"; person[2] = 46; var x = person.length;// person.length will return 3 var y = person[0];// person[0] will return "John"
25
Accessing Arrays with Named Indexes
Description In JavaScript, objects use named indexes If you use a named index, when accessing an array, JavaScript will redefine the array to a standard object After the automatic redefinition, array methods and properties will produce undefined or incorrect results Examples: var person = []; person["firstName"] = "John” person["lastName"] = "Doe"; person["age"] = 46; var x = person.length;// person.length will return 0 var y = person[0];// person[0] will return undefined
26
Ending Definitions with a Comma
Description Trailing commas in object and array definition are legal in ECMAScript 5 Internet Explorer 8 will crash. JSON does not allow trailing commas. Examples: person = {firstName:"John", lastName:"Doe", age:46,} // ECMAScript 5 person = \ {"firstName":"John", "lastName":"Doe ", "age":46} // JSON
27
Undefined is Not Null Description
JavaScript objects, variables, properties, and methods can be undefined empty JavaScript objects can have the value null You can test if an object exists by testing if the type is undefined Examples (Assume myObj is undefined): if (typeof myObj === "undefined") //correct if (myObj === null) //incorrect if (myObj !== null && typeof myObj !== "und efined") //incorrect if (typeof myObj !== "undefined" && myObj !== null) //correct
28
Expecting Block Level Scope
Description JavaScript does not create a new scope for each code block Examples: for (var i = 0; i < 10; i++) { // some code } return i; //This code will display the value of i (10), even OUTSIDE the for loop block
29
Resources https://www.w3schools.com/js/default.asp
30
Questions and Answers
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.