JavaScript Course v2.2
JavaScript Course v2.2
JAVASCRIPT 2
EXTERNAL JAVASCRIPT ADVANTAGES 2
JAVASCRIPT AND ECMA SCRIPT RELATION 2
NAMESPACING IN JAVASCRIPT 2
JAVASCRIPT VERSIONS 3
ECMASCRIPT 2009 (ES5) 5
ECMASCRIPT 2015 (ES6) 7
ECMASCRIPT 2016 (ES7) 8
ECMASCRIPT 2017 (ES8) 9
ECMASCRIPT 2018 (ES9) 10
ECMASCRIPT 2019 (ES10) 11
ECMASCRIPT 2020 (ES11) 12
OPTIONAL CHAINING OPERATOR → ES11 12
NULLISH COALESCING OPERATOR → ES11 12
JAVASCRIPT SYNTAX 14
JAVASCRIPT VALUES 14
JAVASCRIPT STATEMENTS 14
JAVASCRIPT EXPRESSIONS 14
JAVASCRIPT IDENTIFIERS 14
JAVASCRIPT IS CASE SENSITIVE 14
JAVASCRIPT AND CAMEL CASE 15
JAVASCRIPT CHARACTER SET 15
JAVASCRIPT COMMENTS 15
JAVASCRIPT GLOBAL 16
JAVASCRIPT GLOBAL PROPERTIES 16
JAVASCRIPT GLOBAL FUNCTIONS 16
FUNCTIONS OR METHODS? 17
ENCODEURI & ENCODEURICOMPONENT 17
UNIFORM RESOURCE IDENTIFIER (URI) 18
JAVASCRIPT SCOPE 19
1. LOCAL JAVASCRIPT VARIABLES 19
2. GLOBAL JAVASCRIPT VARIABLES 19
3. BLOCK SCOPE 19
JAVASCRIPT VARIABLES 20
AUTOMATICALLY GLOBAL 20
STRICT MODE → ES5 20
GLOBAL VARIABLES IN HTML 20
THE LIFETIME OF JAVASCRIPT VARIABLES 20
DECLARING (CREATING) VARIABLES 21
1. JAVASCRIPT VAR 21
2. JAVASCRIPT LET → ES6 21
3. JAVASCRIPT CONST → ES6 23
JAVASCRIPT HOISTING 26
JAVASCRIPT DECLARATIONS ARE HOISTED 26
JAVASCRIPT INITIALIZATIONS ARE NOT HOISTED 26
NOTE - TO AVOID HOISTING, YOU CAN RUN JAVASCRIPT IN STRICT MODE BY USING “USE STRICT ” ON
TOP OF THE CODE. 26
DECLARE YOUR VARIABLES AT THE TOP ! 26
ARITHMETIC OPERATORS 27
OPERATOR PRECEDENCE 27
EXPONENTIATION OPERATOR → ES7 30
DATA TYPES 31
1. PRIMITIVE DATA TYPE (IMMUTABLE) 31
2. COMPLEX DATA TYPE 31
OBJECT TYPES 31
JAVASCRIPT A (LOOSELY) DYNAMICALLY TYPED LANGUAGE 31
PASSED BY VALUE & PASSED BY REFERENCE. 31
NOTE: 32
STRINGS 33
ESCAPE CHARACTER 33
BREAKING LONG CODE LINES 33
STRINGS CAN BE OBJECTS 34
TEMPLATE LITERALS → ES6 34
STRING METHODS AND PROPERTIES 35
FINDING A STRING IN A STRING 35
- ALL METHODS ABOVE, ARE CASE SENSITIVE. 36
SEARCHING FOR A STRING IN A STRING 36
SEARCH VS INDEXOF ? 36
EXTRACTING STRING PARTS 36
REPLACING STRING CONTENT 37
CONVERTING TO UPPER AND LOWER CASE 38
THE CONCAT(VALUETOADDBTW, TXTTOCONCAT …) METHOD 38
THE TRIM() METHOD → ES5 38
EXTRACTING STRING CHARACTERS 38
REPEATING A STRING → ES6 39
CONVERTING A STRING TO AN ARRAY 39
COMPLETE 40
NUMBERS 41
JAVASCRIPT NUMBERS ARE ALWAYS 64-BIT FLOATING POINT 41
PRECISION 41
NUMERIC STRINGS 41
NAN - NOT A NUMBER 42
INFINITY 42
HEXADECIMAL 42
NUMBERS CAN BE OBJECTS 42
NUMBER METHODS 43
THE TOEXPONENTIAL() METHOD 43
THE TOFIXED() METHOD 43
THE TOPRECISION() METHOD 43
THE VALUEOF() METHOD 44
CONVERTING VARIABLES TO NUMBERS 44
NUMBER SAFETY CHECKING METHODS → ES6 45
NUMBER PROPERTIES 45
NEW NUMBER PROPERTIES → ES6 46
NUMBER TYPE CHECKING METHODS → ES6 46
2
BIGINT - ARBITRARY PRECISION INTEGERS → ES10 47
COMPLETE NUMBER REFERENCE. 47
BOOLEANS 48
THE BOOLEAN() FUNCTION 48
BOOLEANS CAN BE OBJECTS 48
IMPLICIT TYPE COERCION IN JAVASCRIPT. 49
STRING COERCION 49
BOOLEAN COERCION 49
EQUALITY COERCION 49
SYMBOL → ES6 50
CREATE A SYMBOL 50
SHARED SYMBOLS IN THE GLOBAL SYMBOL REGISTRY 50
“HIDDEN” PROPERTIES 50
SYMBOLS IN A LITERAL 51
SYMBOLS ARE SKIPPED BY FOR…IN 51
FINDING SYMBOL PROPERTIES ON OBJECTS 51
DISPLAY SYMBOL 51
SYMBOL DESCRIPTION → ES10 51
SYMBOL REFERENCE 52
FUNCTIONS 53
JAVASCRIPT FUNCTION SYNTAX 53
FUNCTION PARAMETERS & ARGUMENTS 54
CONVERTING ARGUMENTS TO AN ARRAY 55
DEFAULT, REST AND SPREAD PARAMETERS → ES6 55
JAVASCRIPT FUNCTION INVOCATION “CALL” 56
SELF-INVOKING FUNCTIONS 57
FUNCTIONS CAN BE USED AS VALUES OR AS EXPRESSION 57
FUNCTIONS ARE OBJECTS 57
ARROW FUNCTIONS → ES6 57
FUNCTION RETURN 58
FUNCTION CALL 58
JAVASCRIPT FUNCTION APPLY 59
JAVASCRIPT FUNCTION BIND → ES5 60
THE DIFFERENCE BETWEEN CALL(), APPLY() AND BIND() 61
JAVASCRIPT CLOSURES 61
NEW FUNCTION.TOSTRING() → ES10 62
CURRYING IN JAVASCRIPT 62
VOID OPERATOR 64
SYNTAX 64
DESCRIPTION 64
ITERATORS → ES6 65
ITERABLES 65
ITERATORS 65
ITERATORS THAT ARE ITERABLE 66
GENERATORS → ES6 68
GENERATOR FUNCTIONS 68
FUNCTION* F(…) OR FUNCTION *F(…)? 69
GENERATOR COMPOSITION 69
“YIELD” IS A TWO-WAY STREET 70
YIELD BINDS LOOSELY 70
3
USING GENERATORS FOR ITERABLES 71
USES OF GENERATORS 71
ADVANTAGES OF GENERATORS 73
DISADVANTAGES OF GENERATORS 73
OBJECTS 75
OBJECT (CREATE) DEFINITION 75
JAVASCRIPT OBJECTS ARE MUTABLE 76
OBJECT PROPERTIES 76
ENHANCED OBJECT LITERALS → ES6 78
DESTRUCTURING OBJECT → ES6 79
OBJECT METHODS 80
THE THIS KEYWORD 80
THE IN OPERATOR 80
OBJECTS ARE PASSED BY REFERENCE 81
DISPLAY OBJECTS 82
OBJECT AND INTERNAL METHODS 83
OBJECT CONSTRUCTORS 85
THE THIS KEYWORD 85
ADDING A PROPERTY TO A CONSTRUCTOR 85
OBJECT PROTOTYPES 86
PROTOTYPE-BASED PROGRAMMING 86
THREE DIFFERENT KINDS OF PROTOTYPAL OBJECT-ORIENTED. 87
OBJECT METHODS 90
ES5 OBJECT METHODS 90
ES6 OBJECT METHODS 91
ES8 OBJECT METHODS 92
REST/SPREAD OPERATOR FOR OBJECTS → ES9 93
OBJECT.FROMENTRIES(ITERABLE) 93
THIS KEYWORD 94
STANDARDIZED GLOBALTHIS OBJECT → ES10 96
ARRAYS 97
CREATING AN ARRAY 97
ACCESS THE ELEMENTS OF AN ARRAY 97
CHANGING AN ARRAY ELEMENT 97
ACCESS THE FULL ARRAY 97
ARRAYS ARE OBJECTS 97
ARRAY ELEMENTS CAN BE OBJECTS 98
ARRAY PROPERTIES 98
ACCESSING THE LAST ARRAY ELEMENT 98
DESTRUCTRING ARRAY → ES6 98
REST/SPREAD OPERATOR FOR ARRAYS → ES6 98
ASSOCIATIVE ARRAYS 99
THE DIFFERENCE BETWEEN ARRAYS AND OBJECTS IN JAVASCRIPT 99
HOW TO RECOGNIZE AN ARRAY 99
DECLARES A THREE DIMENSIONAL ARRAY 100
ARRAY METHODS 101
CONVERTING ARRAYS TO STRINGS 101
AUTOMATIC TOSTRING() 101
POPPING AND PUSHING 101
4
SHIFTING ELEMENTS 101
UNSHIFTING ELEMENTS 101
DELETING ELEMENTS (DON’T USE IT) 102
SPLICING AN ARRAY 102
MERGING (CONCATENATING) ARRAYS 102
SLICING AN ARRAY 103
REVERSING AN ARRAY 103
SORTING AN ARRAY 103
NUMERIC SORT 104
THE COMPARE FUNCTION 104
SORTING AN ARRAY IN RANDOM ORDER 104
FIND THE HIGHEST (OR LOWEST) ARRAY VALUE 104
HOME BUILT METHODS FOR MIN AND MAX 105
SORTING OBJECT ARRAYS 105
ARRAY ITERATION METHODS 107
ARRAYVAR.FOREACH() → ES5 107
ARRAYVAR.MAP() →ES5 107
ARRAYVAR.FILTER() → ES5 107
ARRAYVAR.REDUCE() & ARRAYVAR.REDUCERIGHT() → ES5 108
ARRAYVAR.EVERY() → ES5 108
ARRAYVAR.SOME() → ES5 108
ARRAYVAR.INDEXOF() → ES5 109
ARRAYVAR.LASTINDEXOF() → ES5 109
ARRAYVAR.ENTRIES () → ES6 109
ARRAYVAR.FIND() → ES6 109
ARRAYVAR.FINDINDEX() → ES6 110
ARRAY.FROM() → ES6 110
ARRAY.OF() → ES6 110
ARRAY.FILL() → ES6 111
ARRAYVAR.INCLUDES() → ES7 111
ARRAYVAR.FLAT() → ES10 111
ARRAYVAR.FLATMAP() → ES10 112
COMPLETE ARRAY REFERENCE. 112
DATE OBJECTS 113
JAVASCRIPT DATE OUTPUT 113
CREATING DATE OBJECTS 113
DATE METHODS 114
DATE FORMATS 115
JAVASCRIPT DATE INPUT 115
JAVASCRIPT DATE OUTPUT 116
TIME ZONES 116
DATE INPUT - PARSING DATES 116
GET DATE METHODS 117
THE NOW() METHOD → ES5 117
THE GETTIME() METHOD 117
THE GETFULLYEAR() METHOD 117
THE GETMONTH() METHOD 117
THE GETDATE() METHOD 117
THE GETHOURS() METHOD 117
THE GETMINUTES() METHOD 117
THE GETSECONDS() METHOD 118
THE GETMILLISECONDS() METHOD 118
THE GETDAY() METHOD 118
5
UTC DATE METHODS 118
SET DATE METHODS 120
THE SETFULLYEAR() METHOD 120
THE SETMONTH() METHOD 120
THE SETDATE() METHOD 120
THE SETHOURS() METHOD 120
THE SETMINUTES() METHOD 121
THE SETSECONDS() METHOD 121
THE SETMILLISECONDS() METHOD 121
COMPARE DATES 121
MAP DATA-STRUCTURE → ES6 122
MAP CREATION 122
INITIALIZE A MAP WITH VALUES 122
ADD ITEMS TO A MAP 122
GET AN ITEM FROM A MAP BY KEY 122
MAP KEYS 122
DELETE AN ITEM FROM A MAP BY KEY 123
DELETE ALL ITEMS FROM A MAP 123
CHECK IF A MAP CONTAINS AN ITEM BY KEY 123
FIND THE NUMBER OF ITEMS IN A MAP 123
ITERATING OVER A MAP 123
CONVERT TO ARRAY 124
WEAKMAP 124
SET DATA-STRUCTURE → ES6 125
INITIALIZE A SET 125
INITIALIZE A SET WITH VALUES 125
ADD ITEMS TO A SET 125
CHECK IF AN ITEM IS IN THE SET 125
DELETE AN ITEM FROM A SET BY KEY 125
DETERMINE THE NUMBER OF ITEMS IN A SET 126
DELETE ALL ITEMS FROM A SET 126
ITERATE THE ITEMS IN A SET 126
CONVERT THE SET KEYS INTO AN ARRAY 126
RELATION WITH ARRAY OBJECTS 127
REMOVE DUPLICATE ELEMENTS FROM THE ARRAY 127
A WEAKSET 127
REFLECT OBJECT → ES6 128
STATIC METHODS 128
MATH OBJECT 131
MATH CONSTRUCTOR 131
MATH.ROUND() 131
MATH.POW() 131
MATH.SQRT() 131
MATH.ABS() 131
MATH.CEIL() 131
MATH.FLOOR() 132
MATH.SIN() 132
MATH.COS() 132
MATH.MIN() AND MATH.MAX() 132
MATH.RANDOM() 132
MATH.TRUNC() → ES6 132
MATH.CBRT() → ES6 133
6
MATH.SIGN() → ES6 133
MATH PROPERTIES (CONSTANTS) 133
RANDOM 134
A PROPER RANDOM FUNCTION 134
COMPARISON & LOGICAL OPERATORS 135
COMPARISON OPERATORS 135
LOGICAL OPERATORS 135
CONDITIONAL (TERNARY) OPERATOR 135
BINARY LOGICAL OPERATORS 136
COMPARING DIFFERENT TYPES 136
CONDITIONS 137
CONDITIONAL STATEMENTS 137
COMMON CODE BLOCKS IN SWITCH 138
SWITCHING DETAILS 139
STRICT COMPARISON 139
LOOPS 140
1. THE FOR LOOP 140
2. THE FOR/IN LOOP 141
3. THE FOR/OF LOOP → ES6 141
4. THE WHILE LOOP 141
5. THE DO/WHILE LOOP 142
COMPARING FOR AND WHILE 142
BREAK & CONTINUE 143
THE BREAK STATEMENT 143
THE CONTINUE STATEMENT 143
JAVASCRIPT LABELS 143
TYPE CONVERSION 144
THE DATA TYPE OF TYPEOF 144
THE CONSTRUCTOR PROPERTY 144
JAVASCRIPT TYPE CONVERSION 144
CONVERTING NUMBERS, BOOLEANS AND DATES TO STRINGS 144
CONVERTING BOOLEANS AND DATES TO NUMBERS 144
AUTOMATIC TYPE CONVERSION 144
AUTOMATIC STRING CONVERSION 145
JAVASCRIPT TYPE CONVERSION TABLE 145
BITWISE OPERATIONS 147
JAVASCRIPT USES 32 BITS BITWISE OPERANDS 147
BITWISE AND ( & ) 147
BITWISE OR ( | ) 147
BITWISE XOR ( ^ ) 147
JAVASCRIPT BITWISE NOT ( ~ ) 148
JAVASCRIPT (ZERO FILL) BITWISE LEFT SHIFT (<<) 148
JAVASCRIPT (SIGN PRESERVING) BITWISE RIGHT SHIFT (>>) 148
JAVASCRIPT (ZERO FILL) RIGHT SHIFT (>>>) 148
BINARY NUMBERS 148
CONVERTING DECIMAL TO BINARY 149
CONVERTING BINARY TO DECIMAL 149
REGULAR EXPRESSIONS 150
REGULAR EXPRESSION MODIFIERS 150
7
REGULAR EXPRESSION PATTERNS 150
USING STRING METHODS 152
USING THE REGEXP OBJECT 152
REGEXP OBJECT METHODS 153
REGEXP OBJECT PROPERTIES 153
ERRORS 154
THE JAVASCRIPT STATEMENTS TRY AND CATCH COME IN PAIRS. 154
OPTIONAL CATCH BINDING → ES10 154
JAVASCRIPT THROWS ERRORS 154
THE FINALLY STATEMENT 155
THE ERROR OBJECT 155
ERROR OBJECT PROPERTIES 155
ERROR NAME VALUES 156
USE STRICT → ES5 157
THE "USE STRICT" DIRECTIVE 157
DECLARING STRICT MODE 157
THE "USE STRICT"; SYNTAX 157
WHY STRICT MODE? 157
NOT ALLOWED IN STRICT MODE 157
FUTURE PROOF! 158
CLASSES → ES6 159
CLASS DEFINITION 159
METHODS 159
STATIC METHODS 159
PRIVATE CLASS VARIABLES → ES11 160
INHERITANCE 160
GETTERS AND SETTERS 161
KEY POINTS TO REMEMBER ABOUT CLASSES 163
MODULES → ES6 164
MODULE BASICS 164
EXPORT MODULES 164
IMPORT MODULES 165
MODULES PATH REFERENCES 166
AGGREGATING MODULES 166
WHAT DOES IMPORT ACTUALLY DO? 167
JS USE STATIC MODULE SYSTEM 168
HOW TO USE DYNAMIC MODULE SYSTEM 168
DYNAMIC IMPORT → ES10 169
RESOURCES: 169
1- MODULES 169
JAVASCRIPT ASYNC 170
1. CALLBACKS 170
2. ASYNCHRONOUS JAVASCRIPT 170
3. PROMISES → ES6 171
4. JAVASCRIPT ASYNC/AWAIT → ES8 178
PROXY → ES6 179
PROXY HANDLERS 179
STATIC METHODS 181
WEB GEOLOCATION API 182
EVENT LOOP: MICROTASKS AND MACROTASKS 183
8
EVENT LOOP 183
TASK 183
HOW JS ENGINE HANDLE TASKS: 184
MORE ABOUT MICROTASKS 186
MICROTASKS FOR USE CASES 186
JAVASCRIPT DEBUGGING 188
CODE DEBUGGING 188
JAVASCRIPT DEBUGGERS 188
JAVASCRIPT STYLE GUIDE & CODING CONVENTIONS 189
JAVASCRIPT CODING CONVENTIONS 189
NAMING CONVENTIONS 190
ACCESSING HTML ELEMENTS 191
FILE EXTENSIONS 191
USE LOWER CASE FILE NAMES 191
JAVASCRIPT BEST PRACTICES 193
AVOID GLOBAL VARIABLES 193
ALWAYS DECLARE LOCAL VARIABLES 193
DECLARATIONS ON TOP 193
INITIALIZE VARIABLES 193
NEVER DECLARE NUMBER, STRING OR BOOLEAN OBJECTS 193
DON'T USE NEW OBJECT() 193
BEWARE OF AUTOMATIC TYPE CONVERSIONS 194
USE === COMPARISON 194
USE PARAMETER DEFAULTS → ES6 194
END YOUR SWITCHES WITH DEFAULTS 194
AVOID USING EVAL() 194
JAVASCRIPT COMMON MISTAKES 195
ACCIDENTALLY USING THE ASSIGNMENT OPERATOR 195
MISUNDERSTANDING FLOATS 195
BREAKING A JAVASCRIPT STRING → ES5 195
MISPLACING SEMICOLON 195
BREAKING A RETURN STATEMENT 195
ACCESSING ARRAYS WITH NAMED INDEXES 196
ENDING DEFINITIONS WITH A COMMA → ES5 196
UNDEFINED IS NOT NULL 196
JAVASCRIPT PERFORMANCE (SPEED UP YOUR CODE) 198
REDUCE ACTIVITY IN LOOPS 198
REDUCE DOM ACCESS 198
REDUCE DOM SIZE 198
AVOID UNNECESSARY VARIABLES 198
DELAY JAVASCRIPT LOADING 198
JAVASCRIPT FORMS 200
JAVASCRIPT FORM VALIDATION 200
DATA VALIDATION 200
HTML CONSTRAINT VALIDATION 200
HTML DOM 203
WHAT IS THE DOM? 203
WHAT IS THE HTML DOM? 204
HTML DOM METHODS 205
9
THE DOM PROGRAMMING INTERFACE 205
HTML DOM DOCUMENT 206
THE HTML DOM DOCUMENT OBJECT 206
FINDING HTML OBJECTS 206
HTML DOM COLLECTIONS 208
THE HTMLCOLLECTION OBJECT 208
HTML HTMLCOLLECTION LENGTH 208
METHODS 208
HTML DOM NAVIGATION 210
DOM NODES 210
NODE RELATIONSHIPS 210
NAVIGATING BETWEEN NODES 211
CHILD NODES AND NODE VALUES 212
INNERHTML 212
DOM ROOT NODES 212
THE NODENAME PROPERTY 213
THE NODEVALUE PROPERTY 213
THE NODETYPE PROPERTY 214
HTML DOM NODE LISTS 215
THE HTML DOM NODELIST OBJECT 215
HTML DOM NODE LIST LENGTH 215
HTML DOM NODE LIST METHODS 215
THE DIFFERENCE BETWEEN AN HTMLCOLLECTION AND A NODELIST? 216
HTML DOM ELEMENTS (NODES) 218
CREATING NEW HTML ELEMENTS (NODES) 218
CREATING NEW HTML ELEMENTS - INSERTBEFORE() 219
REMOVING EXISTING HTML ELEMENTS 219
REMOVING A CHILD NODE 220
REPLACING HTML ELEMENTS 221
HTML DOM ELEMENTS 223
FINDING HTML ELEMENTS 223
HTML DOM - CHANGING HTML 226
CHANGING THE HTML OUTPUT STREAM 226
CHANGING HTML CONTENT 226
CHANGING THE VALUE OF AN ATTRIBUTE 227
CHANGING HTML STYLE – CHANGING CSS 227
HTML DOM STYLE OBJECT REFERENCE. 228
HTML DOM ANIMATION 229
A BASIC WEB PAGE 229
CREATE AN ANIMATION CONTAINER 229
STYLE THE ELEMENTS 229
ANIMATION CODE 230
CREATE THE ANIMATION USING JAVASCRIPT 230
HTML DOM EVENTS 232
REACTING TO EVENTS 232
HTML EVENT ATTRIBUTES 233
ASSIGN EVENTS USING THE HTML DOM 233
THE ONLOAD AND ONUNLOAD EVENTS 233
10
THE ONCHANGE EVENT 234
THE ONMOUSEOVER AND ONMOUSEOUT EVENTS 234
THE ONMOUSEDOWN, ONMOUSEUP AND ONCLICK EVENTS 235
MORE EXAMPLES 235
HTML DOM EVENT OBJECT REFERENCE. 236
HTML DOM EVENTLISTENER 237
THE ADDEVENTLISTENER() METHOD 237
SYNTAX 237
ADD AN EVENT HANDLER TO AN ELEMENT 237
ADD MANY EVENT HANDLERS TO THE SAME ELEMENT 238
ADD AN EVENT HANDLER TO THE WINDOW OBJECT 238
PASSING PARAMETERS 238
EVENT BUBBLING OR EVENT CAPTURING? 238
THE REMOVEEVENTLISTENER() METHOD 239
BROWSER SUPPORT 239
PREVENTDEFAULT EVENT METHOD 240
STOPPROPAGATION EVENT METHOD 240
STOPIMMEDIATEPROPAGATION EVENT METHOD 240
HTML DOM EVENT OBJECT REFERENCE. 241
BROWSER BOM 242
THE BROWSER OBJECT MODEL (BOM) 242
THE WINDOW OBJECT 242
WINDOW SIZE 242
OTHER WINDOW METHODS 242
WINDOW SCREEN 243
WINDOW SCREEN PROPERTIES 243
WINDOW LOCATION 244
WINDOW LOCATION PROPERTIES & METHODS 244
WINDOW HISTORY 245
WINDOW HISTORY METHODS 245
WINDOW NAVIGATOR 246
WINDOW NAVIGATOR PROPERTIES AND METHODS 246
WARNING !!! 246
POPUP BOXES 248
1. ALERT BOX 248
2. CONFIRM BOX 248
3. PROMPT BOX 248
TIMING EVENTS 248
1. THE SETTIMEOUT() METHOD 250
.2THE SETINTERVAL() METHOD 250
MORE EXAMPLES 250
COOKIES 252
WHAT ARE COOKIES? 252
CREATE A COOKIE WITH JAVASCRIPT 252
READ A COOKIE WITH JAVASCRIPT 252
CHANGE A COOKIE WITH JAVASCRIPT 253
DELETE A COOKIE WITH JAVASCRIPT 253
THE COOKIE STRING 253
11
JAVASCRIPT COOKIE EXAMPLE 253
WINDOW LOCALSTORAGE PROPERTY 256
WINDOW SESSIONSTORAGE PROPERTY 257
DIFFERENCES BETWEEN SESSIONSTORAGE, LOCALSTORAGE AND COOKIES 258
CONSOLE 259
• CONSOLE.ASSERT() 259
• CONSOLE.CLEAR() 259
• CONSOLE.COUNT() 259
• CONSOLE.COUNTRESET() 260
• CONSOLE.DEBUG() 260
• CONSOLE.DIR() 260
• CONSOLE.DIRXML() 260
• CONSOLE.ERROR() 261
• CONSOLE.GROUP() 261
• CONSOLE.GROUPCOLLAPSED() 262
• CONSOLE.INFO() 262
• CONSOLE.LOG() 262
• DIFFERENCE BETWEEN LOG() AND DIR() 262
• LOGGING OBJECTS 263
• CONSOLE.TABLE() 263
• CONSOLE.TIME() 265
• CONSOLE.TIMEEND() 265
• CONSOLE.TIMESTAMP() – NOT STANDARDIZED 265
• CONSOLE.TRACE() 265
• CONSOLE.WARN() 266
WHAT IS THE DIFFERENCE BETWEEN VIEWSTATE AND SESSIONSTATE? 267
12
13
Basics Information Before you Start
• Ascending ( )تصاعديmeans smallest to largest, 0 to 9, and/or A to Z.
• Descending ( )تنازليmeans largest to smallest, 9 to 0, and/or Z to A.
• A code block is a block of code between { and }.
• Lexical Scope: Static scope. The word lexical refers to the fact that
lexical scoping uses the location where a variable is declared within
the source code to determine where that variable is available
• Context Scope: Dynamic scope.
1
JavaScript
- JavaScript is an object-based scripting language which is lightweight
and cross-platform.
- It is used to create client-side dynamic pages. The programs in
JavaScript language are called scripts. The scripts are written in HTML
pages and executed automatically as the page loads. It is provided
and executed as plain text and does not need special preparation or
compilation to run.
Namespacing in JavaScript
- namespace is a unique name used for grouping the desired functions,
objects and properties. This improves modularity in the coding and
enables code reuse.
2
JavaScript Versions
- ECMAScript is the official name of the language. From 2015
ECMAScript is named by year (ECMAScript 2015).
- ECMAScript is often abbreviated to ES.
ECMAScript Editions
3
Reflect API
Tail Calls
4
ECMAScript 2009 (ES5)
- ECMAScript 5 is also known as ES5 and ECMAScript 2009.
- ECMAScript 2009(ES5) introduced the following new features:
• The "use strict" Directive
• String.trim()
• Array methods
o Array.isArray()
o Array.forEach()
o Array.map()
o Array.filter()
o Array.reduce() & Array.reduceRight()
o Array.every()
o Array.some()
o Array.indexOf()
o Array.lastIndexOf()
• JSON.parse()
• JSON.stringify()
• Date Methods
o Date.now()
o Date.toISOString()
• Property Getters and Setters.
• Object Property Methods.
• Function.prototype.bind()
Syntactical Changes
• Property access [ ] on strings.
• Trailing commas in array and object literals.
• Multiline string literals.
"foo \
bar"
• Reserved words as property names.
JSON.parse()
- A common use of JSON is to receive data from a web server, used to
convert the text into a JavaScript object.
JSON.stringify()
- A common use of JSON is to send data to a web server. When
sending data to a web server, the data has to be a string.
5
6
ECMAScript 2015 (ES6)
- ECMAScript 6 is also known as ES6 and ECMAScript 2015. Some
people call it JavaScript 6.
- ECMAScript 2015(ES6) introduced the following new features:
• Arrow Functions
• A new this scope
• Symbol Type
• Iterators
• Promises
• Generators
• let & const
• Classes
o Constructor
o Super
o Getters and setters
• Modules
o Importing modules
o Exporting modules
• Template Literals
• Default parameters
• The spread operator
• Enhanced Object Literals
o Simpler syntax to include variables
o Prototype
o super()
o Dynamic properties
• For-of loop
• Map & Set
• New String methods
• New Object methods
• Number Safety Checking Methods
• Number Type Checking Methods
• Array Elements Finding
• Destructuration Assignment
o Array Matching
o Object Matching
o Object Matching, Deep Matching
o Object And Array Matching, Default Values
o Parameter Context Matching
7
ECMAScript 2016 (ES7)
- ECMAScript 2016(ES7) introduced only two new features:
o Array.prototype.includes().
o Exponentiation operator.
8
ECMAScript 2017 (ES8)
- At the TC39 meeting in January 2017, the last feature of ECMAScript
2017, “Shared memory and atomics” .
- Major new features:
o Async Functions.
o Shared memory and atomics.
- Minor new features:
o Object.values/Object.entries.
o Object.getOwnPropertyDescriptors().
o String padding.
o Trailing commas in function parameter lists and calls.
9
ECMAScript 2018 (ES9)
- Major new features:
o Asynchronous Iteration.
o Rest/Spread Properties.
- New regular expression features:
o RegExp named capture groups.
o RegExp Unicode Property Escapes.
o RegExp Lookbehind Assertions.
o s_(dotAll) flag for regular expressions.
- Other new features:
o Promise.prototype.finally().
o Template Literal Revision.
10
ECMAScript 2019 (ES10)
- ES10 is the version of ECMAScript corresponding to the year 2019.
This version does not include as many new features as those that
appeared in ES6 (2015).
- The new JavaScript features in ES2019 are:
o Array.flat(), Array.flatMap().
o Object.fromEntries().
o String.trimStart(), String.trimEnd().
o Symbol Description.
o try/catch. Optional binding.
o JSON ⊂ ECMAScript.
o well-formed JSON.stringify.
o Stable Array.prototype.sort().
o New Function.toString()
o BigInt primitive type → Not Stable, will be in ES11.
o Dynamic import → Not Stable, will be in ES11.
o Standardized globalThis object.
11
ECMAScript 2020 (ES11)
- We’re going to review some of the latest features coming with
ES2020.
- Some of them are:
o Private Class Variables
o Promise.allSettled().
o String.prototype.matchAll
o Optional Chaining Operator
o Nullish Coalescing Operator
o Dynamic import
o BigInt primitive type
//ES11
let consumption = car?.engine?.consumption //No error and consumption is undefined
12
- The new operator ?? only considered undefined and null, as falsey
values. Note that, different from the case above, the values of 0,
NaN, false are persisted even though a non-falsey value.
13
JavaScript Syntax
JavaScript Values
- Fixed values are called literals. Variable values are called variables.
Literals Variables
Numbers var x = 5;
Strings
JavaScript 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.
o The statements are executed, one by one, in the same order as
they are written.
o Semicolons separate JavaScript statements, semicolon is not
required, but highly recommended.
o JavaScript ignores multiple spaces, =‘value’ or = ‘value’
o One place you will find statements grouped together in code
blocks, inside curly brackets {...}, is in JavaScript functions.
JavaScript Expressions
- An expression is a combination of values, variables, and operators,
which computes to a value “an evaluation”.
JavaScript Identifiers
- All JavaScript variables must be identified with unique names.
- Can be short or descriptive names.
- the first character must be a letter, or an underscore (_), or a dollar
sign ($). Subsequent characters may be letters, digits, underscores,
or dollar signs.
- Numbers are not allowed as the first character, so JS easily
distinguish identifiers from numbers.
14
JavaScript and Camel Case
- ways of joining multiple words:
Underscore first_name
JavaScript Comments
1. Single line comments start with // → most common
2. Multi-line comments start with /* and end with */ → formal
documentation.
- Using comments to prevent execution of code.
15
JavaScript Global
- The JavaScript global properties and functions can be used with all
the built-in JavaScript objects.
Property Description
Function Description
16
unescape() Deprecated in version
1.5. Use decodeURI() or decodeURIComponent(
) instead
Functions or Methods?
- It makes sense to call the list above global functions rather
than global methods because the functions are called globally
and not any objects.
- Anyway, you can also call these functions methods, since they are
methods of the global object where they run. In a web browser,
the global object is the browser window. Then isNaN() is actually a
window method: window.isNaN().
17
Uniform Resource Identifier (URI)
- A URI is a sequence of characters that identifies a logical or
physical resource. According to the specifications, resources do not
have to be accessible on the Internet. Examples of resources
include electronic documents, elevator door sensors.
- There are two types of URIs”:
1. Uniform Resource Locator (URL) – this type of URI begins by
stating which protocol should be used to locate and access the
physical or logical resource on a network. If the resource is a
web page, for example, the URI will begin with the protocol
HTTP. If the resource is a file, the URI will begin with the
protocol FTP or if the resource is an email address, the URI will
begin with the protocol mailto. It is important to remember that
URLs are not persistent. This means that if the resource’s
location changes, the URL also needs to change to point to the
resource’s new location.
2. Uniform Resource Name (URN) – this type of URI does not
state which protocol should be used to locate and access the
resource; it simply labels the resource with a persistent,
location-independent unique identifier. A URN will identify the
resource throughout its lifecycle and will never change. Each
URN has three components: the label “urn,” a colon and a
character string that serves as a unique identifier.
18
JavaScript Scope
- Scope determines the accessibility (visibility) of variables.
- In general terms, the scope will let us know at a given part of
code, what are the variables and functions that we can or cannot
access.
- In JavaScript there are two types of scope:
1. Local or Function scope.
2. Global scope.
3. Block scope
3. Block Scope
• It is related to the variables declared using let and const.
Variables declared with var do not have block scope.
• Block scope tells us that any variable declared inside a block { },
can be accessed only inside that block and cannot be accessed
outside of it.
Scope Chain
- JavaScript engine also uses Scope to find variables.
- JavaScript engine tries to find the variable in local scope, if not
exist, it tries to check for the variable in the outer scope. If the
variable does not exist in the outer scope, it tries to find the variable
in the global scope.
19
- If the variable is not found in the global space as well, reference error
is thrown.
JavaScript Variables
- In JavaScript, objects and functions are also variables.
Automatically Global
- If you assign a value to a variable that has not been declared, it will
automatically become a GLOBAL variable.
20
Declaring (Creating) Variables
- Variables are containers for storing data values.
- After the declaration, the variable has no value “undefined”.
- It's a good programming practice to declare all variables at the
beginning of a script.
1. JavaScript Var
o You can declare many variables in one statement, start the
statement with var and separate the variables by comma or
span multiple lines.
o If you re-declare a JavaScript variable, it will not lose its
value.
{
var x = 2;
}
// x CAN be used here
{
let x = 2;
}
// x can NOT be used here
21
Redeclaring Variables
- Redeclaring a variable using the var keyword can impose problems.
Redeclaring a variable inside a block will also redeclare the variable
outside the block.
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
- Redeclaring a variable using the let keyword can solve this problem.
Redeclaring a variable inside a block will not redeclare the variable
outside the block.
var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
- the variable declared in the loop does not redeclare the variable
outside the loop.
Function Scope
- Variables declared with var and let are quite similar when declared
inside a function.
Global Scope
- Variables declared with var and let are quite similar when declared
outside a block. They will both have Global Scope.
22
- In HTML, the global scope is the window object. Global variables
defined with the var keyword belong to the window object.
- Global variables defined with the let keyword do not belong to the
window object.
Redeclaring
- Redeclaring a JavaScript variable with var is allowed anywhere in a
program.
- Redeclaring a var variable with let, in the same scope, or in the
same block, is not allowed, vice versa same thing too.
- Redeclaring a let variable with let, in the same scope, or in the
same block, is not allowed.
- Redeclaring a variable with let, in another scope, or in another block,
is allowed.
Hoisting
- Variables defined with let are not hoisted to the top and using it
before declaring it will throw ReferenceError.
Block Scope
- Declaring a variable with const is similar to let when it comes
to Block Scope.
23
- If we assign a primitive value to a constant, we cannot change the
primitive value.
- You can change the properties of a constant object, but you can’t
reassign a constant object.
// ERROR
car = {type:"BMW", model:"EX60", color:"red"};
Redeclaring
- Redeclaring or reassigning an existing var or let variable to const, in
the same scope, or in the same block, is not allowed.
var x = 2; // Allowed
const x = 2; // Not allowed
{
let x = 2; // Allowed
const x = 2; // Not allowed
}
{
const x = 2; // Allowed
const x = 3; // Not allowed
x = 3; // Not allowed
var x = 3; // Not allowed
24
let x = 3; // Not allowed
}
const x = 2; // Allowed
{
const x = 3; // Allowed
}
Hoisting
- Variables defined with const are not hoisted to the top. It cannot be
used before it is declared.
carName = "Volvo"; // You can NOT use carName here
const carName = "Volvo";
25
JavaScript Hoisting
- Hoisting is JavaScript's default behavior of moving
declarations to the top.
- Hoisting applies to variable & function declarations.
x = 5; // Assign 5 to x
elem = document.getElementById("demo");
elem.innerHTML = x; // Display x in the element
var x; // Declare x
var x = 5; // Initialize x
elem = document.getElementById("demo");
elem.innerHTML = x + " " + y; // Display x and y, result is “5 undefined”
var y = 7; // Initialize y
- Y will be undefined, this is because only the declaration (var y), not
the initialization (=7) is hoisted to the top.
Note - To avoid hoisting, you can run JavaScript in strict mode by using
“use strict” on top of the code.
26
JavaScript in strict mode does not allow variables to be used if they are not
declared.
Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
++ Increment
-- Decrement
Operator Precedence
- the order in which operations are performed.
- Multiplication (*) and division (/) have higher precedence than
addition (+) and subtraction (-).
- When using parentheses (), the operations inside the parentheses
are computed first
- When many operations have the same precedence, they are
computed from left to right. L → R
19 . Member person.name
19 [] Member person["name"]
19 () Function call myFunction()
19 new Create new Date()
27
17 ++ Postfix Increment i++
17 -- Postfix Decrement i--
28
16 ++ Prefix Increment ++i
16 -- Prefix Decrement --i
16 ! Logical not !(x==y)
16 typeof Type typeof x
15 ** Exponentiation (ES2016) 10 ** 2
14 * Multiplication 10 * 5
14 / Division 10 / 5
14 % Division Remainder 10 % 5
13 + Addition 10 + 5
13 - Subtraction 10 - 5
10 == Equal x == y
10 === Strict equal x === y
10 != Unequal x != y
10 !== Strict unequal x !== y
3 += Assignment x += y
3 /= Assignment x /= y
3 -= Assignment x -= y
3 *= Assignment x *= y
3 %= Assignment x %= y
29
3 <<= Assignment x <<= y
3 >>= Assignment x >>= y
3 >>>= Assignment x >>>= y
3 &= Assignment x &= y
3 ^= Assignment x ^= y
3 |= Assignment x |= y
30
Data Types
1. Primitive data type (immutable)
o string
o number
o BigInt → ES10
o boolean
o Symbol → ES6
o null → typeof “object”
o undefined→ typeof “undefined”
o Object
o function → typeof “function”
Object Types
o Object
o Date
o Array
o Map → ES6
o Set → ES6
o String
o Number
o Boolean
31
Note:
- An empty string has both a legal value and a type, still type of string.
- null value is used to represent no value or no object. It implies no
object or null string, no valid boolean value, no number and no array
object.
- undefined It’s a property of global object and means “no value”,
o Variable used in the code doesn't exist.
o Variable is not assigned to any value.
o Property doesn't exist.
32
Strings
- JavaScript strings are used for storing and manipulating text.
- A JavaScript string is zero or more characters written inside quotes.
- You can use quotes inside a string, as long as they don't match the
quotes surrounding the string.
Escape Character
- The solution to avoid this problem (using same quotes inside it), is to
use the backslash escape character.
\\ \ Backslash
Code Result
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator
33
- A safer way to break up a string, is to use string addition.
string
is awesome!`
34
String Methods and Properties
- In JavaScript, methods and properties are also available to primitive
values, because JavaScript treats primitive values as objects when
executing methods and properties.
- the length property returns the length of a string.
- JavaScript counts positions from zero.
2. lastIndexOf(searchValue, start)
- returns the index of the last occurrence of a specified text in a string.
- The search will start at the specified position, or at the end if no start
position is specified and end the search at the beginning of the array.
- If start < 0 → index 0. Which means the end of the search.
- If start > str.length → index str.length.
35
5. includes(searchValue, start) →ES7
- Determines whether a string contains the characters of a specified
string. Returns false or true.
- The start is optional, at which to begin searching. Defaults to 0.
6. matchAll(regExp) →ES11
- A method returns an iterator of all results matching a string against
the regular expression, including capturing groups.
- Syntax: str.matchAll(regExp)
Search vs indexOf ?
- The search(regExp) method can’t take a second start position
argument.
- The indexOf() method can’t take regular expressions.
36
- If a parameter is negative. It start to count from the end of string
with 0 and not include the start parameter, end parameter will be
included.
2. substring(start, end)
- it is similar to slice(), the difference is that substring() can’t
accept negative indexes. end not included too.
- If start is greater than end, it will swap them.
3. substr(start, length)
- it is similar to slice(), the difference is that the second parameter
specifies the length of the extracted part.
- If start is negative, it’s not included, the position counts from the
end of the string to the end with the length required.
- length is optional.
37
Converting to Upper and Lower Case
- A string is converted to upper case with toUpperCase().
- A string is converted to lower case with toLowerCase().
- It is strongly recommended that the assignment operators (+, +=) are used
instead of the concat() method.
All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only
replaced.
38
1. charAt(position)
- returns the character at a specified index (position) in a string.
- If not found return an empty string.
2. charCodeAt(position)
- returns the unicode of the character at a specified index in a string, it
returns a UTF-16 code (an integer between 0 and 65535)
- If the position is out of bounds, the charCodeAt() method will return
a special not-a-number value printed as NaN.
'Ho'.repeat(3) //HoHoHo
39
txt.split(""); // Split in characters
40
Numbers
- JavaScript has only one type of number. Numbers can be written
with or without decimals.
- Extra-large or extra small numbers can be written with scientific
(exponent) notation:
var x = 123e5; // 12300000
var y = 123e-5; // 0.00123
Precision
- Integers (numbers without a period or exponent notation) are
accurate up to 15 digits.
- The maximum number of decimals is 17, but floating point arithmetic
is not always 100% accurate.
Numeric Strings
- JavaScript strings can have numeric content. All arithmetic operators
treat string as numeric except (+).
var x = "100";
var y = "10";
var z = x - y; // z will be 90
- But adding (+) a number and a string, JavaScript will treat the
number as a string, it’s called concatenation.
41
NaN - Not a Number
- It’s a JavaScript reserved word indicating that a number is not a legal
number. typeof NaN is a Number.
Infinity
- Infinity (or -Infinity) is the value JavaScript will return if you
calculate a number outside the largest possible number.
- Both are numbers.
- Division by (zero) also generates Infinity (or -Infinity).
Hexadecimal
- Hexadecimal is base 16. Decimal is base 10. Octal is base 8. Binary
is base 2.
- JavaScript interprets numeric constants as hexadecimal if they are
preceded by 0x.
var x = 0xFF; // x will be 255
42
Number Methods
- JavaScript treats primitive values as objects when executing methods
and properties.
- If use literals numbers leave a space before “.” to avoid considering it
as decimal point or one of the following ways:
1..toString()
1 .toString() // space before dot
(1).toString()
1.0.toString()
var x = 99.656;
x.toExponential(2); // returns 9.97e+1
x.toExponential(4); // returns 9.9656e+1
x.toExponential(6); // returns 9.965600e+1
x.toExponential(); // returns 9.9656e+1
43
- toPrecision(wholeNumLength) returns a string, with a number
written with a specified length.
var x = 9.656;
x.toPrecision(); // returns 9.656
x.toPrecision(1); // returns 1e+1 = 10
x.toPrecision(2); // returns 9.7
x.toPrecision(4); // returns 9.656
x.toPrecision(6); // returns 9.65600
1. Number(value) Method.
- convert JavaScript variables to numbers.
- It can also convert a date to a number, it will returned the
milliseconds of date since 1.1.1970
- Spaces and strings (a-z) not allowed, return NaN.
44
- base is Optional.
3. parseFloat(value) Method.
- parses a string and returns a whole number. Only the first number is
returned. It returns the number with decimal point if exist.
- Spaces and strings (a-z) are allowed.
Number Properties
Property Description
45
POSITIVE_INFINITY Represents infinity (returned on anyNum /
0)
var x = Number.EPSILON;
var x = Number.MIN_SAFE_INTEGER;
var x = Number.MAX_SAFE_INTEGER;
46
▪ Number.isNaN() does not convert the values to a Number
and will not return true for any value that is not of the type
Number.
47
Booleans
- A JavaScript Boolean represents one of two values: true or false.
- The Boolean value of an expression is the basis for all JavaScript
comparisons and conditions.
- Everything With a "Value" is True.
- Everything Without a "Value" is False. Such as 0, -0 , empty
string “”, undefined, null, false and NaN.
- Don’t use Boolean Objects, comparison not working with type (===)
and you can’t compare two boolean objects.
48
Implicit Type Coercion in JavaScript.
- Implicit type coercion in JavaScript is automatic conversion of
value from one data type to another. It takes place when the
operands of an expression are of different data types.
String coercion
- It takes place while using the ‘ + ‘ operator. When a number is added
to a string, the number type is always converted to the string type.
- Type coercion also takes place when using the ‘ - ‘ operator, but the
difference is that, a string is converted to a number and then
subtraction takes place.
Boolean Coercion
- It takes place when using logical operators, ternary operators, if
statements and loop checks.
Equality Coercion
- Equality coercion takes place when using ‘ == ‘ operator. As we have
stated before, the ‘ == ‘ operator compares values and not types.
- While the above statement is a simple way to explain == operator,
it’s not completely true, the reality is that while using the ‘==’
operator, coercion takes place. The ‘==’ operator, converts both the
operands to the same type and then compares them.
- Coercion does not take place when using the ‘===’ operator. Both
operands are not converted to the same type in the case of ‘===’
operator.
49
Symbol → ES6
- Unique and immutable data type to be used as an identifier for
object properties. Symbol can have an optional description.
- Same global symbol, but not locally.
- Symbols are guaranteed to be unique. Even if we create many
symbols with the same description, they are different values.
Create a symbol
- To create a new primitive symbol, you write Symbol(description)
with an optional string as its description.
let sym1 = Symbol();
let sym2 = Symbol('foo');
“Hidden” properties
- Symbols allow us to create “hidden” properties of an object, that
no other part of code can accidentally access or overwrite.
let user = { // belongs to another code
name: "John"
};
let id = Symbol("id");
50
user[id] = 1;
Symbols in a literal
- If we want to use a symbol in an object literal {...}, we need
square brackets around it.
let id = Symbol("id");
let user = {
name: "John",
[id]: 123 // not "id: 123"
};
Display symbol
- It’s not converted to string automatically, you should use
symbolVar.toString().
51
console.log(symbol.description); // description
Symbol Reference
52
Functions
- It is a block of code designed to perform a particular task.
- Why Functions? You can reuse code.
- A programming language is said to have First-class functions
(citizen) when functions in that language are treated like any other
variable. In JavaScript, a function can be passed as an argument to
other functions, can be returned by another function and can be
assigned as a value to a variable.
53
- Accessing a function without () will return the function definition
instead of the function result which done by ().
- Because of Hoisting function can be called before declaration.
o Parameter Rules
- JavaScript function definitions don’t specify data types for
parameters.
- JavaScript functions don’t perform type checking on the passed
arguments.
- JavaScript functions don’t check the number of arguments
received.
54
g({ name: "foo", val: 7 })
h({ name: "bar", val: 42 })
o Arguments
- It’s local variables are created when a function starts, and deleted
when the function is completed.
- The arguments.length property returns the number of arguments
received when the function was invoked.
- JavaScript arguments are passed by value: The function only gets to
know the values, not the argument's locations.
- Changes to arguments aren’t visible (reflected) outside the
function.
function toArray(arrayLikeObject) {
return Array.prototype.slice.call(arrayLikeObject);
}
o Rest Parameters
55
- Using the rest parameter syntax, we can create functions that can
take a variable number of arguments. Any number of arguments will
be converted into an array using the rest parameter.
- It also helps in extracting all or some parts of the arguments.
- Rest parameter can be used by applying three dots (...) before the
parameters, should be the last one of the arguments in the function.
function f (x, y, ...a) {
return (x + y) * a.length
}
f(1, 2, "hello", true, 7) === 9
o Spread Parameters
function f(x, y, z) {
return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6
function myFunction(a, b) {
return a * b;
}
myFunction(10, 2); // Will return 20
- The function above does not belong to any object. But in JavaScript
there is always a default global object.
- In HTML the default global object is the HTML page itself.
56
- In a browser the page object is the browser window. myFunction()
and window.myFunction() is the same function.
Self-Invoking Functions
- Function expressions can be made "self-invoking". It is invoked
(started) automatically, without being called.
- It is called IIFE (immediately invoked function expression,
pronounced “iffy”).
- Function expressions will execute automatically if the expression is
followed by ().
- This function is actually an anonymous self-invoking
function (function without name).
(function () {
var x = "Hello!!"; // I will invoke myself
})();
function myFunction(a, b) {
return arguments.length;
}
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y; //arrow function
57
- 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.
- If you have parameters, you pass them inside the parentheses. But if
you have only one parameter, you can skip the parentheses as well.
Function Return
- When JavaScript reaches a return statement, the function will stop
executing.
- Functions often compute a return value. The return value is
"returned" back to the "caller".
Function Call
- In JavaScript all functions are object methods (belong to Object or
Global Object).
- With call(thisArg, args...), an object can use a method belonging
to another object.
- A method allows an object to use the method (function) of another
object.
var person = {
58
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName: "Mary",
lastName: "Doe"
59
}
person.fullName.apply(person1); // Will return "Mary Doe"
60
// expected output: undefined
JavaScript Closures
- Closures is an ability of a function to remember the variables and
functions that are declared in its outer scope.
- Global variables can be made local with closures.
- A closure gives you access to an outer function’s scope from an
inner function.
- To use a closure, define a function inside another function and
expose it. To expose a function, return it or pass it to another
function.
- Let’s understand closures by example.
function randomFunc(){
var obj1 = { name: "Vivian", age: 45 };
return function(){
console.log(obj1.name + " is "+ "awesome"); // Has access to obj1 even when the
randomFunc function is executed
}
}
61
- The function randomFunc() gets executed and returns a function
when we assign it to a variable:
var initialiseClosure = randomFunc();
Currying in JavaScript
62
- Currying is an advanced technique to transform a function of
arguments n, to n functions of one or less arguments.
- For Example, if we have a function f(a, b) , then the function after
currying, will be transformed to f(a)(b).
- By using the currying technique, we do not change the
functionality of a function, we just change the way it is invoked.
- Currying doesn’t call a function. It just transforms it.
function multiply(a, b){
return a*b;
}
function currying(fn){
return function(a){
return function(b){
return fn(a, b);
}
}
}
- It’s useful if you want a fixed arguments, and remaining one will
be provided as needed. In other words “partially applied function”
or “partial” for short.
63
Void Operator
- The void operator evaluates the given expression and then
returns undefined.
Syntax
- void expression
Description
- This operator allows evaluating expressions that produce a value into
places where an expression that evaluates to undefined primitive
value, usually using "void(0)" (which is equivalent to "void 0"). In
these cases, the global variable undefined can be used.
- It should be noted that the precedence of the void operator should be
taken into account and that parentheses can help clarify the
resolution of the expression following the void operator:
void 2 == '2'; // (void 2) == '2', returns false
void (2 == '2'); // void (2 == '2'), returns undefined
<a href="javascript:void(0);">
Click here to do nothing
</a>
64
Iterators → ES6
Iterables
- A value is considered iterable if it has a method whose key is the
symbol Symbol.iterator that returns a so-called ( )ما يسمى بiterator.
- Some of the built-in data structure that use iterable are:
o Arrays
o Strings
o Maps
o Sets
o arguments → array-like
Iterators
- Object that knows how to access items from a collection one at a
time, while keeping track of its current position within that sequence.
- An iterator is any object which implements the Iterator protocol by
having a next() method. Next method returns an object with two
properties:
▪ Value
The next value in the iteration sequence.
▪ Done
true if the last value in the sequence has already been
consumed, false, otherwise.
const customIterable = {
[Symbol.iterator]() {
let counter = 0;
return {
next() {
65
if (counter < 5) {
counter++;
return { done: false, value: counter };
} else {
return { done: true, value: undefined };
}
}
}
}
}
const iterable = {
[Symbol.iterator]() {
return this;
},
next() {
if (index < args.length) {
return { value: args[index++] };
} else {
return { done: true };
}
66
},
};
- Even if the original iterable and the iterator are not the same object,
it is still occasionally useful if an iterator has the following method
(which also makes it an iterable):
[Symbol.iterator]() {
return this;
}
var foo = {
[Symbol.iterator]: () => ({
items: ['p', 'o', 'n', 'y', 'f', 'o', 'o'],
next: function next () {
return {
done: this.items.length === 0,
value: this.items.shift()
}
}
})
}
Reference To Iterators
67
Generators → ES6
- In normal Function the only way to exist it, is by returning from it
or throwing an error. If you call the function again, it will begin the
execution from the top again.
- In contrast, a generator is a function that can stop midway and
then continue from where it stopped.
- Inside the function body, we don’t have a return. Instead, we have
another keyword yield. It’s an operator with a generator yields
“returns” the value specified after it and then pause itself.
- In JavaScript, a generator is a function which returns an object, you
can call next() on it. Every invocation of it will return an object:
{
value: Any,
done: true|false
}
- The value property will contain the value. The done property is
either true or false.
- We can also return from a generator. However, return sets
the done property to true, after that the generator cannot generate
any more values.
- Remember that every function implicitly returns undefined if no
return statement is provided when it’s finished.
Generator functions
- Generator function identified by the function* keyword. You can
have a space between * and function.
function * generatorFunction() {
console.log('This will be executed first.');
yield 'Hello, ';
console.log('I will be printed after the pause');
yield 'World!';
}
const generatorObject = generatorFunction();
68
- Creating object from that function. the generator
function always returns a generator object. The generator object is
an iterator. So you can use it in for/of loops or other functions
accepting an iterable.
- we call the next() method on the generatorObject. With this call, the
generator begins executing.
console.log(generatorObject.next().value); // Hello,
- we call next() again. This time the generator wakes up and begin
executing from where it left.
console.log(generatorObject.next().value); // World!
- Or using for/of
for(let value of generatorObject) {
console.log(value); // Hello, then World!
}
- For/of iteration ignores the last value, when done: true. This is how
for loops works.
Generator composition
- How would you call generator from another generator function?
- ECMAScript 6 has the operator yield* for making recursive generator
calls.
function* bar() {
yield 'x';
yield* foo(); // another generator function
yield 'y';
}
69
“yield” is a two-way street
- Until this moment, generators were similar to iterable objects, with a
special syntax to generate values. But in fact they are much more
powerful and flexible.
- That’s because yield is a two-way street: it not only returns the
result to the outside, but also can pass the value inside the
generator.
- To do so, we should call generator.next(arg), with an argument.
That argument becomes the result of yield.
function* gen() {
// Pass a question to the outer code and wait for an answer
let result = yield "2 + 2 = ?"; // (*)
alert(result);
}
let question = generator.next().value; // <-- yield returns the value // "2 + 2 = ?"
yield a + b + c;
70
console.log('Hello' + (yield)); // OK
console.log('Hello' + (yield 123)); // OK
- You also don’t need parens if you use yield on the right-hand side of
an assignment.
let range = {
from: 1,
to: 5,
*[Symbol.iterator]() {
// a shorthand for [Symbol.iterator]: function*()
for(let value = this.from; value <= this.to; value++) {
yield value;
}
}
};
Uses of Generators
- There are many awesome use cases of generators.
1. Implementing Iterables
o When you implement an iterator, you have to manually
make an iterator object with a next() method. Also, you
have to manually save the state. Using generator will avoid
these issues.
71
3. Infinite Data Streams
o It’s possible to create generators that never end.
function * naturalNumbers() {
let num = 1;
while (true) {
yield num;
num = num + 1
}
}
const numbers = naturalNumbers();
console.log(numbers.next().value) // 1
console.log(numbers.next().value) // 2
4. Generators as observers
o Generators can also receive values using
the next(val) function and it receives those values via
yield. Then the generator is called an observer since it
wakes up when it receives new values.
function* dataConsumer() {
console.log('Started');
console.log(`1. ${yield}`); // (A)
console.log(`2. ${yield}`);
return 'result';
}
const genObj = dataConsumer();
genObj.next();
// Started
// {value: undefined, done: false}
genObj.next('a');
// 1. a
//{value: undefined, done: false}
genObj.next('b');
// 2. b
//{value: "result", done: true}
72
o Unfortunately, next() is asymmetric, but that can’t be
helped: It always sends a value to the currently
suspended yield, but returns the operand of the
following yield.
o When using a generator as an observer, it is important to
note that the only purpose of the first invocation of next()
is to start the observer. It is only ready for input afterwards,
because this first invocation advances execution to the
first yield. Therefore, any input you send via the
first next() is ignored.
function* gen() {
// (A)
while (true) {
const input = yield; // (B)
console.log(input);
}
}
const obj = gen();
obj.next('a'); // NO OUTPUT
obj.next('b'); // b
Advantages of Generators
1. Lazy Evaluation
o Lazy Evaluation is an evaluation model which delays the
evaluation of an expression until its value is needed. That is,
if we don’t need the value, it won’t exist. It is calculated as
we demand it. Look Infinite Data Streams Example above.
2. Memory Efficient
o A direct consequence of Lazy Evaluation is that generators
are memory efficient. We generate only the values that are
needed. With normal functions, we needed to pre-generate
all the values and keep them around in case we use them
later.
Disadvantages of Generators
1. Generator objects are one-time access only.
73
o Once you’ve exhausted all the values, you can’t iterate over
it again. To generate the values again, you need to make a
new generator object.
74
Objects
- In JavaScript, objects are king. If you understand objects, you
understand JavaScript.
- Objects are variables, but can contain many values (unordered
properties).
- The values are written as name:value pairs (name and value
separated by a colon).
- JavaScript objects are containers for named values called properties
or methods.
- In JavaScript, almost "everything" is an object.
- Booleans, Numbers, Strings can be objects.
- Dates, Math, Regular expressions, Arrays, Functions, Objects, Maps,
Sets are always objects.
- Comparing two JavaScript objects will always return false.
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
75
3. Object.create(anyObject) → ES5
- Creates a new object, using an existing object as the
prototype of the newly created object. Return new object.
- Use it when you want to choose prototype object to
inherit to, without the need to define constructor. It’s a
way of “inheritance”.
- Both x and person are the same object. Any change to one of them
will affect the other one.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}
var x = person;
x.age = 10; // This will change both x.age and person.age
Object Properties
- The name:values pairs in JavaScript objects are called properties.
- Object properties can be primitive values, other objects and
functions.
- Properties can usually be changed, added and deleted, but some are
read only.
- You can access object properties in the following ways:
1. objectName.propertyName
2. objectName["propertyName"]
3. objectName[expression] // x = "age"; person[x]
person.nationality = "English";
76
- The delete keyword deletes a property (own key) from an object, the
delete operator doesn’t delete prototype property.
- It deletes both the value of the property and the property itself. After
deletion, the property cannot be used before it is added back again.
- It is designed to be used on object properties. It has NO effect on
variables or functions.
- It should not be used on predefined JavaScript object properties,
it can crash your application.
Property Attributes
- Each property in the object have a name. In addition they also have a
value and other attributes are: enumerable, configurable, and
writable.
- All attributes can be read, but only the value attribute can be
changed.
- ECMAScript 5 has methods for both getting and setting all property
attributes.
writable : true
- true the value associated with the property may be changed with
an assignment operator.
Defaults to true.
enumerable: true
configurable: true
- true this property descriptor may be changed and the property may be
deleted from the corresponding object.
Defaults to false.
77
Prototype Properties
- JavaScript objects inherit the properties of their prototype.
- The delete keyword does not actually delete inherited properties, but
if you delete a prototype property, it will affect all objects inherited
from the prototype.
//ES5
var x = 0, y = 0;
obj = { x: x, y: y };
//EC6
var x = 0, y = 0
obj = { x, y }
//ES5
var obj = {
foo: "bar"
};
obj[ "baz" + quux() ] = 42;
//EC6
let obj = {
foo: "bar",
[ "baz" + quux() ]: 42
}
78
obj = {
foo (a, b) {
…
},
bar (x, y) {
…
},
*quux (x, y) {
…
}
}
//ES5
obj = {
foo: function (a, b) {
…
},
bar: function (x, y) {
…
},
// quux: no equivalent in ES5
…
};
79
me: "there"
},
printAll(){
console.log('work like es6');
}
}
// ES5
var name = person.fullName;
var m = person.details.me;
var pr = person.printAll;
//ES6
var {fullName: name, details: {me: m}, printAll: pr} = person;
var obj = { a: 1 }
var { a, b = 2 } = obj
Object Methods
- Methods are actions that can be performed on objects.
- Methods are stored in properties as function definitions.
- You access an object method as following:
objectName.methodName()
- If you access the method property without (), it will return
the function definition.
The in operator
- The in operator checks whether a property exists in the object.
80
'newProperty' in jane
• Avoid String, Number and Boolean as objects. They complicate your code
and slow down execution speed. Defined by a “new” keyword.
81
Display Objects
- Displaying a JavaScript object in HTML will output [object Object].
- Some common solutions to display JavaScript objects are:
1. Object Properties by name.
document.getElementById("demo").innerHTML =
person.name + "," + person.age + "," + person.city;
for (x in person) {
txt += person[x] + " ";
};
3. Object.values() → ES8
document.getElementById("demo").innerHTML = myArray;
var myArray = Object.values(person);
4. JSON.stringify()
82
Object and Internal Methods
- Almost everything JS programs do with objects is done using
properties, prototypes and functions. So when the ECMAScript
standard committee defined a set of 14 internal methods, the
common interface for all objects, it should come as no surprise that
they ended up focusing on these 3 fundamental things.
- The weird double brackets, [[ ]], emphasize that these
are internal methods, hidden from ordinary JS code. You can’t call,
delete or overwrite these like ordinary methods.
1. obj.[[Get]](key, receiver)
3. obj.[[HasProperty]](key)
4. obj.[[Enumerate]]()
- List obj’s enumerable properties. called when JS code does: for (key
in obj) ...
- This returns an iterator object and that’s how a for–in loop gets an
object’s property names.
5. obj.[[GetPrototypeOf]]()
6. functionObj.[[Call]](thisValue, arguments)
83
7. constructorObj.[[Construct]](arguments, newTarget)
• The full list can be found in tables 5 and 6 of the ES6 standard.
84
Object Constructors
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
this.name = function() {return this.firstName + " " + this.lastName;};
}
85
Object Prototypes
Prototype-based programming
- It is a style of object-oriented programming where classes are not
explicitly defined, but rather derived by adding properties and
methods to an instance of another class or less frequently, adding
them to an empty object.
- In simple words: this type of style allows the creation of
an object without first defining its class.
- All JavaScript objects inherit properties and methods from a
prototype.
- When it comes to inheritance, JavaScript only has one construct:
objects. Each object has a private property which holds a link to
another object called its prototype. That prototype object has a
prototype of its own and so on until an object is reached
with null as its prototype. By definition, null has no prototype and
acts as the final link in this prototype chain.
- Nearly all objects in JavaScript are instances of Object which sits
on the top of a prototype chain.
- A prototype is a blueprint of an object. Prototype allows us to
use properties and methods on an object even if the properties
and methods do not exist on the current object.
- Whenever the property or method is not found on the current
object, the JavaScript engine will always try to look in its
prototype and if it still does not exist, it looks inside the
prototype's prototype and so on to the end when prototype being
NULL.
- Note: We want to reiterate that the methods and properties
are not copied from one object to another in the prototype
chain. They are accessed by walking up the chain as described
above.
- Note: The prototype chain is traversed only while retrieving
properties. If properties are set or deleted directly on the object,
the prototype chain is not traversed.
- So Object.prototype.toString(), Object.prototype.valueOf(),
etc., are available to any object types that inherit
from Object.prototype, including new object instances created
from the Person() constructor.
- Object.is(), Object.keys() and other members not defined inside
the prototype bucket are not inherited by object instances or
object types that inherit from Object.prototype. They are
86
methods/properties available just on the Object() constructor
itself.
87
preserve instance safety, you need to make a copy of the state for
each object.
88
return Object.assign(this, {
set (name, value) {
attrs[name] = value;
this.emit('change', {
prop: name,
value: value
});
},
get (name) {
return attrs[name];
}
}, Events.prototype);
};
89
Object Methods
ES5 Object Methods
1. Object.defineProperty(object, property, {value : value})
o Adding or changing an object property.
// Define a getter
Object.defineProperty(person, "fullName", {
get : function () {return this.firstName + " " + this.lastName;}
});
2. Object.defineProperties(object, descriptors)
o Adding or changing many object properties.
Object.defineProperties(person, {
fullName: {
get: function(){
return this.firstName + " " + this.lastName;
},
enumerable: true,
configurable: true
},
"language":{
value: "AR",
enumerable: true,
writable: true,
configurable: true
}
})
3. Object.getOwnPropertyDescriptor(object, property)
o Returns Properties and show Meta data and value.
4. Object.getOwnPropertyNames(object)
o Returns all properties (enumerable or not) as an array
but not one added to prototype.
90
5. Object.keys(object)
o Returns enumerable properties as an array.
6. Object.getPrototypeOf(object)
o Returns the prototype.
7. Object.preventExtensions(object)
o Prevents new properties from ever being added to an
object, may properties still be deleted. You can still
change the values.
8. Object.isExtensible(object)
o Returns true if properties can be added to an object .
9. Object.seal(object)
o Preventing new properties from being added to it and
marking all existing properties as non-configurable.
Values of present properties can still be changed as
long as they are writable.
10. Object.isSealed(object)
o Returns true if object is sealed.
11. Object.freeze(object)
o A frozen object can no longer be changed; freezing an
object prevents new properties from being added to it,
existing properties from being removed, prevents
changing the enumerability, configurability or
writability of existing properties and prevents the
values of existing properties from being changed. In
addition, freezing an object also prevents its prototype
from being changed.
12. Object.isFrozen(object)
o Returns true if object is frozen.
91
o Copies all enumerable own properties from one or
more source objects to a target object. It returns target object
after changed.
2. Object.is(val1, val2)
o determines whether two values are the same value. Two values
are the same if one of the following holds:
▪ both undefined
▪ both null
▪ both true or both false
▪ both strings of the same length with the same characters
in the same order
▪ both the same object (means both object have same
reference)
▪ both numbers and
• both +0
• both -0
• both NaN
• or both non-zero and both not NaN and both have
the same value.
3. Object.setPrototypeOf(obj, prototype)
o It’s very slow, avoid using it.
2. Object.values(object)
o Method returns values for object properties.
92
3. Object.getOwnPropertyDescriptors(object)
o Returns all Properties and show Meta data and values.
first // 1
second // 2
others // { third: 3, fourth: 4, fifth: 5 }
Spread properties
o Allow to create a new object by combining the properties of the
object passed after the spread operator
const items = { first, second, ...others }
items //{ first: 1, second: 2, third: 3, fourth: 4, fifth: 5 }
Object.fromEntries(iterable) → ES10
- Transforms a list of [key, value] pairs into an object.
- An iterable such as Array or Map or other objects implementing
the iterable protocol. Return a new object.
93
this Keyword
- The JavaScript this keyword refers to the object it belongs to.
- It has different values depending on where it is used:
1. this alone, refers to the global object.
2. this in an event, refers to the element that received the event.
3. Methods like call(), apply() and bind() can refer this to any
object.
const call = {
caller: "mom",
says: function() {
console.log(`Hey, ${this.caller} just called.`);
}
};
call.says();
const call = {
caller: "mom",
says: () => {
console.log(`Hey, ${this.caller} just called.`);
}
};
call.says();
94
const call = {
caller: "mom",
says: function() {
console.log(`Hey, ${this.caller} just called.`);
}
};
let newCall = call.says;
newCall();
- Here, we assign a new variable to the says function inside the call
object And then we invoke the variable, which is a simple function
call.
- Notice where we invoke the function. Is it inside the call object?
No. We are invoking newCall() function globally, which in turn
makes the this keyword equal to the global object.
- since the global object does not have a caller property, you get
"undefined" as a result.
- By now, you might notice a key pattern:
Regular functions change their behaviors BASED ON the
object that is CALLING the function.
var box = {
color: 'green',
position: 1,
clickMe: function() {
document.querySelector('body').addEventListener('click', () => {
var str = 'This is box number ' + this.position + ' and it is ' + this.color;
alert(str);
});
}
}
- The amazing thing about arrow functions is that they share the
lexical this keyword of their surroundings. So, in our example
here it shares the this keyword with its outer function.
This this keyword for the outer function refers to the box object,
so this.position and this.color will have the correct values
of green and 1.
95
Function Type Strict Mode In Object this Reference to
// The global this was not standardized before ES1O. The solution was
var getGlobal = function ( ) {
if (typeof self !== 'undefined') { return self; }
if (typeof window !=='undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error( 'unable to locate global object' );
}
// ES10 added globalThis object which sould be used from now on to access global scope
on any platform
96
Arrays
- Array is a special variable which can hold more than one value at
a time (store multiple values in a single variable).
- In general, arrays in JavaScript are sparse – they can have holes
in them, because an array is simply a map from indices to values.
- Dense arrays, don’t have holes in them, JavaScript don’t use this
type.
Creating an Array
1. Using an array literal, A declaration can be multiple lines.
- For simplicity, readability and execution speed, use the first one.
var x = arrayVar;
97
Array Elements Can Be Objects
- you can have variables of different types in the same Array. You
can have objects in an Array. You can have functions in an Array.
You can have arrays in an Array.
Array Properties
- The length property of an array returns the length of an array
(the number of array elements).
- It is always one more than the highest array index.
- It provides an easy way to append a new element to the end of an
array.
array[array.length] = newValue;
var list = [ 1, 2, 3 ]
var [ a, , b ] = list
98
var params = [ "hello", true, 7 ]
var other = [ 1, 2, ...params ]//[ 1, 2, "hello", true, 7 ]
Associative Arrays
- Arrays with named indexes are called associative arrays (or
hashes).
- JavaScript does not support arrays with named indexes, so
always use numbered indexes.
WARNING !!
If you use named indexes, JavaScript will redefine the array to a standard
object. After that, some array methods and properties will
produce incorrect results.
1. isArray(arryVariable)→ ES5
- determines whether an object is an array. Return true or false.
- not supported in older browsers.
Array.isArray(fruits);
2. To solve this problem you can create your own isArray() function.
function isArray(x) {
99
return x.constructor.toString().indexOf("Array") > -1;
}
function isArray(myArray) {
return myArray.constructor === Array;
}
100
Array Methods
Converting Arrays to Strings
1. The JavaScript method toString() converts an array to a string of
(comma separated) array values.
2. The join(separator) method also joins all array elements into a
string without any separator, but in addition you can specify the
separator.
Automatic toString()
- JavaScript automatically converts an array to a comma separated
string when a primitive value is expected.
- This is always the case when you try to output an array.
document.getElementById("out").innerHTML = arrayVar;
1. Popping
- The pop() method removes the last element from an array, it
returns the value popped out “deleted”.
arrayVar.pop();
2. Pushing
- The push(val1, val2 ...) method adds a new element to an
array at the end, it returns the new array length.
arrayVar.push(newValue);
Shifting Elements
- The shift() method removes the first array element and "shifts"
all other elements to a lower index, it returns the string that was
shifted out “deleted”.
Unshifting Elements
101
- the unshift(newValue) method adds a new element to an array at
the beginning and "unshifts" older elements, it returns the new
array length.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon"); // Returns 5
delete arrayVar[index];
- Using delete may leave undefined holes in the array. Use pop() or
shift() instead.
Splicing an Array
- The splice(start, deleteCount, ele1, ele2 ...) method can be
used to add new items to an array, it returns an array with deleted
items if there is.
- With clever parameter setting, you can use it to remove elements
without leaving "holes" in the array.
- start
o If it’s > array.length, it will be set to the length of the array (at the
end).
o If it is negative, it will start from array.length – start.
o If array.length + start < 0, it will begin from index 0.
- deleteCount
o It’s Optional. If it is omitted or if its value >= array.length - start ,
then delete all elements from start to the end of the array.
o If it is 0 or negative, no elements are removed.
- The ele1, ele2 ... to add to the array, beginning from start. It’s
Optional.
- Returned value is an array containing the deleted elements or empty array if
no deleted elements.
102
var newArray = array1.concat(array2, array3 ...);
Slicing an Array
- The slice(start, end) method slices out a piece of an array into a
new array.
newArray = arrayVar.slice(2);
- start
o It is Optional. If it is undefined, it begins from index 0.
o It can be a negative index, indicating an offset from the end.
o If it is greater than the index range, an empty array is
returned.
- end
o It is Optional and extracts up to but not including.
o It can be a negative index, indicating an offset from the end.
o If it is omitted or greater than the array length, it will slice out
the rest of the array from start.
Reversing an Array
- The reverse() method reverses the elements in an array, it’s change
the same array.
- If you want array reversed alphabetically, first sort the array then
reverse it, but anyway it will reverse the array.
Sorting an Array
- The sort(compareFunction) method sorts an array alphabetically,
it’s change the same array.
- The default sort order is ascending. It’s converting the elements
into strings then comparing their sequences of UTF-16 code units
values.
arrayVar.sort();
103
- compareFunction is an optional argument which is a function that
compares two elements of the array.
Numeric Sort
- By default, the sort() function sorts values as strings.
- if numbers are sorted as strings, "25" > "100",
because "2" > "1".
- You can fix this by providing a compare function.
- When the sort() function compares two values, it sends the values
to the compare function, and sorts the values according to the
returned value.
- If the result is negative a is sorted before b.
- If the result is positive b is sorted before a.
- If the result is 0, no changes are done with the sort order of the two
values.
- This sort is ascending.
- Descending sort is done by changing compare function to be:
104
1. Array.reduce() can be used to find the maximum (minimum)
element in a numeric array, by comparing each value. (Reduce
Explained Later)
var arrayVar = [1,2,3];
var max = arr.reduce(function(a, b) {
return Math.max(a, b); // Math.min(a, b)
});
However, both spread (...) and apply will either fail or return the
wrong result if the array has too many elements, because they try to
pass the array elements as function parameters. The reduce solution
does not have this problem.
105
- The solution is to write a compare function to compare the property
values.
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
cars.sort(function(a, b){return a.year - b.year});
106
Array Iteration Methods
- Array iteration methods operate on every array item.
ArrayVar.forEach() → ES5
- The forEach(callbackFunction) method calls a function once for
each array element and changing the same array.
- Each callback function receive 3 parameters: value, index and the
array itself. index and array can be omitted if not used.
arrayVar. forEach(myFunction);
function myFunction(value, index, array)
{ //any code here }
ArrayVar.map() →ES5
- The map(callbackFunction) method creates a new array by
performing a function on each array element, does not change the
original array.
- It doesn’t execute the function for elements without values, but
returned array will have the hole elements.
- Each callback function receive 3 parameters: value, index and the
array itself. index and array can be omitted if not used.
ArrayVar.filter() → ES5
- The filter(callbackFunction) method creates a new array with
array elements that passes a test. So returned value should be true
or false.
107
ArrayVar.reduce() & ArrayVar.reduceRight() → ES5
- The reduce(callbackFunction, initialValue) method runs a
function on each array element to produce (reduce it to) a single
value, it works from L → R in the array.
- The reduceRight(callbackFunction, initialValue) same method,
but it works from R → L in the array.
- Both does not reduce the original array.
- initialValue is optional.
- It doesn’t execute the function for elements without values.
var sum = numbers1.reduce(myFunction);
function myFunction(total, value, index, array) {
return total + value;
}
ArrayVar.every() → ES5
- The every(callbackFunction) method check if all array values pass a
test and returns a single value. It stop when the test return false.
- If ALL members in the array pass the test it return true else it return
false.
ArrayVar.some() → ES5
- The some(callbackFunction) method tests whether at least
one element in the array passes the test return true else it return
false. It returns a single value.
108
- It doesn’t execute the function for elements without values.
ArrayVar.indexOf() → ES5
- the indexOf(searchFor, startIndex) method searches an array for
an element value and returns its position.
ArrayVar.lastIndexOf() → ES5
- Array.lastIndexOf(searchFor, startIndex) is the same
as Array.indexOf(), but returns the position of the last
occurrence of the specified element.
var a = arrayVar.lastIndexOf(value);
ArrayVar.entries () → ES6
- The entries() method returns an Array Iterator object with
key/value pairs.
ArrayVar.find() → ES6
109
- The find(callbackFunction) method returns the value of the first
array element that passes a test function. Otherwise, undefined is
returned.
var firstValue = arrayVar.find(myFunction);
ArrayVar.findIndex() → ES6
- The findIndex(callbackFunction) method returns the index of the
first array element that passes a test function. Otherwise, -1 is
returned.
- Each callback function receive 3 parameters: value , index and the
array itself. index and array can be omitted if not used.
- It is execute the function for elements without values.
- Supported in some browsers.
Array.from() → ES6
- The Array.from(object, mapFunction, thisValue) static method
creates a new, shallow-copied Array instance from an array-like,
iterable object or any object with a length property.
- let you create Arrays from:
1. array-like objects (objects with a length property and indexed
elements); or
2. iterable objects (objects such as Map and Set).
- mapFunction, thisValue are Optional.
Array.of() → ES6
- Array.of(el1, el2 ...) method creates a new Array instance from
a variable number of arguments, regardless of number or type of the
arguments.
110
- The difference between Array.of() and the Array constructor is in
the handling of integer arguments: Array.of(7) creates an array
with a single element, 7, whereas Array(7) creates an empty array
with a length property of 7.
Array.of(1); // [1]
Array.of(1, 2, 3); // [1, 2, 3]
Array.of(undefined); // [undefined]
Array.fill() → ES6
- Array.fill(value, start, end) method fills the specified elements
in an array with a static value.
- You can specify the position of where to start and end the filling. If
not specified, all elements will be filled.
- It overwrites the original array.
- Value Required. The value to fill the array with.
- start Optional. The index to start filling the array (default is 0).
- end Optional. The index to stop filling the array (default
is array.length).
ArrayVar.includes() → ES7
- The includes(searchFor, start) method determines whether an
array contains a specified element.
- This method returns true if the array contains the element,
and false if not.
- It is case sensitive.
- it can be applied to other kinds of objects (e.g. array-like objects)
- start
o is optional.
o If it is >= length of the array, false is returned. The array will
not be searched.
o If the computed index (start + arr.length) is <= -1, the
entire array will be searched.
ArrayVar.flat() → ES10
- link
111
ArrayVar.flatMap() → ES10
- link
112
Date Objects
- Date objects are static. The computer time is ticking, but date
objects are not.
1. new Date()
- new Date() creates a new date object with the current date and
time.
3. new Date(dateString)
- new Date(dateString) creates a new date object from a date
string.
113
4. new Date(milliseconds)
- new Date(milliseconds) creates a new date object as zero time
(1.1.1970) plus milliseconds.
Date Methods
- methods operate on a Date object.
- Displaying Dates:
o JavaScript will output the default dates format, when you
display a date object in HTML, it is automatically converted to a
string.
o The toUTCString() method converts a date to a UTC string (a
date display standard).
UTC : UTC (Universal Time Coordinated) is the same as GMT
(Greenwich Mean Time).
114
Date Formats
JavaScript Date Input
- There are generally 3 types of JavaScript date input formats:
Type Example
115
- Commas are ignored. Names are case insensitive.
Time Zones
- When setting a date, without specifying the time zone, JavaScript will
use the browser's time zone.
116
Get Date Methods
The now() Method → ES5
- Date.now() returns the number of milliseconds since zero date
(January 1. 1970 00:00:00 UTC), returns the same as getTime()
performed on a Date object.
d.getFullYear();
d.getMonth();
- You can use an array of names and return the month as a name.
d.getDate();
117
- The getMinutes() method returns the minutes of a date as a number
(0-59).
d.getMinutes();
d.getSeconds();
d.getMilliseconds();
d.getDay();
- You can use an array of names and return the weekday as a name.
- In JavaScript, the first day of the week (0) means "Sunday".
Method Description
118
Complete Date Reference.
119
Set Date Methods
- Set Date methods let you set date values (years, months, days,
hours, minutes, seconds, milliseconds) for a Date Object.
d.setMonth(11);
d.setDate(15);
- If days is negative, the date will be set counting backwards from the
last day of the previous month.
- If days was 0, the date will be set to the last day of the previous
month.
- Return milliseconds from 1.1.1970 to that date we set.
d.setHours(22);
120
- Return milliseconds from 1.1.1970 to that date we set.
- minutes, second, ms are optional parameters.
d.setMinutes(30);
d.setSeconds(30);
d.setMilliseconds(30);
Compare Dates
- It can be compared easily by using them and bitwise operators.
If you added more than limit in any function above, it will the change the
whole date accordingly.
121
Map Data-Structure → ES6
- Map is object holds key-value pairs and remembers the original
insertion order of the keys. Any value (both objects and primitive
values) may be used as either a key or a value.
- Maps are more useful over objects when you just need a simple look
up structure for data storing.
Map Creation
const m = new Map()
Map keys
- any value can be used as the key, even objects.
- If you try to get a non-existing key using get() out of a map, it will
return undefined.
122
m.get(-0) //test
m.delete('color')
m.clear()
123
Iterate over map key, value pairs
- The Map object offers the entries() method we can use to iterate on
all the values.
Convert to array
Convert the map keys into an array
const a = [...m.keys()]
WeakMap
- A WeakMap is a special kind of map.
- In a map object, items are never garbage collected. A WeakMap
instead, let’s all its items be freely garbage collected. Every key
of a WeakMap is an object. When the reference to this object is lost,
the value can be garbage collected.
- Here are the main differences:
o you cannot iterate over the keys or values (or key-values) of a
WeakMap.
o you can’t clear all items from a WeakMap.
o you can’t check its size.
124
Set Data-Structure → ES6
- Object lets you store unique values of any type, whether primitive
values or object references.
- Set objects are collections of values. You can iterate through the
elements of a set in insertion order. A value in the Set may only
occur once; it is unique in the Set's collection.
Initialize a Set
- A Set is initialized by calling the constructor.
s.add('one')
s.add('two')
s.delete('one')
125
Determine the number of items in a Set
- Use the size property.
s.size
s.clear()
- The entries() method returns an iterator, which you can use like
this.
const i = s.entries()
console.log(i.next())
for (const k of s) {
console.log(k)
}
126
const a = [...s.values()]
A WeakSet
- A WeakSet is a special kind of Set.
- In a Set, items are never garbage collected. A WeakSet instead, let’s
all its items be freely garbage collected. Every key of a WeakSet is
an object. When the reference to this object is lost, the value can be
garbage collected.
- Here are the main differences:
o you can’t iterate over the WeakSet.
o you can’t clear all items from a WeakSet.
o you can’t check its size.
127
Reflect Object → ES6
- Unlike most global objects, Reflect is not a constructor. You can’t use
it with a new operator or invoke the Reflect object as a function. All
properties and methods of Reflect are static (just like
the Math object).
- The Reflect object provides static functions, some of these methods
are also the same as corresponding methods on Object, although
they do have some subtle ( )خفيفdifferences between them.
Static methods
1. Reflect.apply(targetFunc, thisArgument, argumentsList)
o Calls a target function with arguments as specified by
the argumentsList parameter.
128
}
4. Reflect.deleteProperty(object, property)
o The delete operator as a function. Equivalent to
calling delete object[property]. Returns a Boolean that
is true if the property was deleted successful, false otherwise.
Reflect.get(obj, 'x') // 1
7. Reflect.getOwnPropertyDescriptor(object, property)
o Similar to Object.getOwnPropertyDescriptor(). Returns a
property descriptor of the given property if it exists on the
object, undefined otherwise.
o If the target argument to this method is not an object (a
primitive), then it will cause a TypeError.
With Object.getOwnPropertyDescriptor, a non-object first
argument will be coerced to an object at first.
Reflect.getOwnPropertyDescriptor('foo', 0)
// TypeError: "foo" is not non-null object
Object.getOwnPropertyDescriptor('foo', 0)
// { value: "f", writable: false, enumerable: true, configurable: false }
8. Reflect.getPrototypeOf(object)
o Same as Object.getPrototypeOf().
129
9. Reflect.setPrototypeOf(object, prototype)
o A function that sets the prototype of an object. Returns
a Boolean that is true if the update was successful, false
otherwise.
11. Reflect.isExtensible(object)
o Same as Object.isExtensible(). Returns a Boolean that is true if
the target is extensible.
12. Reflect.preventExtensions(object)
o Similar to Object.preventExtensions(). Returns a Boolean that
is true if the update was successful, false otherwise.
13. Reflect.ownKeys(object)
o Returns an array of the target object's own (not inherited)
property keys.
o Its return value is equivalent
to Object.getOwnPropertyNames(object).concat(Object.getO
wnPropertySymbols(object)).
Reflect.ownKeys({z: 3, y: 2, x: 1}) // [ "z", "y", "x" ]
130
Math Object
- The JavaScript Math object allows you to perform mathematical
tasks on numbers.
Math.PI; // returns 3.141592653589793
Math Constructor
- Unlike other global objects, the Math object has no constructor.
Methods and properties are static. Done without creating an object.
Math.round()
- Math.round(x) returns the value of x rounded to its nearest integer.
- It rounds negative values with decimal equal to -0.5 to the next
integer in the direction of +∞.
Math.round(-1.5) // return -1
Math.pow()
- Math.pow(base, exponent) returns the base to the exponent power, that
is, baseexponent.
- If the base is negative and the exponent is not an integer, the result
is NaN. Other cases work.
Math.sqrt()
- Math.sqrt(x) returns the square root of x.
- If the value of x is negative, it returns NaN.
Math.abs()
- Math.abs(x) returns the absolute (positive) value of x.
- Passing an empty object, an array with more than one member, a
non-numeric string or undefined/empty variable returns NaN.
Passing null, an empty string or an empty array returns 0.
Math.ceil()
131
- Math.ceil(x) returns the value of x rounded up to its nearest
integer.
- if x is null, it returns 0 and does not give a NaN error.
Math.floor()
Math.sin()
- Math.sin(x) returns the sine (a value between -1 and 1) of the angle
x (given in radians).
Math.cos()
- Math.cos(x) returns the cosine (a value between -1 and 1) of the
angle x (given in radians).
If you want to use degrees instead of radians, you have to convert degrees
to radians:
Angle in radians = Angle in degrees x PI / 180.
Math.random()
- Math.random() returns a random floating number between 0
(inclusive) and 1 (exclusive).
Math.trunc() → ES6
- The Math.trunc(value) method returns the integer part of a number.
132
- Note: This method will NOT round the number up/down to the
nearest integer, but simply remove the decimals.
Math.cbrt() → ES6
- The Math.cbrt(value) method returns the cubic root of a number.
Math.sign() → ES6
- Math.sign(value) method determine the sign of a number, including
special cases of signed zero and non-number.
133
Random
- Always returns a number lower than 1.
134
Comparison & Logical Operators
Comparison Operators
- Comparison operators are used in logical statements to determine
equality or difference between variables or values.
Operator Description
== equal to
!= not equal
Logical Operators
- Logical operators are used to determine the logic between variables
or values.
- Logical operators in JavaScript, unlike operators in other
programming languages, do not return true or false. They always
return one of the operands.
Operator Description
&& and
|| or
! not
135
Binary Logical Operators
And (&&)
- If the first operand is falsy, return it. Otherwise, return the second
operand.
Or (||)
- If the first operand is truthy, return it. Otherwise, return the second
operand.
136
Conditions
Conditional Statements
- you want to perform different actions for different decisions. You can
use conditional statements in your code to do this.
- In JavaScript we have the following conditional statements:
1. The if Statement
▪ Use the if statement to specify a block of JavaScript code to be
executed if a condition is true.
if (condition) {
// executed if the condition is true
}
if (condition) {
// executed if the condition is true
} else {
// executed if the condition is false
}
137
4. The switch Statement
▪ Use the switch statement to select one of many code blocks to
be executed.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
switch(expression) {
case x:
case z:
// code block
break;
case y:
case e:
138
// code block
break;
default:
// code block
}
Switching Details
- If multiple cases matches a case value, the first case is selected.
- If no matching cases are found, the program continues to
the default label.
- If no default label is found, the program continues to the
statement(s) after the switch.
Strict Comparison
- Switch cases use strict equality (===). The values must be of the
same type to match.
139
Loops
- Loops are handy, if you want to run the same code over and over
again, each time with a different value.
▪ Statement 1
o is executed (one time) before the execution of the code block.
o Initialize the variable used in the loop.
o It’s Optional.
for (; i < len; i++) {
// code block to be executed
}
▪ Statement 2
o defines the condition for executing the code block. It used to
evaluate the condition of the initial variable.
o It’s Optional too but you must provide a break inside the loop.
o If statement 2 returns true, the loop will start over again, if it
returns false, the loop will end.
▪ Statement 3
o executed (every time) after the code block has been executed.
o Often statement 3 increments the value of the initial variable.
o It’s Optional too but you need to add increment inside the loop.
o Statement 3 can do anything like negative increment (i--),
positive increment (i = i + 15), or anything else.
140
text += cars[i] + "<br>";
i++;
}
for (x in person) {
text += person[x];
}
- NOTE: For/Of goes over values but For/In goes over properties
and values.
141
- You need to handle the condition such as incrementing (positive or
negative).
do {
// code block to be executed
}
while (condition);
142
Break & Continue
The Break Statement
- used to "jump out" of a switch() statement.
- used to jump out of a loop.
- used to jump out of any code block with labels.
JavaScript Labels
- To label JavaScript statements you precede ( )تسبقthe statements with
a label name and a colon.
- Labels should be nested in one code block or will throw an error.
label:
{
statements;
}
break labelname;
continue labelname; // it’s used inside loops ONLY
L: function F() {}
143
Type Conversion
The Data Type of typeof
- The typeof operator is not a variable. It is an operator. Operators (
+ - * / ) do not have any data type.
- typeof is mainly used for primitive values, while instanceof is used
for objects.
var ob = {};
ob instanceof Object; // true
5 + null
144
// returns 5, because null is converted to 0
"5" + null
// returns "5null", because null is converted to "null"
"5" + 2
// returns "52", because 2 is converted to "2"
"5" - 2
// returns 3, because "5" is converted to 5
"5" * "2"
// returns 10, because "5" and "2" are converted to 5 and 2
document.getElementById("demo").innerHTML = myVar;
// if myVar = {name:"Fjohn"}
// toString converts to "[object Object]"
// if myVar = [1,2,3,4]
// toString converts to "1,2,3,4"
// if myVar = new Date()
// toString converts to "Fri Jul 18 2014 09:08:55 GMT+0200"
0 0 "0" false
1 1 "1" true
145
"0" 0 "0" true
[] 0 "" true
146
Bitwise Operations
JavaScript Uses 32 bits Bitwise Operands
- JavaScript stores numbers as 64 bits floating point numbers.
- Before a bitwise operation, JavaScript converts numbers to 32 bits
signed integers after that, the result converted back to 64 bits.
Operation Result
0&0 0
0&1 0
1&0 0
1&1 1
Bitwise OR ( | )
- It returns 1 if one of the bits are 1.
Operation Result
0|0 0
0|1 1
1|0 1
1|1 1
Bitwise XOR ( ^ )
- It returns 1 if the bits are different.
Operation Result
0^0 0
0^1 1
1^0 1
1^1 0
147
JavaScript Bitwise NOT ( ~ )
- Inverts all the bits.
- The result always done by –( num + 1).
~5 = -(5+1) = -6
~-6 = -(-6+1) = 5
5 00000000000000000000000000000101
-5 11111111111111111111111111111011
5 00000000000000000000000000000101
Binary Numbers
- JavaScript binary numbers are stored in two's complement format.
This means that a negative number is the bitwise NOT of the
number plus 1.
5 → 00000000000000000000000000000101 to get -5
~5 → 11111111111111111111111111111010 = -6
Then plus 1 to it which is XOR
1111111111111111111111111111010
00000000000000000000000000000001
148
-5 → 1111111111111111111111111111011
149
Regular Expressions
- A regular expression is a sequence of characters that forms a
search pattern. Used for text search or text replace.
/pattern/modifiers;
var patt = /w3schools/i;
- Note: If you want to use any special character as a part of the
expression, for example you want to match literal ), then you
have to escape them with backslash “\)”.
- () use for subexpression.
Modifier Description
Expression Description
Metacharacter Description
150
\W Find a non-word character
Quantifier Description
151
Matches any string that contains a sequence of X to
n{X,Y}
Y n's
let re = /\w+/;
let re = new RegExp('\\w+');
152
RegExp Object methods
1. Using test()
▪ It searches a string for a pattern, and returns true or false,
depending on the result.
2. Using exec()
▪ It searches a string for a specified pattern, and returns the
found text as an object, if no match returns an empty object
(null).
Property Description
153
Errors
1. The try statement lets you test a block of code for errors.
2. The catch statement lets you handle the error.
3. The throw statement lets you create custom errors.
4. The finally statement lets you execute code, after try and catch,
regardless of the result.
//Before ES10
try {
undefined_Function("I'm trying");
} catch(error) {
console. log('action' );
}
// ES10
try {
undefined_Function("I'm trying");
} catch {
console. log('action' );
}
154
- When an error occurs, JavaScript will normally stop and generate an
error message.
- The technical term for this is: JavaScript will throw an exception
(throw an error).
- The throw statement allows you to create a custom error.
- The exception can be a String, a Number, a Boolean or an Object.
If you use throw together with try and catch, you can control program flow
and generate custom error messages.
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
try {
//Block of code to try
}
catch(err) {
//Block of code to handle errors
}
finally {
//Block of code to be executed regardless of the try / catch result
}
155
Property Description
156
Use Strict → ES5
The "use strict" Directive
- The "use strict" directive was new in ES5.
- Used to indicate that the code should be executed in "strict mode".
- All modern browsers support "use strict" except Internet Explorer 9
and lower.
- It helps you to write cleaner code.
157
9. Deleting an undeletable property is not allowed.
10. The word eval cannot be used as a variable.
11. The word arguments cannot be used as a variable.
12. The with statement is not allowed.
13. For security reasons, eval() is not allowed to create variables in
the scope from which it was called.
14. Requires that all properties named in an object literal be unique.
15. The this keyword in functions behaves differently in strict mode.
It refers to the object that called the function. If the object is not
specified, functions in strict mode will return undefined and
functions in normal mode will return the global object (window).
Future Proof!
o Keywords reserved for future JavaScript versions can NOT be used as
variable names in strict mode:
• implements
• interface
• let
• package
• private
• protected
• public
• static
• yield
158
Classes → ES6
- 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 are assigned inside a constructor() method.
Class Definition
- Use the keyword class to create a class and always add
the constructor() method.
- The constructor method is called each time the class object is
initialized.
class Car {
constructor(brand) {
this.carname = brand;
}
}
mycar = new Car("Ford");
Methods
- The constructor method is special, in fact, if you do not have a
constructor method, JavaScript will add an invisible and
empty constructor method.
- You are also free to make your own methods.
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return "I have a " + this.carname;
}
}
mycar = new Car("Ford");
let car = mycar.present();
Static Methods
159
- Static methods are defined on the class itself and not on the
prototype.
- That means you can’t call a static method on the object (mycar), but
on the class (Car).
class Car {
constructor(brand) {
this.carname = brand;
}
static hello() { // x
return "Hello!!"; // x.carname;
}
}
- If you want to use the mycar object inside the static method, you can
send it as a parameter.
document.getElementById("demo").innerHTML = Car.hello(mycar);
class Person {
#born = 1980;
age() { console.log(2020 - this.#born); }
}
const person1 = new Person();
person1.age(); // 40
console.log(person1.#born); //Uncaught SyntaxError: Private field '#born' must be declared
in an enclosing class
Inheritance
- To create a class inheritance, use the extends keyword.
160
- A class created with a class inheritance, inherits all the methods from
another class.
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
class Car {
constructor(brand) {
this.carname = brand;
161
}
get cnam() {
return this.carname;
}
set cnam(x) {
this.carname = x;
}
}
- Even get is a function, no need for parentheses () when you use it.
- The name of the getter/setter method can’t be the same as the
name of the property. So we can use an underscore
character _ before the property name to separate the getter/setter
from the actual property.
class Car {
constructor(brand) {
this._carname = brand;
}
get carname() {
return this._carname;
}
}
- To use a setter, use the same syntax as when you set a property
value, without parentheses ().
class Car {
constructor(brand) {
this._carname = brand;
}
get carname() {
return this._carname;
}
162
set carname(x) {
this._carname = x;
}
}
163
Modules → ES6
- A module is a reusable piece of code that encapsulates
implementation details and exposes a public API so it can be easily
loaded and used by other code.
- A module format is the syntax we use to define a module. Different
module formats
such AMD, CommonJS, UMD and System.register have emerged in
the past and a native module format is now available since ES6.
- A module loader interprets and loads a module written in a certain
module format at runtime. Popular examples
are RequireJS and SystemJS.
- A module bundler replaces a module loader and generates a bundle
of all code at build time. Popular examples
are Browserify and Webpack.
Module basics
- An ES6 module is a file containing JS code which is a small unit of
independent, reusable code. There’s no special module keyword; a
module mostly reads just like a script.
- What should know about ES6 Modules.
• ES6 modules are automatically strict-mode code, even if you
don’t write "use strict".
• You can use import and export in modules.
• Modules must be included in your HTML with type="module",
which can be an inline or external script tag.
• Modules are deferred and only run after a document is
loaded.
- ES6 modules is a very powerful concept, although support is not
available everywhere yet, a common way of using it is to transpile
into ES5. You can use Grunt, Gulp, Webpack, Babel or some other
transpiler to compile the modules during a build process.
Export Modules
- Everything declared inside a module is local to the module, by
default. If you want something declared in a module to be public, so
that other modules can use it, you must export that feature. There
are a few ways to do this.
1. You can export each module individually.
164
export let subtractAll = (a, b) => {return a - b;}
export let divideAll = (a, b) => {return a / b;}
export let multiplyAll = (a, b) => {return a * b;}
export let findModulus = (a, b) => {return a % b;}
- You can export any top-level function, class, var, let or const.
Import Modules
- In a separate file, we can import and use exported things. It can be
done in several ways.
1. You can import individually.
165
import { sumAll } from "./math.js";
Aggregating modules
- Sometimes the main module of a package is little more than
importing all the package’s other modules and exporting them in a
unified way. To simplify this kind of code, there’s an all-in-one
import-and-export shorthand.
166
// import "equatorial-guinea" and re-export some of its exports
export {Coffee, Cocoa} from "equatorial-guinea";
- Because the system doesn’t specify how loading works and because
you can figure out all the dependencies, an implementation of ES6 is
free to do all the work at compile time and bundle all your modules
into a single file to ship them over the network. Tools like webpack
does that.
- This is a big deal, because loading scripts over the network takes
time and every time you fetch one, you may find that it
167
contains import declarations that require you to load dozens more. A
naive loader would require a lot of network round trips.
- Modules are singletons. Even if a module is imported multiple times,
only a single “instance” of it exists.
168
- The ES6 module syntax is very static and that’s good—it’s paying off
in the form of powerful compile-time tools. But the static syntax was
designed to work alongside a rich dynamic, programmatic loader API.
// Option 1
const moduleSpecifier = './utils.js';
import (moduleSpecifier)
.then((module) => {
module.doStuff1( ) ; // Method-1
module.doStuff2( ) ; // Method-2
});
Resources:
- Modules.
169
JavaScript Async
1. Callbacks
- It is a function passed as an argument to another function.
- This technique allows a function to call another function, a callback
function can run after another function has finished.
Function Sequence
- JavaScript functions are executed in the sequence they are called.
Not in the sequence they are defined.
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
myCalculator(5, 5, myDisplayer);
2. Asynchronous JavaScript
- Functions running in parallel with other functions are called
asynchronous.
- When using the JavaScript function setTimeout(), you can specify a
callback function to be executed on time-out.
setTimeout(myFunction, 4000);
function myFunction() {
170
document.getElementById("demo").innerHTML = "I love You !!";
}
3. Promises → ES6
- "I promise a result!"
- "Producing code" is code that can take some time.
- "Consuming code" is code that must wait for the result, functions
want the result of the “producing code” once it’s ready.
- A promise is a JavaScript object that links producing code and
consuming code. The “producing code” takes whatever time it needs
to produce the promised result and the “promise” makes that result
available to all of the subscribed code when it’s ready.
- Promises done ONE time, accepting first value.
let promise = new Promise(function(resolve, reject) {
// The producing code (it may takes some time)
- When the executing code obtains the result, it should call one of the
two callbacks.
Result Call
171
- When a Promise object state is "rejected", the result is an
error object.
catch
- If we’re interested only in errors, then we can use null as the
first argument: .then(null, errorHandlingFunction). Or we
can use .catch(errorHandlingFunction), which is exactly the
same.
finally
- The call .finally(f) is similar to .then(f, f) in the sense
that f always runs when the promise is settled: resolve or reject.
172
- finally is a good handler for performing cleanup, e.g. stopping
our loading indicators, as they are not needed anymore, no
matter what the outcome is.
- A finally handler has no arguments.
- A finally handler passes results and errors to the next handler.
promise
.then(
function(result) { /* handle successful result */ },
function(error) { /* handle an error */ }
)
.finally(()=>{ /*do it doesn’t matter the result */ });
Chaining
- A common need is to execute two or more asynchronous
operations back to back, where each subsequent operation starts
when the previous operation succeeds, with the result from the
previous step. We accomplish this by creating a promise chain.
doSomething()
.then(function(result) {
return doSomethingElse(result);
})
.then((newResult) => doThirdThing(newResult))
.then(function(finalResult) {
console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);
173
▪ Sent when a promise is rejected, after that rejection
has been handled by the executor's reject function.
2. unhandledrejection
▪ Sent when a promise is rejected but there is no
rejection handler available.
- In both cases, the event (of type PromiseRejectionEvent) has
a promise property indicating the promise that was rejected,
and a reason property that provides the reason given for the
promise to be rejected.
- These make it possible to offer fallback error handling for
promises, as well as to help debug issues with your promise
management. These handlers are global per context, so all
errors will go to the same event handlers, regardless of source.
- You can handle unhandled promises by adding a handler for
the unhandledrejection event.
event.preventDefault();
}, false);
Composition
- Promise.resolve() and Promise.reject() are shortcuts to
manually create an already resolved or rejected promise
respectively.
- Promise.all() and Promise.race() are two composition tools
for running asynchronous operations in parallel.
Nesting
- Nesting is a control structure to limit the scope
of catch statements. Specifically, a nested catch only catches
failures in its scope and below, not errors higher up in the chain
outside the nested scope. When used correctly, this gives
greater precision in error recovery.
174
doSomethingCritical()
.then(result => doSomethingOptional(result)
.then(optionalResult => doSomethingExtraNice(optionalResult))
.catch(e => {})
) // Ignore if optional stuff fails; proceed.
.then(() => moreCriticalStuff())
.catch(e => console.error("Critical failure: " + e.message));
2. Promise.allSettled → ES11
▪ A method returns a promise that resolves after all of the
given promises have either fulfilled or rejected, with an
array of objects that each describes the outcome of each
promise.
▪ It is typically used when you have multiple asynchronous
tasks that are not dependent on one another to
175
complete successfully or you'd always like to know the
result of each promise.
▪ If the iterable is empty, returned value is an empty array
and run sync.
Promise.allSettled([
Promise.resolve(33),
new Promise(resolve => setTimeout(() => resolve(66), 0)),
99,
Promise.reject(new Error('an error'))
])
.then(values => console.log(values));
// [
// {status: "fulfilled", value: 33},
// {status: "fulfilled", value: 66},
// {status: "fulfilled", value: 99},
// {status: "rejected", reason: Error: an error}
// ]
3. Promise.any
▪ Takes an iterable of Promise objects and as soon as one
of the promises in the iterable fulfills, returns a single
promise that resolves with the value from that promise.
▪ If no promises in the iterable fulfill (if all of the given
promises are rejected), then the returned promise is
rejected with an AggregateError, a new subclass
of Error that groups together individual errors. Essentially,
this method is the opposite of Promise.all().
▪ Return an already rejected Promise if
the iterable passed is empty.
▪ Return an asynchronously resolved Promise if
the iterable passed contains no promises.
▪ This method is useful for returning the first promise that
fulfills.
▪ This method returns the first fulfilled value. This method
will ignore all rejected promises up until the first promise
that fulfils.
176
reject("Always fails");
});
4. Promise.race
▪ A method returns a promise that fulfills or rejects as soon
as one of the promises in an iterable fulfills or rejects,
with the value or reason from that promise.
▪ If the iterable passed is empty, the promise returned will
be forever pending.
▪ If the iterable contains one or more non-promise value
and/or an already settled promise, then Promise.race will
resolve to the first of these values found in the iterable.
var p = Promise.race(resolvedPromisesArray);
// immediately logging the value of p
console.log(p);
// setTimeout to execute code after stack is empty
setTimeout(function(){
console.log('the stack is now empty');
console.log(p);
177
});
// logs, in order:
// Promise { <state>: "pending" }
// the stack is now empty
// Promise { <state>: "fulfilled", <value>: 33 }
- Same as:
- The keyword await before a function makes the function wait for
a promise.
178
Proxy → ES6
- Throughout the ES6 standard, wherever possible, any bit of syntax or
built-in function that does anything with objects is specified in terms
of the 14 internal methods. ES6 drew a clear boundary around the
brains of an object. What proxies let you do is, replace the standard
kind of brains with arbitrary JS code.
- When we start talking about overriding these internal methods in a
moment, remember, we’re talking about overriding the behavior of
core syntax like obj.prop, built-in functions like Object.keys() and
more.
- ES6 defines a new global constructor, Proxy. It takes two arguments:
a target object and a handler object.
- Focusing on how proxy and target are related. In this example, all
of proxy’s internal methods are forwarded to target. That is, if
something calls proxy.[[Enumerate]](), it’ll just
return target.[[Enumerate]]().
- We’ll do something that causes proxy.[[Set]]() to be called.
proxy.color = "pink";
- It did. And the same goes for all the other internal methods. This
proxy will, for the most part, behave exactly the same as its target.
- There are limits to the fidelity ( )االخالصof the illusion. You’ll find
that proxy !== target and a proxy will sometimes flunk ( )يفشلtype
checks that the target would pass. Even if a proxy’s target is a DOM
Element, for example, the proxy isn’t really an Element; so
something like document.body.appendChild(proxy) will fail with
a TypeError.
Proxy handlers
- The handler object’s methods can override any of the proxy’s internal
methods.
- Handler functions are sometimes called traps, presumably because
they trap calls to the target object.
179
- For example, if you’d like to intercept all attempts to assign to an
object’s properties, you can do that by defining
a handler.set() method.
- With the help of the Reflect class we can give some accessors the
original behavior and redefine others. Arguments are the same
arguments (target, prop, receiver) that pass to the get function.
const target = {
message1: "hello",
message2: "everyone"
};
const handler3 = {
get: function (target, prop, receiver) {
if (prop === "message2") {
return "world";
}
return Reflect.get(...arguments);
},
};
console.log(proxy3.message1); // hello
console.log(proxy3.message2); // world
- The receiver argument provided value of this for the call to target.
When used with Proxy, it can be an object that inherits from target.
- All handler methods are optional. If an internal method is not
intercepted by the handler, then it’s forwarded to the target, as we
saw before.
180
- All Proxy Handlers from MDN.
Static Methods
Proxy.revocable(target, handler)
- A method used to create a revocable Proxy object.
▪ target: an object to wrap with Proxy. It can be any sort of
object, including a native array, a function or even another
proxy.
▪ handler: an object whose properties are functions define the
behavior of proxy when an operation is performed on it.
revocable.revoke();
181
Web Geolocation API
- Here details link
182
Event loop: Microtasks and Macrotasks
- Browser JavaScript execution flow, as well as in Node.js, is based on
an event loop.
Event Loop
- The event loop concept is very simple. There’s an endless loop, where
the JavaScript engine waits for tasks, executes them and then
sleeps, waiting for more tasks.
- The general algorithm of the engine:
1. While there are tasks.
Task
- A task is any JavaScript code which is scheduled to be run by the
standard mechanisms.
- Task can be Sync or Async.
- Sync tasks executed directly without enqueued them → Call Stack
- Async tasks are:
1. Macrotask → Task Queue
- Those tasks (their callbacks functions) are enqueued in Macrotask
Queue: setTimeout, setInterval, setImmediate,
requestAnimationFrame, I/O, UI Rendering.
2. Microtask → Job Queue
- Those tasks are enqueued in Microtask Queue: promises an
execution of .then/catch/finally handler. await as well, as it’s
another form of promise handling.
- There’s also a special function queueMicrotask(func) that
queues functions for execution in the microtask queue.
- MutationObserver is another microtask. Check here.
183
How JS engine handle Tasks:
- Immediately after every macrotask, the engine executes all
tasks from microtask queue, prior to running any other
macrotasks or rendering or anything else.
- A more detailed event loop algorithm:
1. Dequeue and run the oldest task from the macrotask queue.
a. Execute all microtasks:
i. While the microtask queue is not empty:
• Dequeue and run the oldest microtask.
2. If this is a good time to render:
a. Do some prep work.
b. Run requestAnimationFrame callbacks.
c. Render.
3. If the macrotask queue is empty, wait till a macrotask appears.
4. Go to step 1.
EX:
console.log(1)
setTimeout(() => {
queueMicrotask(() => {
console.log(2)
184
});
console.log(3)
});
Promise.resolve().then(() => console.log(4))
queueMicrotask(() => {
console.log(5)
queueMicrotask(() => {
console.log(6)
});
});
console.log(7)
Log - 6
Log - 2
output:
1 7 4 5 6 undefined 3 2
- 1,7 are sync so get printed. The microtask queue by the main
execution context is checked. There are two types of micro tasks here
one is the promise callback and the other is task queue by
queueMicroTask, which further puts another task in micro task queue.
So first 4 is printed, then 5 and as there is still a task remaining in
microtask queue 6 is also printed. After this the main execution
ends and undefined is printed and the program returns. Now it’s
time to look for tasks in macrotask queue. Here the callback of
setTimeout will be invoked. 3 is printed. The microtask queue is
checked again and 2 is printed finally.
185
import { of, merge, asapScheduler, asyncScheduler, animationFrameScheduler,
queueScheduler } from 'rxjs';
import { filter, startWith, observeOn } from 'rxjs/operators';
const delay = 0;
const async$ = of('async')
.pipe(observeOn(asyncScheduler, delay)); // macro queue
console.log('after subscription');
output:
queue
after subscription
asap
animationFrameScheduler
async
186
187
JavaScript Debugging
Code Debugging
▪ Programming code might contain syntax errors or logical errors.
Many of these errors are difficult to diagnose.
▪ Often, There are no error messages and you will get no indications
where to search for errors.
▪ Searching for (and fixing) errors in programming code is called code
debugging.
JavaScript Debuggers
1. The console.log() Method
o If your browser supports debugging, you can
use console.log() to display JavaScript values in the debugger
window.
2. Setting Breakpoints
o In the debugger window, you can set breakpoints in the
JavaScript code. At each breakpoint, JavaScript will stop
executing and let you examine JavaScript values.
o After that you can resume the execution of code (typically with
a play button).
188
JavaScript Style Guide & Coding Conventions
▪ Always use the same coding conventions for all your JavaScript
projects.
Variable Names
▪ use camelCase for identifier names (variables and functions).
Code Indentation
▪ Always use 2 spaces for indentation of code blocks.
Statement Rules
▪ General rules for simple statements:
o Always end a simple statement with a semicolon.
▪ General rules for complex (compound) statements:
o Put the opening bracket at the end of the first line.
o Use one space before the opening bracket.
o Put the closing bracket on a new line, without leading spaces.
o Do not end a complex statement with a semicolon.
if (time < 20) {
189
greeting = "Good day";
} else {
greeting = "Good evening";
}
Object Rules
▪ General rules for object definitions:
o Place the opening bracket on the same line as the object name.
o Use colon plus one space between each property and its value.
o Use quotes around string values, not around numeric values.
o Do not add a comma after the last property-value pair.
o Place the closing bracket on a new line, without leading spaces.
o Always end an object definition with a semicolon.
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Line Length
▪ For readability, avoid lines longer than 80 characters. If a
JavaScript statement does not fit on one line, the best place to break
it, is after an operator or a comma.
Naming Conventions
▪ Always use the same naming convention for all your code. For
example:
o Variable and function names written as camelCase
o Global variables and Constants written in UPPERCASE.
▪ Hyphens in HTML and CSS:
▪ HTML5 attributes can start with data- (data-quantity, data-price).
▪ CSS uses hyphens in property-names (font-size).
190
▪ Hyphens can be mistaken as subtraction attempts.
Hyphens are not allowed in JavaScript names.
▪ Underscores:
▪ Many programmers prefer to use underscores (date_of_birth),
especially in SQL databases.
▪ PascalCase:
▪ often preferred by C programmers.
▪ camelCase:
▪ camelCase is used by JavaScript itself, by jQuery and other
JavaScript libraries.
NOTE: Do not start names with a $ sign. It will put you in conflict with
many JavaScript library names.
File Extensions
▪ HTML files should have a .html extension (not .htm).
▪ CSS files should have a .css extension.
▪ JavaScript files should have a .js extension.
191
192
JavaScript Best Practices
Avoid Global Variables
- Minimize the use of global variables. This includes all data types,
objects and functions.it can be overwritten by other scripts.
Declarations on Top
- It is a good coding practice to put all declarations at the top of each
script or function.
- This will:
• Give cleaner code. Where all local variables in one place.
• Make it easier to avoid unwanted global variables.
• Reduce unwanted re-declarations.
Initialize Variables
- It is a good coding practice to initialize variables when you declare
them.
- This will:
• Give cleaner code.
• Provide a single place to initialize variables.
• Avoid undefined values.
193
- Use false instead of new Boolean()
- Use [] instead of new Array()
- Use /()/ instead of new RegExp()
- Use function (){} instead of new Function()
194
JavaScript Common Mistakes
Accidentally Using the Assignment Operator
- uses an assignment operator (=), instead of a comparison operator
(==) in an if statement.
Misunderstanding Floats
var x = 0.1;
var y = 0.2;
var z = x + y // the result in z will not be 0.3
var x = "Hello \
World!";
Misplacing Semicolon
if (x == 19);
{
// code block will be executed
}
function myFunction(a) {
var power = 10
return a * power // so this will work as expected
}
195
- Never break a return statement.
196
- But you cannot test if an object is null, because this will throw an
error if the object is undefined.
- To solve this problem, you must test if an object is not null and
not undefined. But this can still throw an error.
- Because of this, you must test for not undefined before you can test
for not null.
if (!!myObj)
197
JavaScript Performance (speed up your code)
Reduce Activity in Loops
- Statements or assignments that can be placed outside the loop will
make the loop run faster.
var i;
var l = arr.length;
for (i = 0; i < l; i++) {
change it to this:
document.getElementById("demo").innerHTML = firstName + " " + lastName;
198
- The HTTP specification defines that browsers should not download
more than two components in parallel.
- An alternative is to use defer="true" in the script tag. The defer
attribute specifies that the script should be executed after the page
has finished parsing, but it only works for external scripts.
199
JavaScript Forms
JavaScript Form Validation
- HTML form validation can be done by JavaScript.
- The (validation function) can be called when the form is submitted.
Data Validation
- Data validation is the process of ensuring that user input is clean,
correct and useful.
- Validation can be defined by many different methods and deployed in
many different ways.
1. Server side validation is performed by a web server, after
input has been sent to the server.
2. Client side validation is performed by a web browser, before
input is sent to a web server.
Attribute Description
200
2. Constraint Validation CSS Pseudo Selectors
Selector Description
Property Description
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}
}
Property Description
201
validity Contains boolean properties related to the
validity of an input element.
a. Validity Properties
Property Description
202
HTML DOM
- With the HTML DOM, JavaScript can access and change all the
elements of an HTML document.
- When a web page is loaded, the browser creates
a Document Object Model of the page.
- The HTML DOM model is constructed as a tree of Objects.
- With the object model, JavaScript gets all the power it needs to
create dynamic HTML:
• JS can change all the HTML elements in the page.
• JS can change all the HTML attributes in the page.
• JS can change all the CSS styles in the page.
• JS can remove existing HTML elements and attributes.
• JS can add new HTML elements and attributes.
• JS can react to all existing HTML events in the page.
• JS can create new HTML events in the page.
203
What is the HTML DOM?
- The HTML DOM is a standard object model and programming
interface for HTML. It defines:
204
HTML DOM Methods
The DOM Programming Interface
- The HTML DOM can be accessed with JavaScript.
- In the DOM, all HTML elements are defined as objects.
- The programming interface is the properties and methods of
each object.
- A property is a value that you can get or set (like changing the
content of an HTML element).
- A method is an action you can do (like add or deleting an HTML
element).
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
205
HTML DOM Document
The HTML DOM Document Object
- The HTML DOM document object is the owner of all other objects in
your web page.
- If you want to access any element in an HTML page, you always start
with accessing the document object.
206
document.implementation Returns the DOM implementation 3
207
HTML DOM Collections
The HTMLCollection Object
- As example, getElementsByTagName() method returns
an HTMLCollection object.
- An HTMLCollection object is an array-like list (collection) of HTML
elements.
- The elements in the collection can be accessed by an index number.
EX: The following code selects all <p> elements in a document:
var x = document.getElementsByTagName("p");
y = x[1];
- The length property is useful when you want to loop through the
elements in a collection.
Methods
1. HTMLCollection.item(index)
- Returns the specific node at the given index into the list.
Returns null if the index is out of range.
- An alternative to accessing collection[i].
208
2. HTMLCollection.namedItem(ID)
- Returns the specific node whose ID or as a fallback name matches
the string specified by name. Matching by name is only done as a last
resort, only in HTML and only if the referenced element supports
the name attribute. Returns null if no node exists by the given
name.
- An alternative to accessing collection[name].
An HTMLCollection may look like an array, but it is not. You can loop
through the list and refer to the elements with a number (just like an
array).
However, you can’t use array methods like valueOf(), pop(), push(), or
join() on an HTMLCollection.
209
HTML DOM Navigation
- With the HTML DOM, you can navigate the node tree using node
relationships.
DOM Nodes
- According to the W3C HTML DOM standard, everything in an HTML
document is a node:
- With the HTML DOM, all nodes in the node tree can be accessed by
JavaScript.
- New nodes can be created and all nodes can be modified or deleted.
Node Relationships
- The nodes in the node tree have a hierarchical relationship to each
other.
- The terms parent, child and sibling ( )إخوانare used to describe the
relationships:
o In a node tree, the top node is called the root (or root node).
o Every node has exactly one parent, except the root (which has
no parent).
o A node can have a number of children.
o Siblings (brothers or sisters) are nodes with the same parent.
<html>
<head>
<title>DOM Tutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
210
</html>
- and:
o <head> has one child: <title>.
o <title> has one child (a text node): "DOM Tutorial".
o <body> has two children: <h1> and <p>.
o <h1> has one child: "DOM Lesson one".
o <p> has one child: "Hello world!".
o <h1> and <p> are siblings.
211
Child Nodes and Node Values
- A common error in DOM processing is to expect an element node to
contain text.
- The element node <title> (in the example above) does not contain
text.
- It contains a text node with the value "DOM Tutorial".
- The value of the text node can be accessed by the
node's innerHTML property:
InnerHTML
- In this tutorial we use the innerHTML property to retrieve the content
of an HTML element.
- However, learning the other methods above is useful for
understanding the tree structure and the navigation of the DOM.
EX
<html>
<body>
<p>Hello World!</p>
212
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>
<script>
alert(document.body.innerHTML);
alert(document.documentElement.innerHTML);
</script>
</body>
</html>
<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").nodeName;
</script>
213
The nodeType Property
- The nodeType property is read only. It returns the type of a node.
<script>
document.getElementById("id02").innerHTML =
document.getElementById("id01").nodeType;
</script>
ELEMENT_NODE 1 <h1
class="heading">W3Schools</h1>
TEXT_NODE 3 W3Schools
214
HTML DOM Node Lists
The HTML DOM NodeList Object
- A NodeList object is a list (collection) of nodes extracted from a
document.
- childNodes return a Live NodeList object for the property .
- querySelectorAll() return a Static NodeList object for the method.
- Some (older) browsers return a NodeList object instead of an
HTMLCollection for methods like getElementsByClassName().
EX: The following code selects all <p> nodes in a document.
y = myNodeList[1];
myNodelist = document.querySelectorAll("p");
document.getElementById("demo").innerHTML = myNodelist.length;
- The length property is useful when you want to loop through the
nodes in a node list.
EX: Change the background color of all <p> elements in a node list
var myNodelist = document.querySelectorAll("p");
var i;
for (i = 0; i < myNodelist.length; i++) {
myNodelist[i].style.backgroundColor = "red";
}
215
- An alternative to accessing nodeList[i].
• NodeList.entries()
- Returns an iterator, allowing code to go through all key/value
pairs contained in the collection. (In this case, the keys are
numbers starting from 0 and the values are nodes)
• NodeList.forEach()
- Executes a provided function once per NodeList element,
passing the element as an argument to the function.
• NodeList.keys()
- Returns an iterator, allowing code to go through all the keys of
the key/value pairs contained in the collection. (In this case,
the keys are numbers starting from 0)
• NodeList.values()
- Returns an iterator allowing code to go through all values
(nodes) of the key/value pairs contained in the collection.
216
A node list may look like an array, but it is not. You can loop through the
node list and refer to its nodes like an array.
However, you can’t use Array Methods, like valueOf(), push(), pop(), or
join() on a node list.
217
HTML DOM Elements (Nodes)
- Adding and Removing Nodes (HTML Elements).
Creating New HTML Elements (Nodes)
- To add a new element to the HTML DOM, you must create the
element (element node) first and then append it to an existing
element.
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
o Example Explained
This code creates a new <p> element.
To add text to the <p> element, you must create a text node
first. This code creates a text node.
- Then you must append the text node to the <p> element.
para.appendChild(node);
218
- This code appends the new element to the existing element.
element.appendChild(para);
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
<div>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
219
var elmnt = document.getElementById("p1");
elmnt.remove();
</script>
o Example Explained
- The HTML document contains a <div> element with two
child nodes (two <p> elements).
<div>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
elmnt.remove();
- The remove() method does not work in older browsers, see the
example below on how to use removeChild() instead.
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>
o Example Explained
220
- This HTML document contains a <div> element with two
child nodes (two <p> elements).
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
parent.removeChild(child);
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
221
</script>
222
TML DOM Elements
Finding HTML Elements
- Often, with JavaScript, you want to manipulate HTML elements. To do
so, you have to find the elements first. There are several ways to do
this:
var x = document.getElementsByTagName("p");
EX: finds the element with id="main", and then finds all <p> elements
inside "main".
var x = document.getElementById("main");
var y = x.getElementsByTagName("p");
223
- It returns live HTMLCollection of found elements. If no elements
found, empty HTMLCollection returned.
- You may also call it on any element object.
- You can look for multiple class names, separated by whitespace.
EX: returns a list of all elements with class="intro".
var x = document.getElementsByClassName("intro");
var x = document.querySelectorAll("p.intro");
224
- You can look for different selectors by separate them with comma.
You can look for multiple selectors in selector1, separated by
whitespace.
- For special characters, you must escape it twice (once for the
JavaScript string and another time for querySelector())
EX: Match a div with id=‘foo:bar’
document.querySelector('#foo\\:bar');
var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
225
HTML DOM - Changing HTML
Changing the HTML Output Stream
- The HTML DOM allows JavaScript to change the content of HTML
elements.
- In JavaScript, document.write() can be used to write directly to
the HTML output stream.
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
<html>
<body>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
226
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
<script>
document.getElementById("p2").style.color = "blue";
227
</script>
</body>
</html>
228
HTML DOM Animation
A Basic Web Page
- To demonstrate how to create HTML animations with JavaScript,
we will use a simple web page.
<!DOCTYPE html>
<html>
<body>
</body>
</html>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
229
height: 50px;
position: absolute;
background: red;
}
Animation Code
- 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.
function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
230
}
231
HTML DOM Events
- HTML DOM allows JavaScript to react to HTML events.
- HTML events are "things" that happen to HTML elements.
- An HTML event can be something the browser does or something a
user does.
- JavaScript lets you execute code when events are detected.
- HTML allows event handler attributes, with JavaScript code, to be
added to HTML elements.
Reacting to Events
- A JavaScript can be executed when an event occurs, like when a user
clicks on an HTML element.
- To execute code when a user clicks on an element, add JavaScript
code to an HTML event attribute.
onclick=JavaScript
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.
EX: the content of the <h1> element is changed when a user clicks on
it.
<!DOCTYPE html>
<html>
<body>
</body>
</html>
232
<html>
<body>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>
<script>
document.getElementById("myBtn").onclick = displayDate;
</script>
233
- The onload event can be used to check the visitor's browser type and
browser version and load the proper version of the web page based
on the information.
- The onload and onunload events can be used to deal with cookies.
<body onload="checkCookies()"></body>
<!DOCTYPE html>
<html>
<body>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>
<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}
function mOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
</script>
</body>
234
</html>
<!DOCTYPE html>
<html>
<body>
<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
obj.innerHTML = "Release Me";
}
function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>
</body>
</html>
More Examples
- onmousedown and onmouseup
Change an image when a user holds down the mouse button.
- onload
Display an alert box when the page has finished loading.
235
- onfocus
Change the background-color of an input field when it gets focus.
- Mouse Events
Change the color of an element when the cursor moves over it.
236
HTML DOM EventListener
The addEventListener() method
document.getElementById("myBtn").addEventListener("click", displayDate);
Syntax
element.addEventListener(event, function, useCapture);
- The first parameter is the type of the event (like "click" or
"mousedown" or any other HTML DOM Event)
- The second parameter is the function we want to call when the event
occurs.
- The third parameter is a boolean value specifying whether to use
event bubbling or event capturing. This parameter is optional.
- Note that you don't use the "on" prefix for the event; use "click"
instead of "onclick".
element.addEventListener("click", myFunction);
function myFunction() {
237
alert ("Hello World!");
}
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = sometext;
});
Passing Parameters
- When passing parameter values, use an "anonymous function" that
calls the specified function with the parameters.
var p1 = 5;
var p2 = 7;
document.getElementById("myBtn").addEventListener("click", function() {
myFunction(p1, p2);
});
238
- Event propagation is a way of defining the element order when an
event occurs. If you have a <p> element inside a <div> element and
the user clicks on the <p> element, which element's "click" event
should be handled first?
- In bubbling the inner most element's event is handled first and
then the outer: the <p> element's click event is handled first then the
<div> element's click event.
- In capturing the outer most element's event is handled first and
then the inner: the <div> element's click event will be handled first
then the <p> element's click event.
- With the addEventListener() method you can specify the propagation
type by using the "useCapture" parameter.
addEventListener(event, function, useCapture);
- The default value is false, which will use the bubbling propagation,
when the value is set to true, the event uses the capturing
propagation.
element.removeEventListener("mousemove", myFunction);
Browser Support
- Note: The addEventListener() and removeEventListener() methods
are not supported in IE 8 and earlier versions. However, for these
specific browser versions, you can use the attachEvent() method to
attach an event handlers to the element, and
the detachEvent() method to remove it:
element.attachEvent(event, function);
element.detachEvent(event, function);
var x = document.getElementById("myBtn");
if (x.addEventListener) { // For all major browsers, except IE 8 and earlier
x.addEventListener("click", myFunction);
} else if (x.attachEvent) { // For IE 8 and earlier versions
x.attachEvent("onclick", myFunction);
}
239
preventDefault Event Method
- The preventDefault() method cancels the event if it is cancelable,
meaning that the default action that belongs to the event will not
occur.
- For example, this can be useful when:
• Clicking on a "Submit" button, prevent it from submitting a
form.
• Clicking on a link, prevent the link from following the URL.
- Note: Not all events are cancelable. Use the cancelable property to
find out if an event is cancelable.
- Note: The preventDefault() method doesn’t prevent further
propagation of an event through the DOM. Use the stopPropagation()
method to handle this.
var x = document.getElementById("myBtn");
x.addEventListener("click", myFunction);
x.addEventListener("click", someOtherFunction);
function myFunction(event) {
alert ("Hello World!");
event.stopImmediatePropagation();
}
240
alert ("I will not get to say Hello World");
}
241
Browser BOM
The Browser Object Model (BOM)
- There are no official standards for the Browser Object Model (BOM).
window.document.getElementById("header");
document.getElementById("header");
Window Size
- Two properties can be used to determine the size of the browser
window. Both properties return the sizes in pixels:
o window.innerHeight - the inner height of the browser window.
o window.innerWidth - the inner width of the browser window.
- The browser window (the browser viewport) is NOT including toolbars
and scrollbars.
- For Internet Explorer 8, 7, 6, 5:
o document.documentElement.clientHeight
o document.documentElement.clientWidth or
o document.body.clientHeight
o document.body.clientWidth
EX: A practical JavaScript solution (covering all browsers, do for the
height in the same way):
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
242
Window Screen
- It contains information about the user's screen.
243
Window Location
- The window.location object can be used to get the current page
address (URL) and to redirect the browser to a new page.
244
Window History
- The window.history object contains the browsers history. It can be
written without the window prefix.
- To protect the privacy of the users, there are limitations to how
JavaScript can access this object.
245
Window Navigator
- The window.navigator object contains information about the
visitor's browser. It can be written without the window prefix.
Warning !!!
- The information from the navigator object can often be misleading,
and should not be used to detect browser versions because:
246
o Different browsers can use the same name.
o The navigator data can be changed by the browser owner.
o Some browsers misidentify themselves to bypass site tests.
o Browsers cannot report new operating systems, released later
than the browser.
247
Popup Boxes
- JavaScript has three kind of popup boxes: Alert box, Confirm box
and Prompt box.
- You can write all popup boxes without the window prefix.
1. Alert Box
- An alert box is often used if you want to make sure information
comes through to the user.
- When an alert box pops up, the user will have to click "OK" to
proceed.
- Syntax
window.alert("sometext");
2. Confirm Box
- A confirm box is often used if you want the user to verify or accept
something.
- When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
- If the user clicks "OK", the box returns true. If the user clicks
"Cancel", the box returns false.
- Syntax
window.confirm("sometext");
3. Prompt Box
- A prompt box is often used if you want the user to input a value
before entering a page.
- When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
- If the user clicks "OK" the box returns the input value. If the user
clicks "Cancel" the box returns null.
- Syntax
window.prompt("sometext","defaultText");
• Line Breaks
- To display line breaks inside a popup box, use a back-slash followed
by the character n.
248
249
Timing Events
- The window object allows execution of code at specified time intervals.
- These time intervals are called timing events.
- Timers are operated within a single thread and thus events might
queue up, waiting to be executed.
function to be executed.
milliseconds indicates the number of milliseconds before execution.
function to be executed.
milliseconds indicates the length of the time-interval between each
execution.
More Examples
- Another simple timing.
- A clock created with a timing event.
250
251
Cookies
What are Cookies?
- Cookies are data stored in small text files on user’s computer.
- When a web server has sent a web page to a browser, the connection
is shut down, and the server forgets everything about the user.
Cookies were invented to solve the problem "how to remember
information about the user".
- You can also add an expiry date (in UTC time). By default, the cookie
is deleted when the browser is closed.
- With a path parameter, you can tell the browser what path the cookie
belongs to. By default, the cookie belongs to the current page.
var x = document.cookie;
252
Change a Cookie with JavaScript
- With JavaScript, you can change a cookie the same way as you
create it.
- You should define the cookie path to ensure that you delete the right
cookie. Some browsers will not let you delete a cookie if you don't
specify the path.
253
1. A function to set a cookie value.
2. A function to get a cookie value.
3. A function to check a cookie value.
Example explained:
The parameters of the function above are the name of the cookie
(cname), the value of the cookie (cvalue) and the number of days
until the cookie should expire (exdays). The function sets a cookie
by adding together the cookiename, the cookie value and the
expires string.
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
254
}
return "";
}
Function explained:
Take the cookiename as parameter (cname).
Create a variable (name) with the text to search for (cname + "=").
Decode the cookie string, to handle cookies with special
characters, e.g. '$'
Split document.cookie on semicolons into an array called ca (ca =
decodedCookie.split(';')).
Loop through the ca array (i = 0; i < ca.length; i++), and read
out each value c = ca[i]).
If the cookie is found (c.indexOf(name) == 0), return the value of
the cookie (c.substring(name.length, c.length).
If the cookie is not found, return "".
function checkCookie() {
var username = getCookie("username");
if (username != "") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}
255
Window localStorage Property
- The localStorage and sessionStorage properties allow to save
key/value pairs in a web browser.
- The localStorage object stores data with no expiration date. The
data will not be deleted when the browser is closed and will be
available the next day, week or year.
- localStorage for all domain pages. Other domains have different
Storage objects.
• Syntax
- Syntax for SAVING data to localStorage.
localStorage.setItem("key", "value");
localStorage.removeItem("key");
256
Window sessionStorage Property
- The sessionStorage object stores data for only one session (the data
is deleted when the browser tab is closed).
- A page session lasts as long as the browser is open and survives over
page reloads and restores.
- Opening multiple tabs/windows with the same URL
creates sessionStorage for each tab/window.
• Syntax
- Syntax for SAVING data to sessionStorage.
sessionStorage.setItem("key", "value");
sessionStorage.removeItem("key");
sessionStorage.clear();
var x = localStorage.length;
257
Differences Between sessionStorage,
localStorage and Cookies
- calling localStorage on a document will return a Storage object;
calling sessionStorage on a document will return a
different Storage object. They function and are controlled
separately.
- localStorage and sessionStorage work on same-origin policy (same
domain, protocol and port).
- Cookies can be persistence or session, session stay as window/tab
are open, but persistence are saved on user’s disk until the expiration
date then deleted.
- localStorage and sessionStorage, the data is not sent back to the
server for every HTTP request, so it reducing the amount of traffic
between client and server.
- Cookies only allow you to store
strings. sessionStorage and localStorage allow you to store
JavaScript primitives but not Objects or Arrays.
- Cookies can be made secure by setting the httpOnly flag as true for
that cookie. This prevents client-side access to that cookie.
- Opening multiple tabs/windows with the same URL
creates sessionStorage for each tab/window while localStorage for
all domain pages.
258
Console
- The console object provides access to the browser's debugging
console. The specifics of how it works varies from browser to
browser, but there is a de facto ( )بحكم الواقعset of features that are
typically provided.
• console.assert()
- a method writes an error message to the console if the assertion is
false. If the assertion is true, nothing happens.
Syntax
console.assert(assertion, obj1 [, obj2, ..., objN]);
console.assert(assertion, msg [, subst1, ..., substN]); // C-like
message formatting
EX:
• console.clear()
- a method clears the console if the environment allows it.
• console.count()
- a method logs the number of times that this particular call
to count() has been called.
Syntax
console.count([label]);
EX:
function greet() {
console.count(user);
return "hi " + user;
}
259
user = "bob";
greet();
user = "alice";
greet();
console.count("alice");
Output:
// "bob: 1"
// "alice: 1"
// "alice: 2"
• console.countReset()
- a method resets counter used with console.count() for that label
to 0. If omitted, countReset() resets the default counter to 0.
Syntax
console.countReset([label]);
• console.debug()
- a method outputs a message to the web console at the "debug"
log level. The message is only displayed to the user if the
console is configured to display debug output.
Syntax
console.debug(obj1 [, obj2, ..., objN]);
console.debug(msg [, subst1, ..., substN]);
• console.dir()
- a method displays an interactive list of the properties of the
specified JavaScript object. The output is presented as a
hierarchical listing with disclosure triangles that let you see the
contents of child objects.
Syntax
console.dir(object);
• console.dirxml()
- Displays an interactive tree of the descendant elements of the
specified XML/HTML element. If it is not possible to display as
an element the JavaScript Object view is shown instead. The
260
output is presented as a hierarchical listing of expandable nodes
that let you see the contents of child nodes.
Syntax
console.dirxml(object);
• console.error()
- Outputs an error message to the Web Console.
Syntax
console.error(obj1 [, obj2, ..., objN]);
console.error(msg [, subst1, ..., substN]);
• Console.group()
- Creates a new inline group in the Web Console log. This indents
following console messages by an additional level,
until console.groupEnd() is called.
Syntax
console.group([label]);
EX:
console.log("This is the outer level");
console.group();
console.log("Level 2");
console.group();
console.log("Level 3");
console.warn("More of level 3");
console.groupEnd();
console.log("Back to level 2");
console.groupEnd();
console.log("Back to the outer level");
Output:
This is the outer level
console.group
Level 2
▼ console.group
Level 3
More of level 3
261
Back to level 2
Back to the outer level
• Console.groupCollapsed()
- Creates a new inline group in the Web Console.
Unlike console.group(), however, the new group is created
collapsed. The user will need to use the disclosure button next
to it to expand it, revealing the entries created in the group.
Syntax
console.groupCollapsed([label]);
• Console.info()
- A method outputs an informational message to the Web
Console. In Firefox, a small "i" icon is displayed next to these
items in the Web Console's log.
Syntax
console.info(obj1 [, obj2, ..., objN]);
console.info(msg [, subst1, ..., substN]);
• Console.log()
- a method outputs a message to the web console. The message
may be a single string (with optional substitution values) or it
may be any one or more JavaScript objects.
Syntax
console.log(obj1 [, obj2, ..., objN]);
console.log(msg [, subst1, ..., substN]);
262
• Logging objects
- Don't use console.log(obj),
use console.log(JSON.parse(JSON.stringify(obj))).This way
you are sure you are seeing the value of obj at the moment
you log it. Otherwise, many browsers provide a live view that
constantly updates as values change. This may not be what you
want.
• Console.table()
- Displays tabular data as a table.
- This function takes one mandatory argument data, which must
be an array or an object and one additional optional
parameter columns.
- It logs data as a table. Each element in the array (or
enumerable property if data is an object) will be a row in the
table.
- The first column in the table will be labeled (index). If data is an
array, then its values will be the array indices. If data is an
object, then its values will be the property names. Note that (in
Firefox) console.table is limited to displaying 1000 rows (first
row is the labeled index).
263
Syntax
console.table(data [, columns]);
EX:
Output:
EX:
Output:
EX:
264
console.table([john, jane, emily], ["firstName"]);
Output:
• Console.time()
- Starts a timer you can use to track how long an operation takes. You
give each timer a unique name, and may have up to 10,000
timers running on a given page. When you
call console.timeEnd() with the same name, the browser will
output the time, in milliseconds, that elapsed since the timer
was started.
Syntax
console.time(label);
• Console.timeEnd()
- Stops a timer that was previously started by calling console.time().
Syntax
console.timeEnd(label);
Syntax
console.timeStamp(label);
• Console.trace()
- A method outputs a stack trace to the Web Console.
Syntax
console.trace( [...any, ...data ]);
265
EX: this will show you the call path taken to reach the point at which you
call console.trace()
function foo() {
function bar() {
console.trace();
}
bar();
}
foo();
Output:
bar
foo
<anonymous>
- global namespace is just an unnamed function in JavaScript, so that is
why it tells us it’s an anonymous function.
• Console.warn()
- Outputs a warning message to the Web Console.
Syntax
console.warn(obj1 [, obj2, ..., objN]);
console.warn(msg [, subst1, ..., substN]);
266
What is the difference between ViewState and
SessionState?
- 'ViewState': It is maintained at only one level that is page-level.
Changes made on a single page is not visible on other pages.
Information that is gathered in view state is stored for the clients only
and cannot be transferred to any other place.
- 'SessionState': It is maintained at session-level and data can be
accessed across all pages in the web application. The information is
stored within the server and can be accessed by any person that has
access to the server where the information is stored.
- SessionState has the tendency for the persistence of user-specific data
and is maintained on the server-side. This data remains available until
the time that the session is completed or the browser is closed by the
user. The session state is only valid for type objects.
Interview Questions:
Website 1
Website 2
Website 3
Website 4
267