0% found this document useful (0 votes)
14 views87 pages

2 JavaScript

web
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)
14 views87 pages

2 JavaScript

web
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

JavaScript

Trang Hồng Sơn

[email protected]

[email protected] 1 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 2 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 3 / 87
Web page EVENT & DHTML
- JavaScript is a programming language that first appeared in 1995 to give browsers
their first type of smart functionality.
• Web page EVENT: loading a page, hovering over an image, clicking on a title, ...
• DHTML: was classified as anything that combined HTML, JavaScript and CSS
with the purpose of generating dynamic effects (e.g. animate text, rollover
buttons, show/hide elements) based on a user’s actions (e.g. mouse click,
hovering or pointing the mouse over elements).

[email protected] 4 / 87
AJAX & jQuery

- Starting in 2004, JavaScript usage underwent a major shift with a technique called
AJAX, an acronym for ’Asynchronous JavaScript and XML’. AJAX brought a new era
of web pages capable of updating dynamically without any apparent communication
with their origin web site.

- The jQuery JavaScript library – created in 2006 – established itself as the most
popular choice for two purpose:
• The first was JavaScript as a language was severely fragmented, mainly due to the
browser wars.
• The second issue was JavaScript relied on the DOM (Document Object Model) to
access and navigate the structure of web pages. There’s really no quick way to
explain the DOM.

