-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavaScript.txt
More file actions
468 lines (450 loc) · 18.5 KB
/
javaScript.txt
File metadata and controls
468 lines (450 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
INTRO
In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($).
adding a number and a string will return a string. Unlike + operator, other operators first tries to convert string to integer value and return number
JavaScript evaluates expressions from left to right. Different sequences can produce different results:
16 + 4 + "Volvo" => 20Volvo
"Volvo" + 16 + 4 => Volvo164
typeof - Returns the type of a variable
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined"
typeof undefined // Returns "undefined"
typeof null // Returns "object"
instanceof - Returns true if an object is an instance of an object type
The constructor property returns the constructor function for all JavaScript variables.
"John".constructor // Returns function String() {[native code]}
(3.14).constructor // Returns function Number() {[native code]}
false.constructor // Returns function Boolean() {[native code]}
[1,2,3,4].constructor // Returns function Array() {[native code]}
{name:'John',age:34}.constructor // Returns function Object() {[native code]}
new Date().constructor // Returns function Date() {[native code]}
function () {}.constructor // Returns function Function(){[native code]}
You cannot use typeof to determine if a JavaScript object is an array (or a date). To check if the object is an Array function
function isArray(myArray) {
return myArray.constructor === Array;
}
JavaScript variables can be converted to different data type -
By the use of a JavaScript function
Automatically by JavaScript itself
Bit operators work on 32 bits numbers. - &(AND), |(OR), ~(NOT), ^(XOR), <<(Zero fill left shift)
in - Property in Object like ("PI" in Math)
===
var x = "John";
var y = new String("John");
var z = new String("John");
// (x === y) is false because x and y have different types (string and object)
// (y === z) is false because x and y are different objects. Comparing two JavaScript objects will always return false
Everything With a "Value" is True and vis a versa
When comparing two strings, "2" will be greater than "12", because (alphabetically) 1 is less than 2.
inheritance is possible using prototype. By default every object has prototype property which can be used to attach methods and other properties
javaScript is a single threaded ie no 2 script can run simultaneously.
Ajax allow script to continue execution while waiting for some information ie do not block execution
spread operator and rest parameter - function(parameter1, ...n, parameter2){//n is an array}
methods
https://www.w3schools.com/js/js_string_methods.asp
https://www.w3schools.com/jsref/jsref_obj_string.asp
https://www.w3schools.com/jsref/jsref_obj_number.asp
https://www.w3schools.com/jsref/jsref_obj_array.asp
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
THIS KEYWORD
This has different values depending on where it is used.
In a method, this refers to the owner object.
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
In the example above, this is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.
Alone, this refers to the global object.
In a function, this refers to the global object. But in strict mode, this is undefined.
Methods like call(), and apply() can refer this to any object.
ERRORS
The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
throw "Too big"; // throw a text
throw 500; // throw a number
The finally statement lets you execute code, after try and catch, regardless of the result
example
try {
eval("alert('Hello)"); // Missing ' will produce an error
}
catch(err) {
document.getElementById("demo").innerHTML = err.name + ' ' + err.message;
}
SCOPE
types -
Global scope
Variables declared Globally (outside any function) have Global Scope.
Global variables can be accessed from anywhere in a JavaScript program.
example - declared without any keyword like let, var, const, etc
function scope
Variables declared Locally (inside a function) have Function Scope.
Local variables can only be accessed from inside the function where they are declared.
example - declared with var or let or const
Block scope
Variables declared with the var keyword can not have Block Scope. They can be accessed from outside the block.
let and const variables declared inside a block {} can not be accessed from outside the block
Scope determines the accessibility (visibility) of these variables.
Variables defined inside a function are not accessible (visible) from outside the function.
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
myFunction();
// code here can use carName
function myFunction() {
carName = "Volvo";
}
Global variables defined with the let keyword do not belong to the window object
HOISTING
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope (to the top of the current script or the current function).
JavaScript only hoists declarations, not initializations.
This means a variable can be used before it has been declared
Variables and constants declared with let or const are not hoisted
USE STRICT
"use strict"; Defines that JavaScript code should be executed in "strict mode".
Strict mode changes previously accepted "bad syntax" into real errors.
JavaScript in strict mode does not allow variables to be used if they are not declared.
mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
CONST
JavaScript const variables must be assigned a value when they are declared
It does NOT define a constant value. It defines a constant reference to a value.
Because of this, we cannot change constant primitive values, but we can change the properties of constant objects.
OBJECT
Objects are mutable. They are addressed by reference, not by value.
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
Accessors (Getters and Setters)
var person = {
firstName: "John",
lastName : "Doe",
language : "en",
get lang() {
return this.language;
},
set lang(lang) {
this.language = lang;
}
};
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;
// Set an object property using a setter:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
The Object.defineProperty(object, property, descriptor) method can also be used to add Getters and Setters:
// Define a getter
Object.defineProperty(person, "fullName", {
get : function () {return this.firstName + " " + this.lastName;}
});
Changing Meta Data
ES5 allows the following property meta data to be changed:
writable : true // Property value can be changed
enumerable : true // Property can be enumerated
configurable : true // Property can be reconfigured
OBJECT CREATION
factory pattern
var personFactory = function(name, age, state){
var temp = {};
temp.name = name;
temp.age = age;
temp.state = state;
temp.printPerson = function(){
console.log(this.name + ' ' + this.age + ' ' + this.state);
}
return temp;
}
var person1 = personFactory('John', 32, 'CA');
var person2 = personFactory('Kie', 25, 'NJ');
constructor pattern
based on 'function is another object'
use 'new' keyword to create object
drawback - each instance has the copy of every method defined inside the function
example
var personConstructor = function(name, age, state){
this.name = name;
this.age = age;
this.state = state;
this.printPerson = function(){
console.log(this.name + ' ' + this.age + ' ' + this.state);
}
}
var person1 = new personConstructor('John', 32, 'CA');
var person2 = new personConstructor('Kie', 25, 'NJ');
prototype pattern
this approach do not have properties or methods attached to the created object
example
var personPrototype = function(){};
personPrototype.prototype.name = 'no name'; // or personPrototype.name = 'no name';
personPrototype.prototype.age = 0;
personPrototype.prototype.state = 'no state';
personPrototype.prototype.printPerson = function(){
console.log(this.name + ' ' + this.age + ' ' + this.state);
}
var person1 = new personPrototype();
person1.name = 'John';
person1.age = 32;
person1.state = 'CA';
'name' in person1 // return true. checks whether 'name' property is present in person1. If it does not find there, javaScript checks in the parent object and its prototype
person1.hasOwnProperty('name') // return true. Checks only in the person1
dynamic prototype pattern
every properties and methods are defined inside the function
example
var personDynamicPrototype = function(name, age, state){
this.name = name;
this.age = age;
this.state = state;
if(typeof this.printPerson != 'function'){
personDynamicPrototype.prototype.printPerson = function(){
console.log(this.name + ' ' + this.age + ' ' + this.state);
}
}
}
var person1 = new personDynamicPrototype('John', 32, 'CA');
FUNCTION
Parameter Defaults
If a function is called with missing arguments (less than declared), the missing values are set to: undefined
ECMAScript 2015 allows default parameters in the function call:
function (a=1, b=1) { // function code }
The Arguments Object
JavaScript functions have a built-in object called the arguments object.
example
function findMax() {
var i;
var max = -Infinity;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
Objects are Passed by Reference. Changes to object properties are visible (reflected) outside the function.
Closures
function with preserved data
Global variables can be made local (private) with closures.
A closure is a function having access to the parent scope, even after the parent function has closed.
var add = (function () {
var counter = 0;
return function () {counter += 1; return counter}
})();
// The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.
// This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.
// This is called a JavaScript closure. It makes it possible for a function to have "private" variables.
add();
add();
add();
// the counter is now 3
CALLBACK FUNCTION
function can be passed as a parameter
example
function add(x, y){return x+y}
function multiply(x, y){return x*y}
function calc(x,y,callback){return callback(x,y)}
console.log(calc(3,5,add)); // =>8
console.log(calc(3,5,multiply)); // =>15
ANONYMOUS FUNCTION
function calc(x,y,callback){
if(typeof callback === 'function'){
return callback(x,y)
}
}
console.log(calc(3,5,function(a,b){return a+b})); // =>8
console.log(calc(3,5,function(a,b){return a*b})); // =>15
FUNCTION CHAINING
simple example
var obj = function(){
this.i = 0;
this.add = function(i){
this.i += i;
return this;
};
this.substract = function(i){
this.i -= i;
return this;
};
this.print = function(){console.log(this.i);};
};
var x = new obj();
x.add(3).substract(2).substract(2).print();
using closure
var obj = function(){
var i = 0; // i is private property
var add = function(j){
i += j;
return this;
};
var substract = function(j){
i -= j;
return this;
};
var print = function(){console.log(i);};
return { add:add, substract:substract, print:print};
};
var x = new obj();
x.add(3).substract(2).substract(2).print();
IMMEDIATELY INVOKED FUNCTION EXPRESSION(IIFE)
syntax -
(function(parameter){})(argument)
(function(parameter){}(argument))
!function(parameter){}(argument)
-function(parameter){}(argument)
makes the parameters as private
helps in providing closure
var counter = (function(){
var i=0;
return{
get:function(){return i},
set:function(value){i=value},
increment:function(){i++}
}
})();
console.log(counter.get()) // 0
console.log(counter.set(5))
console.log(counter.increment())
console.log(counter.get()) // 6
CALL, APPLY AND BIND
independent function with 'this' keyword
var addToThis = function(a, b, c){
return this.num + a + b + c;
}
call - addToThis.call({num:10}, 1, 2 , 3) // =>16
apply - addToThis.apply({num:10}, [1, 2 , 3]) // =>16. This takes array as second parameter
bind
return a function after binding the object with the addToThis()
var bound = addToThis.bind({num:10});
//console.dir(bound);
bound(1, 2, 3)
PROMISES
simple example
declaring promise
let promiseToCleanRoom = new Promise(function(resolve,reject){
let isCleaned = true;
// cleaning the room
if(isCleaned)
resolve('is cleaned');
else
reject('is not cleaned');
});
calling promise
promiseToCleanRoom.then(function(fromResolve){
console.log('the room ' + fromResolve);
}).catch(function(fromReject){
console.log('the room ' + fromReject);
});
nested example
let cleanRoom = function() {
return new Promise(function(resolve, reject) {
resolve('Cleaned Room');
});
};
let removeGarbage = function(message) {
return new Promise(function(resolve, reject) {
resolve(message + ' Removed Garbage');
});
};
let winIcecream = function(message) {
return new Promise(function(resolve, reject) {
resolve( message + ' Won Ice-cream');
});
};
// calling chain of promises
cleanRoom().then(function(result){
return removeGarbage(result);
}).then(function(result){
return winIcecream(result);
}).then(function(result){
console.log('finished ' + result);
});
// output => finished Cleaned Room Removed Garbage Won Ice-cream
Promise.all([promise1, promise2, ...]) - returns a promise with array of values
Promise.all([cleanRoom(), removeGarbage(), winIcecream()]) // output => ["Cleaned Room", "undefined Removed Garbage", "undefined Won Ice-cream"]
Promise.race([promise1, promise2, ...]) - returns any one promise which finishes first
Promise.race([cleanRoom(), removeGarbage(), winIcecream()]) // output => Cleaned Room"
Q&A
difference between 'var' and 'let' keywords
let introduced in ECMAscript 6
let has a block scope while var has function scope
var gets hoisted while let don't
difference between == and ===
both compare operator. object is compared as reference
== compares only value while === compares both value and typeof
difference between 'let' and 'const'
const can't be reassigned
const object can be modified but can't be reassigned
difference between null and undefined
both defines empty value
when declaring variable, undefined is automatically assigned
typeof null === 'object' and typeof undefined === 'undefined'
arrow function
alias of anonymous function
example 'without arrow'
const profile = {
name: 'no name',
setName: function(name){
let myWindowFunction = function(n){
this.name = n;
}
myWindowFunction(name);
}
}
profile.setName('John');
console.log(window.name); // =>'John'
console.log(profile.name); // =>'no name'
example 'with arrow'
const profile = {
name: 'no name',
setName: function(name){
let myArrowFunction = (n) => {
this.name = n;
}
myArrowFunction(name);
}
}
profile.setName('John');
console.log(window.name); // =>'John'
console.log(profile.name); // =>'John'
difference between function declaration and function expression
function funcD(){//function declaration} and let funcE = function(){//function expression}
function declaration is hoisted while expression not
setTimeout
the call back function get executed only when other commands in the stack are executed
example
setTimeout(function(){console.log('a')},0);
console.log('b');
console.log('c');
setTimeout(function(){console.log('a')},0);
console.log('b');
console.log('c');
// output => b c b c a a
EVENTS
bubbles event property returns a Boolean value that indicates whether or not an event is a bubbling event.
cancelBubble() -
this method prevents the event-flow from bubbling up to parent elements.
to prevent both bubbling up to parent elements and capturing down to child elements, use the stopPropagation() method instead.
stopPropagation() -
this method prevents propagation of the same event from being called.
propagation means bubbling up to parent elements or capturing down to child elements.
stopImmediatePropagation() - When clicking on a button, execute the first event handler, and stop the rest of the event handlers from being executed
currentTarget event property returns the element whose event listeners address the event
target event property returns the element that triggered the event.
eventPhase event property
returns a number that indicates which phase of the event flow is currently being evaluated.
The number is represented by 4 constants:
0. NONE
1. CAPTURING_PHASE - The event flow is in capturing phase
2. AT_TARGET - The event flow is in target phase, i.e. it is being evaluated at the event target
3. BUBBLING_PHASE - The event flow is in bubbling phase
isTrusted event property
returns a Boolean value indicating whether the event is trusted or not.
In Chrome, Firefox and Opera, the event is trusted if it is invoked by the user, and not trusted if it is invoked by a script.
In IE, all events are trusted except those that are created with the createEvent() method.
preventDefault() method
cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur
does not prevent further propagation of an event through the DOM. Use the stopPropagation() method to handle this.