2 JavaScript
2 JavaScript
[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.
[email protected] 7 / 87
JavaScript outside of a 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).
[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
[email protected] 12 / 87
Input
[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 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
[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.
[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
[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
[email protected] 23 / 87
Expressions
[email protected] 24 / 87
Data Types
- JavaScript variables can hold many data types: number, boolean, string, array, object
and more.
[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.
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 }
- 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
- 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
- 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.
- 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
[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.
- 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.
[email protected] 37 / 87
Promise1
- 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
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
[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.
- The parseFloat() method parses a string and returns a number. Spaces are allowed.
Only the first number is returned.
[email protected] 44 / 87
Number methods
[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.
- 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 " ) ;
[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 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.
[email protected] 50 / 87
String methods
[email protected] 51 / 87
String methods
- The charAt() method returns the character at a specified index (position) in a string.
- 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).
[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
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
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
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 "
1 var arr = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 delete arr [ 0 ] ; // Changes the first element " Banana " to undefined
[email protected] 57 / 87
Array methods
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.
[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
1 var fruits = [ " Banana " , " Orange " , " Apple " , " Mango " ] ;
2 fruits.sort ( ) ; // Sorts the elements of fruits
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 } ) ;
1 var points = [ 4 0 , 1 0 0 , 1 , 5 , 2 5 , 1 0 ] ;
2 points.sort ( function ( a , b ) { return b - a } ) ;
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
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 ] ;
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
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
[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).
[email protected] 72 / 87
Random
- This below function always returns a random number between min (included) and
max (excluded).
- This below function always returns a random number between min and max (both
included).
[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
[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 ?
[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
[email protected] 81 / 87
Arrow functions
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
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
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