[email protected] 5 / 87
JavaScript components
- JavaScript components:
• allow HTML and JavaScript to be rolled into the same unit and not live separately.
• re-use the same unit multiple times in the same application or across projects.
• easier to test UI behavior, since presentation and logic are encapsulated into the
same unit.
- The most popular JavaScript component approaches include:
• React.- Developed by Facebook, React is one of the clear front-runners in this
space, mainly because it’s designed for just this purpose of building user
interfaces. Because of its limited scope, React is used alongside and complements
more feature rich JavaScript frameworks (e.g. Angular, Node JS).
• Angular.- Developed by Google, Angular is another strong contender in this space.
However, unlike React, Angular is a full-fledged MVC framework, which means
that in addition to having its own JavaScript components, Angular also offers a
wide range of add-ons like controllers and service bindings for components.
• Web Components (http://webcomponents.org)

[email protected] 6 / 87
JavaScript MVC frameworks

- These design patterns consisting of things like web page routing (i.e. what page
sequence to follow for a given task), business logic execution and data validation, are
known by the broader name Model-View-Controller (MVC) architecture.

- The most popular JavaScript MVC frameworks include:


• Angular.- Developed by Google, Angular is one of the clear front-runners in this
space. Angular was initially released in 2010 making it one of the first JavaScript
MVC frameworks. In addition, Angular is now in its eighth major release
incorporating a lot of ’learned lessons’ from its initial release named AngularJS.
• Ember.- Although not as popular as Angular, Ember is another JavaScript MVC
framework alternative. Similar to Angular, Ember has its own JavaScript
components, controllers and model facilities.

[email protected] 7 / 87
JavaScript outside of a browser

- JavaScript running outside of a browser is dominated by NodeJS, a platform based


on the same V8 engine used by Google’s Chrome browser.

- What’s interesting about NodeJS isn’t its ability to run JavaScript outside of a
browser per se, but rather its ability to provide asynchronous & non-blocking behavior,
making it an ideal choice for real-time web applications (e.g. chats, live event
publishing).

[email protected] 8 / 87
What is modern JavaScript?

- Well in 1995 modern was JavaScript events, in 2004 modern was AJAX, in 2006
modern was jQuery, in 2010 modern was Angular1, in 2012 modern was NodeJS, in
2014 modern was React, in 2016 modern was Angular2 and in 2019 modern was the
Deno runtime (https://deno.land).

- So modern JavaScript is really a wide and moving target.

[email protected] 9 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 10 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 11 / 87
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 console of NodeJS, using:
• process.stdout.write()
• console.log()

1 p r o c e s s . s tdout.write ( " Hello World " ) ;


2 console.log ( " Hello World " ) ;

[email protected] 12 / 87
Input

- JavaScript can "receive" data in different ways:


• Get input from a prompt box, using: window.prompt()
• Get input from the console of NodeJS, using:
• process.stdin.once("data", (input) => {...})

1 pr oc es s.s tdin.once ( " data " , ( input ) => {


2 console.log ( " Hello " + input ) ;
3 process.exit ( ) ;
4 });

[email protected] 13 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 14 / 87
Statements
- A computer program is a list of "instructions" to be "executed" by a computer. In a
programming language, these programming instructions are called statements. A
JavaScript program is a list of programming statements.

- JavaScript statements are composed of: Variables, Operators, Expressions, Keywords,


and Comments.

- Semicolons separate JavaScript statements.

- JavaScript statements can be grouped together in code blocks, inside curly brackets
{...}

1 { // Code block
2 var a, b, c; // Declare 3 variables
3 a = 6; // Assign the value 6 to a
4 b = 9; // Assign the value 9 to b
5 c = a + b; // Assign the sum of a and b to c
6 }

[email protected] 15 / 87
Comments

- Not all JavaScript statements are "executed".

- Code after double slashes // or between /* and */ is treated as a comment.

- Comments are ignored, and will not be executed.

1 var x = 6 ; // I will be executed


2 // var y = 9; // I will NOT be executed

[email protected] 16 / 87
Keywords
- JavaScript statements often start with a keyword to identify the JavaScript action to
be performed.

Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do ... while Executes a block of statements, and repeats the block, while a condition is true
for Marks a block of statements to be executed, as long as a condition is true
function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
try ... catch Implements error handling to a block of statements
var Declares a variable

[email protected] 17 / 87
Identifiers
- Identifiers are unique names which used to variable name or function name.

- The rules for legal names are much the same in most programming languages.
• The first character must be a letter, or an underscore (_), or a dollar sign ($).
• Subsequent characters may be letters, digits, underscores, or dollar signs.

- Historically, programmers have used different ways of joining multiple words into one
variable name:
• Hyphens: first-name, last-name, master-card, inter-city.
• Underscore: first_name, last_name, master_card, inter_city.
• Upper Camel Case (Pascal Case): FirstName, LastName, MasterCard, InterCity.
• Lower Camel Case: firstName, lastName, masterCard, interCity.
» JavaScript programmers tend to use camel case that starts with a lowercase letter.

- Identifiers are case sensitive.


[email protected] 18 / 87
Variables

- JavaScript variables are containers for storing data values.

- Declare a JavaScript variable with the "var" keyword.

1 var x = 6 ; // x stores the value 6


2 var y = 9 ; // y stores the value 9
3 var z = x + y ; // z stores the value 15

[email protected] 19 / 87
Operators
- Arithmetic operators are used to perform arithmetic on numbers.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Division Remainder)
** Exponentiation
++ Increment
-- Decrement

- Assignment operators assign values to JavaScript variables.


Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y

[email protected] 20 / 87
Operators
- Comparison operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
>= greater than or equal to
< less than
<= less than or equal to
? ternary operator
- Example:
1 var a = 6 9 ;
2 var b = " 69 " ;
3 console.log ( a = = b ) ;
4 console.log ( a = = = b ) ;
5 console.log ( a > 9 6 ? true : false ) ;

[email protected] 21 / 87
Operators

- Logical operators

Operator Description
&& logical and
|| logical or
! logical not

- Type operators

Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type

[email protected] 22 / 87
Operators

- Bitwise operators work on 32 bits numbers.

Operator Description Example Same as Result Decimal


& AND 5&1 0101 & 0001 0001 1
| OR 5|1 0101 | 0001 0101 5
∼ NOT ∼5 ∼ 0101 1010 10
∧ XOR 5∧1 0101 ∧ 0001 0100 4
« Zero fill left shift 5«1 0101 « 1 1010 10
» Zero fill right shift 5»1 0101 » 1 0010 2

[email protected] 23 / 87
Expressions

- An expression is a combination of values, variables, and operators, which computes to


a value.

1 5 * 10; // can also contain literal values


2 x * 10; // can also contain variable values
3 " John " + " " + " Doe " ; // can also contain string values

[email protected] 24 / 87
Data Types

- JavaScript variables can hold many data types: number, boolean, string, array, object
and more.

1 var a = 69; // number without decimals


2 var b = 6 9 .9 6 ; // number with decimals
3 var c = true ; // boolean
4 var d = " Johnson " ; // string
5 var e = [ " Saab " , " Volvo " , " BMW " ] ; // array
6 var f = { firstName : " John " , lastName : " Doe " } ; // object

[email protected] 25 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 26 / 87
Conditional statements
- Conditional statements is used to perform different actions for different decisions.

- In JavaScript we have the following conditional statements:


• Use if to specify a block of code to be executed, if a specified condition is true.

1 if ( condition ) {
2 // block of code to be executed if the condition is true
3 }

• Use else to specify a block of code to be executed, if the same condition is false.

1 if ( condition ) {
2 // block of code to be executed if the condition is true
3 } else {
4 // block of code to be executed if the condition is false
5 }

[email protected] 27 / 87
Conditional statements

• Use else if to specify a new condition to test, if the first condition is false.

1 if ( condition 1 ) {
2 // block of code to be executed if condition1 is true
3 } else if ( condition 2 ) {
4 // block of code to be executed if the condition1 is false
and condition2 is true
5 } else {
6 // block of code to be executed if the condition1 is false
and condition2 is false
7 }

[email protected] 28 / 87
Conditional statements
• Use switch to specify many alternative blocks of code to be executed.

1 switch ( expression ) {
2 case x :
3 // code block
4 break ;
5 case y :
6 // code block
7 break ;
8 default :
9 // code block
10 }

- This is how it works:


• The switch expression is evaluated once.
• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed.
[email protected] 29 / 87
Loop statements
- Loop statements can execute a block of code a number of times.

- The while loop: loops through a block of code while a specified condition is true.

1 while ( condition ) {
2 // code block to be executed
3 }

- The do/while loop: is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop while
the condition is true.

1 do {
2 // code block to be executed
3 }
4 while ( condition ) ;

[email protected] 30 / 87
Loop statements

- The for loop: loops through a block of code a number of times.

1 for ( statement 1 ; statement 2 ; statement 3 ) {


2 // code block to be executed
3 }

- Statements are:
• Statement1 is executed (one time) before the execution of the code block.
• Statement2 defines the condition for executing the code block.
• Statement3 is executed (every time) after the code block has been executed.

[email protected] 31 / 87
Loop statements

- The for/of loop: loops through the values of an iterable object.

1 for ( variable of iterable ) {


2 // code block to be executed
3 }

- Example:

1 var names = [ " SonKK " , " DungVM " , " ThucBJ " ] ;
2 for ( var name of names ) {
3 console.log ( name ) ;
4 }

[email protected] 32 / 87
Loop statements
- The for/in loop: loops through the properties of an object.

1 for ( property in object ) {


2 // code block to be executed
3 }

- Example:

1 var obj = {
2 name : " SonKK " ,
3 age : 6 9 ,
4 email : " [email protected] "
5 };
6 for ( var prop in obj ) {
7 console.log ( prop + " = " + obj [ prop ] ) ;
8 }

[email protected] 33 / 87
Break & Continue keywords

- The break statement "jumps out" of a loop.

1 for ( var i = 1 ; i <= 1 0 ; i++) {


2 if ( i = = 3 ) { break ; }
3 console.log ( " The number is " + i ) ;
4 }

- The continue statement "jumps over" one iteration in the loop.

1 for ( var i = 1 ; i <= 1 0 ; i++) {


2 if ( i = = 3 ) { continue ; }
3 console.log ( " The number is " + i ) ;
4 }

[email protected] 34 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 35 / 87
Functions
- A JavaScript function is a block of code designed to perform a particular task.

- A JavaScript function is executed when "something" invokes it (calls it).

1 function name ( parameter 1 , parameter 2 , parameter 3 , ...) {


2 // code to be executed
3 // return value if need
4 }

- Example:

1 function myFunction ( a , b ) {
2 console.log ( " Function returns the product of a and b " ) ;
3 return a * b ;
4 }
5 var x = myFunction ( 6 , 9 ) ; // Function is called

[email protected] 36 / 87
Asynchronous
- Imagine that you’re a top singer, and fans ask day and night for your upcoming single.

- To get some relief, you promise to send it to them when it’s published. You give your
fans a list. They can fill in their email addresses, so that when the song becomes
available, all subscribed parties instantly receive it. And even if something goes very
wrong, say, fire in the studio, so that you can’t publish the song, they will still be
notified.

- This is a real-life analogy for things we often have in programming:


• A “producing code” that does something and takes time. For instance, the code
loads data over a network. That’s a “singer”.
• A “consuming code” that wants the result of the “producing code” once it’s ready.
Many functions may need that result. These are the “fans”.
• A promise is a special JavaScript object that links the “producing code” and the
“consuming code” together.

[email protected] 37 / 87
Promise1

- The constructor syntax for a promise object is:

1 var promise = new Promise ( ( resolve , reject ) => {


2 // executor ( the producing code , " singer ")
3 });

- Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code
is only inside executor.
• resolve(value) — if the job finished successfully, with result value.
• reject(error) — if an error occurred, error is the error object.

1
Nguyen-Net, Promise and async/await, 2019, url: https://viblo.asia/p/js-promise-va-
asyncawait-cuoc-chien-khong-hoi-ket-hay-la-su-dong-hanh-dang-ghi-nhan-4P856OjBKY3.
[email protected] 38 / 87
Promise
1 function interview ( gpa ) {
2 var promise = new Promise ( ( resolve , reject ) => {
3 if ( gpa < 0 ) setTimeout ( ( ) => reject ( " ERROR " ) , 1 0 0 0 ) ;
4 else if ( gpa < 5 ) setTimeout ( ( ) => resolve ( " FAIL " ) , 1 0 0 0 ) ;
5 else setTimeout ( ( ) => resolve ( " PASS " ) , 1 0 0 0 ) ;
6 });
7 return promise ;
8 }

10 interview ( 3 )
11 .then ( ( result ) => { console.log ( result ) ; } ) // handle resolve
12 .catch ( ( err ) => { console.log ( err ) ; } ) ; // handle reject

14 ( async ( ) => {
15 try { // handle resolve
16 var result = await interview ( 7 ) ;
17 console.log ( result ) ;
18 } catch ( err ) { console.log ( err ) ; } // handle reject
19 })();
20 console.log ( " TO HERE " ) ;
[email protected] 39 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 40 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 41 / 87
Number methods

- The toString() method returns a number as a string.

1 var num = 9 .6 5 6 ;
2 var str = num.toString ( ) ; // returns "9 .656 "

- The toFixed() method returns a string, with the number written with a specified
number of decimals.

1 var num = 9 .6 5 6 ;
2 var str = num.toFixed ( 2 ) ; // returns "9 .66 "

[email protected] 42 / 87
Number methods

- The Number() method can be used to convert variables to numbers.

1 Number ( true ) ; // returns 1


2 Number ( false ) ; // returns 0
3 Number ( " 10 " ) ; // returns 10
4 Number ( " 10 " ) ; // returns 10
5 Number ( " 10 " ) ; // returns 10
6 Number ( " 10 " ) ; // returns 10
7 Number ( " 10 .33 " ) ; // returns 10 .33
8 Number ( " 10 ,33 " ) ; // returns NaN ( Not a Number )
9 Number ( " 10 33 " ) ; // returns NaN
10 Number ( " John " ) ; // returns NaN
11 Number ( new Date ( " 2017 -09 -30 " ) ) ; // returns 1506729600000

[email protected] 43 / 87
Number methods
- The parseInt() method parses a string and returns a whole number. Spaces are
allowed. Only the first number is returned.

1 parseInt ( " 10 " ) ; // returns 10


2 parseInt ( " 10 .33 " ) ; // returns 10
3 parseInt ( " 10 20 30 " ) ; // returns 10
4 parseInt ( " 10 years " ) ; // returns 10
5 parseInt ( " years 10 " ) ; // returns NaN

- The parseFloat() method parses a string and returns a number. Spaces are allowed.
Only the first number is returned.

1 parseFloat ( " 10 " ) ; // returns 10


2 parseFloat ( " 10 .33 " ) ; // returns 10 .33
3 parseFloat ( " 10 20 30 " ) ; // returns 10
4 parseFloat ( " 10 years " ) ; // returns 10
5 parseFloat ( " years 10 " ) ; // returns NaN

[email protected] 44 / 87
Number methods

- The MAX_VALUE property returns the largest or lowest possible number.

1 var max = Number.MAX_VALUE ;


2 var min = - Number.MAX_VALUE ;

[email protected] 45 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 46 / 87
String methods
- The length property returns the length of a string.

1 var txt = " A B C D E F G H I J K L M N O P Q R S T U V W X Y Z " ;


2 var sln = txt.length ;

- The indexOf() method returns the index of (the position of) the first occurrence of a
specified text in a string.

1 var str = " Please locate where ' locate ' occurs ! " ;
2 var pos = str.indexOf ( " locate " ) ;

- The lastIndexOf() method returns the index of the last occurrence of a specified text
in a string.

1 var str = " Please locate where ' locate ' occurs ! " ;
2 var pos = str.lastIndexOf ( " locate " ) ;

[email protected] 47 / 87
String methods

- The search() method searches a string for a specified value and returns the position
of the match.

1 var str = " Please locate where ' locate ' occurs ! " ;
2 var pos = str.search ( " locate " ) ;

- The two methods, indexOf() and search(), are equal?


- The two methods are NOT equal. These are the differences:
• The search() method cannot take a second start position argument.
• The indexOf() method cannot take powerful search values (regular expressions).

[email protected] 48 / 87
String methods
- The slice() method extracts a part of a string and returns the extracted part in a new
string. The method takes 2 parameters: the start position, and the end position (end
not included).
1 var str = " Apple , Banana , Kiwi " ;
2 var res = str.slice ( 7 , 1 3 ) ; // from position 7 to position 12
3 var res = str.slice ( - 1 2 , - 6 ) ; // from position -12 to position -7

- The substring() method is similar to slice() method. The difference is that


substring() method cannot accept negative indexes.
1 var str = " Apple , Banana , Kiwi " ;
2 var res = str.substring ( 7 , 1 3 ) ; // from position 7 to position 12

- The substr() method is similar to slice() method. The difference is that the second
parameter specifies the length of the extracted part.
1 var str = " Apple , Banana , Kiwi " ;
2 var res = str.substr ( 7 , 6 ) ; // get 6 characters from position 7

[email protected] 49 / 87
String methods

- The replace() method replaces a specified value with another value in a string.

1 var str = " Please visit Microsoft ! " ;


2 var res = str.replace ( " Microsoft " , " IBM " ) ;

- A string is converted to upper case with toUpperCase() method.

1 var str = " Hello World ! " ;


2 var res = str.toUpperCase ( ) ;

- A string is converted to lower case with toLowerCase() method.

1 var str = " Hello World ! " ;


2 var res = str.toLowerCase ( ) ;

[email protected] 50 / 87
String methods

- The concat() method joins two or more strings.

1 var text 1 = " Hello " ;


2 var text 2 = " World " ;
3 var text 3 = text 1 .concat ( " " , text 2 ) ;

- The trim() method removes whitespace from both sides of a string.

1 var str = " Hello World ! ";


2 var res = str.trim ( ) ;

[email protected] 51 / 87
String methods

- The charAt() method returns the character at a specified index (position) in a string.

1 var str = " HELLO WORLD " ;


2 var res = str.charAt ( 0 ) ; // returns H

- The charCodeAt() method returns the unicode of the character at a specified index
in a string. The method returns a UTF-16 code (an integer between 0 and 65535).

1 var str = " HELLO WORLD " ;


2 var res = str.charCodeAt ( 0 ) ; // returns 72

- A string can be converted to an array with the split() method.

1 var str = "a ,b ,c ,d , e " ; // String


2 var arr = str.split ( " ," ) ; // Split on commas

[email protected] 52 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 53 / 87
Array methods

- The toString() method converts an array to a string of (comma separated) array


values.

1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 var str = arr.toString ( ) ; // " Banana , Orange , Apple , Mango "

- The join() method also joins all array elements into a string.

1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 var str = arr.join ( " * " ) ; // " Banana * Orange * Apple * Mango "

[email protected] 54 / 87
Array methods

- The pop() method removes the last element from an array.

1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 var x = arr.pop ( ) ; // Removes the last element " Mango " and the
value of x is " Mango "

- The push() method adds a new element to an array (at the end).

1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 var x = arr.push ( " Kiwi " ) ; // Adds a new element " Kiwi " and the
value of x is 5

[email protected] 55 / 87
Array methods

- The shift() method removes the first array element and "shifts" all other elements to
a lower index.

1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 var x = arr.shift ( ) ; // Removes the first element " Banana " and the
value of x is " Banana "

- The unshift() method adds a new element to an array (at the beginning), and
"unshifts" older elements.

1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 var x = arr.unshift ( " Lemon " ) ; // Adds a new element " Lemon " and the
value of x is 5

[email protected] 56 / 87
Array methods

- Array elements are accessed using their index number.

1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 arr [ 0 ] = " Kiwi " ; // Changes the first element to " Kiwi "

- The length property provides an easy way to append a new element to an array.

1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 arr [ arr.length ] = " Kiwi " ; // Appends " Kiwi "

- Elements can be deleted by using the operator delete.

1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 delete arr [ 0 ] ; // Changes the first element " Banana " to undefined

[email protected] 57 / 87
Array methods

- The splice() method adds new items to an array.

1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 arr.splice ( 2 , 0 , " Lemon " , " Kiwi " ) ; // [" Banana " ," Orange " ," Lemon " ,"
Kiwi " ," Apple " ," Mango "]

- Explain:
• The first parameter (2) defines the position where new elements should be added
(spliced in).
• The second parameter (0) defines how many elements should be removed.
• The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be
added.

[email protected] 58 / 87
Array methods
- The splice() method returns an array with the deleted items.

1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 arr.splice ( 2 , 2 , " Lemon " , " Kiwi " ) ; // [" Banana " ," Orange " ," Lemon " ,"
Kiwi "]

- The splice() method removes elements without leaving "holes" in the array.

1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 arr.splice ( 0 , 1 ) ; // [" Orange " ," Apple " ," Mango "]

- Explain:
• The first parameter (0) defines the position where new elements should be added
(spliced in).
• The second parameter (1) defines how many elements should be removed.
• The rest of the parameters are omitted. No new elements will be added.

[email protected] 59 / 87
Array methods

- The concat() method creates a new array by merging (concatenating) existing arrays.

1 var myGirls = [ " Cecilie " , " Lone " ] ;


2 var myBoys = [ " Emil " , " Tobias " , " Linus " ] ;
3 var myChildren = myGirls.concat ( myBoys ) ; // Concatenates ( joins )
myGirls and myBoys

- The concat() method can take any number of array arguments.

1 var arr 1 = [ " Cecilie " , " Lone " ] ;


2 var arr 2 = [ " Emil " , " Tobias " , " Linus " ] ;
3 var arr 3 = [ " Robin " , " Morgan " ] ;
4 var myChildren = arr 1 .concat ( arr 2 , arr 3 ) ; // Concatenates arr1 with
arr2 and arr3

[email protected] 60 / 87
Array methods

- The slice() method slices out a piece of an array into a new array.

1 var fruits = [ " Banana " , " Orange " , " Lemon " , " Apple " , " Mango " ] ;
2 var citrus = fruits.slice ( 2 ) ; // [" Lemon " ," Apple " ," Mango "]

- The slice() method then selects elements from the start argument, and up to (but
not including) the end argument.

1 var fruits = [ " Banana " , " Orange " , " Lemon " , " Apple " , " Mango " ] ;
2 var citrus = fruits.slice ( 1 , 3 ) ; // [" Orange " ," Lemon "]

[email protected] 61 / 87
Array methods

- The sort() method sorts an array alphabetically.

1 var fruits = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 fruits.sort ( ) ; // Sorts the elements of fruits

- The reverse() method reverses the elements in an array.

1 var fruits = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 fruits.sort ( ) ; // First sort the elements of fruits
3 fruits.reverse ( ) ; // Then reverse the order of the elements

[email protected] 62 / 87
Number array
- By default, the sort() function sorts values as strings. This works well for strings
("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is
bigger than "100", because "2" is bigger than "1".
- Fix this by providing a compare function.

1 var points = [ 4 0 , 1 0 0 , 1 , 5 , 2 5 , 1 0 ] ;
2 points.sort ( function ( a , b ) { return a - b } ) ;

- Sorting an array descending.

1 var points = [ 4 0 , 1 0 0 , 1 , 5 , 2 5 , 1 0 ] ;
2 points.sort ( function ( a , b ) { return b - a } ) ;

- Sorting an array in random order.

1 var points = [ 4 0 , 1 0 0 , 1 , 5 , 2 5 , 1 0 ] ;
2 points.sort ( function ( a , b ) { return 0 .5 - Math.random ( ) } ) ;

[email protected] 63 / 87
Number array

- Find the highest (or lowest) value.


- After an array is sorted, use the index to obtain the highest and lowest values.

1 var points = [ 4 0 , 1 0 0 , 1 , 5 , 2 5 , 1 0 ] ;
2 points.sort ( function ( a , b ) { return a - b } ) ;
3 var min = points [ 0 ] ;
4 var max = points [ points.length - 1 ] ;

- Use Math.max.apply() method to find the highest number in an array.

1 var points = [ 4 0 , 1 0 0 , 1 , 5 , 2 5 , 1 0 ] ;
2 var min = Math.min.apply ( null , points ) ;
3 var max = Math.max.apply ( null , points ) ;

[email protected] 64 / 87
Object array

- The sort() method can be used to sort the array.

1 var cars = [
2 { type : " Volvo " , year : 2 0 1 6 } ,
3 { type : " Saab " , year : 2 0 0 1 } ,
4 { type : " BMW " , year : 2 0 1 0 }
5 ];
6 cars.sort ( function ( a , b ) { return a.year - b.year } ) ; // sort by year
7 cars.sort ( function ( a , b ) { // sort by type
8 var x = a. type.toLowerCase ( ) ;
9 var y = b. type.toLowerCase ( ) ;
10 if ( x < y ) return - 1 ;
11 if ( x > y ) return 1 ;
12 return 0 ;
13 });

[email protected] 65 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 66 / 87
Date object

- Date object is created with the new Date() constructor.


- There are 4 ways to create a new date object:

1 new Date ( ) ; // return current date and time


2 new Date ( year , month , day , hours , minutes , seconds , milliseconds ) ;
3 new Date ( milliseconds ) ;
4 new Date ( date string ) ;

- Output dates in full text string format.

1 var d = new Date ( ) ;


2 d.toString ( ) ; // converts to a string
3 d.toUTCString ( ) ; // converts a date to a UTC string ( a date
display standard )
4 d.toDateString ( ) ; // converts a date to a more readable format

[email protected] 67 / 87
Get Date methods

Method Description
getFullYear() Get the year as a four digit number (yyyy)
getMonth() Get the month as a number (0-11)
getDate() Get the day as a number (1-31)
getHours() Get the hour (0-23)
getMinutes() Get the minute (0-59)
getSeconds() Get the second (0-59)
getMilliseconds() Get the millisecond (0-999)
getTime() Get the time (milliseconds since January 1, 1970)
getDay() Get the weekday as a number (0-6)
Date.now() Get the time. ECMAScript 5.

[email protected] 68 / 87
Set Date methods

Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)

[email protected] 69 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 70 / 87
Math object
- The Math object allows you to perform mathematical tasks on numbers.
1 // methods
2 Math.round ( 4 .7 ) ; // returns 5
3 Math.round ( 4 .4 ) ; // returns 4
4 Math.pow ( 8 , 2 ) ; // returns 64
5 Math.sqrt ( 6 4 ) ; // returns 8
6 Math.abs ( - 4 .7 ) ; // returns 4 .7
7 Math.ceil ( 4 .4 ) ; // returns 5
8 Math.floor ( 4 .7 ) ; // returns 4
9 Math.sin ( 9 0 * Math.PI / 1 8 0 ) ; // returns 1 ( the sine of 90 degrees )
10 Math.cos ( 0 * Math.PI / 1 8 0 ) ; // returns 1 ( the cos of 0 degrees )
11 Math.min ( 0 , 1 5 0 , 3 0 , 2 0 , - 8 , - 2 0 0 ) ; // returns -200
12 Math.max ( 0 , 1 5 0 , 3 0 , 2 0 , - 8 , - 2 0 0 ) ; // returns 150
13 Math.random ( ) ; // returns a random number
14 // properties
15 Math.E // returns Euler ' s number
16 Math.PI // returns PI
17 Math.LOG 2 E // returns base 2 logarithm of E
18 Math.LOG 1 0 E // returns base 10 logarithm of E
[email protected] 71 / 87
Random
- The Math.random() method returns a random number between 0 (inclusive), and 1
(exclusive).

1 // returns a random number from 0 to 1


2 Math.random ( ) ;
3 // returns a random integer from 0 to 9
4 Math.floor ( Math.random ( ) * 1 0 ) ;
5 // returns a random integer from 0 to 10
6 Math.floor ( Math.random ( ) * 1 1 ) ;
7 // returns a random integer from 0 to 99
8 Math.floor ( Math.random ( ) * 1 0 0 ) ;
9 // returns a random integer from 0 to 100
10 Math.floor ( Math.random ( ) * 1 0 1 ) ;
11 // returns a random integer from 1 to 10
12 Math.floor ( Math.random ( ) * 1 0 ) + 1 ;
13 // returns a random integer from 1 to 100
14 Math.floor ( Math.random ( ) * 1 0 0 ) + 1 ;

[email protected] 72 / 87
Random

- This below function always returns a random number between min (included) and
max (excluded).

1 function getRndInteger ( min , max ) {


2 return Math.floor ( Math.random ( ) * ( max - min ) ) + min ;
3 }

- This below function always returns a random number between min and max (both
included).

1 function getRndInteger ( min , max ) {


2 return Math.floor ( Math.random ( ) * ( max - min + 1 ) ) + min ;
3 }

[email protected] 73 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 74 / 87
Objects

- Objects are variables too, but objects can contain many values.

- JavaScript objects are containers for name:value pairs called properties or methods.

1 var mycar = {
2 carname : " Ford " ,
3 present : function ( x ) {
4 return x + " , I have a " + this.carname ;
5 }
6 };
7 console.log ( mycar.carname ) ; // Ford
8 console.log ( mycar.present ( " Hello " ) ) ; // Hello , I have a Ford

[email protected] 75 / 87
Classes

- Adding a function to a constructor.

1 function Car ( brand ) {


2 this.carname = brand ;
3 this.present = function ( x ) {
4 return x + " , I have a " + this.carname ;
5 };
6 }
7 var mycar = new Car ( " Ford " ) ;
8 console.log ( mycar.carname ) ; // Ford
9 console.log ( mycar.present ( " Hello " ) ) ; // Hello , I have a Ford

[email protected] 76 / 87
Outline
1. Introduction

2. Basics
2.1 Input / Output
2.2 Syntax
2.3 Conditional / Loop statements
2.4 Functions

3. Built-in Objects
3.1 Number
3.2 String
3.3 Array
3.4 Date
3.5 Math

4. Custom Object

5. ECMAScript 6

[email protected] 77 / 87
What is ES6 ?
- ES6 stands for ECMAScript 6.
- ECMAScript was created to standardize JavaScript, and ES6 is the 6th version of
ECMAScript, it was published in 2015, and is also known as ECMAScript 2015.

[email protected] 78 / 87
Why Should I Learn ES6 ?

- You should be familiar with some of the new features like:


• Variables (let, const, var)
• Arrow Functions
• Classes

[email protected] 79 / 87
Variables

- Before ES6 there were only one way of defining your variables: with the var keyword.
If you did not define them, they would be assigned to the global object.

- Now, with ES6, there are three ways of defining your variables:
• "var" has a function scope, not a block scope.
• if you use var outside of a function, it belongs to the global scope.
• if you use var inside of a function, it belongs to that function.
• if you use var inside of a block, i.e. a for loop, the variable is still available outside of
that block.
• "let" has a block scope » if you use let inside of a block, i.e. a for loop, the
variable is only available inside of that loop.
• "const" has a block scope » const is a variable that once it has been created, its
value can never change.

[email protected] 80 / 87
Variables

- For example about "var" | "let" keyword.

1 var | let gVar = 6 9 ;


2 function myFunc ( ) {
3 var | let fVar = 9 6 ;
4 console.log ( gVar ) ;
5 console.log ( fVar ) ;
6 for ( var | let bVar = 1 ; bVar <= 3 ; bVar++) {
7 console.log ( bVar ) ;
8 }
9 console.log ( bVar ) ;
10 }
11 myFunc ( ) ;
12 console.log ( gVar ) ;
13 console.log ( fVar ) ;
14 console.log ( bVar ) ;

[email protected] 81 / 87
Arrow functions

- Arrow functions were introduced in ES6.


- Arrow functions allow us to write shorter function syntax.

1 // regular function
2 function hello 1 ( ) {
3 return " Hello World ! " ;
4 }
5 // arrow function
6 hello 2 = ( ) => {
7 return " Hello World ! " ;
8 }
9 console.log ( hello 1 ( ) ) ;
10 console.log ( hello 2 ( ) ) ;

[email protected] 82 / 87
Arrow functions

- If you have parameters, you pass them inside the parentheses.

1 // regular function
2 function hello 1 ( name ) {
3 return " Hello " + name + " ! " ;
4 }
5 // arrow function
6 hello 2 = ( name ) => {
7 return " Hello " + name + " ! " ;
8 }
9 console.log ( hello 1 ( " SonKK " ) ) ;
10 console.log ( hello 2 ( " SonKK " ) ) ;

[email protected] 83 / 87
Classes

- ES6 introduced classes.


- A class is a type of function, but instead of using the keyword function to initiate it,
we use the keyword class, and the properties is assigned inside a constructor() method.

1 class Car {
2 constructor ( brand ) {
3 this.carname = brand ;
4 }
5 present ( x ) {
6 return x + " , I have a " + this.carname ;
7 }
8 }
9 var mycar = new Car ( " Ford " ) ;
10 console.log ( mycar.carname ) ; // Ford
11 console.log ( mycar.present ( " Hello " ) ) ; // Hello , I have a Ford

[email protected] 84 / 87
Classes

- Static methods are defined on the class itself, and not on the prototype.

1 class Car {
2 constructor ( brand ) {
3 this.carname = brand ;
4 }
5 present ( x ) {
6 return x + " , I have a " + this.carname ;
7 }
8 static hello ( x ) {
9 return " Hello " + x.carname ;
10 }
11 }
12 var mycar = new Car ( " Ford " ) ;
13 console.log ( Car.hello ( mycar ) ) ; // Hello Ford

[email protected] 85 / 87
Classes
- To create a class inheritance, use the extends keyword.
- A class created with a class inheritance inherits all the methods from another class.

1 class Car {
2 constructor ( brand ) { this.carname = brand ; }
3 present ( ) { return 'I have a ' + this.carname ; }
4 }
5 class Model extends Car {
6 constructor ( brand , mod ) {
7 super ( brand ) ;
8 this.model = mod ;
9 }
10 show ( ) {
11 return this.present ( ) + ' , it is a ' + this.model ;
12 }
13 }
14 var mycar = new Model ( " Ford " , " Mustang " ) ;
15 console.log ( mycar.show ( ) ) ; // I have a Ford , it is a Mustang

[email protected] 86 / 87
References

1. www.modernjs.com/what-is-modern-js.html
2. www.w3schools.com/js

[email protected] 87 / 87

You might also like