forked from learning-zone/javascript-basics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiscellaneous.html
366 lines (324 loc) · 14.2 KB
/
miscellaneous.html
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
<!DOCTYPE html>
<html>
<head>
<title>Miscellaneous features in JavaScript</title>
</head>
<body>
<h1 id='divId'></h1>
</body>
<script>
/**
* ---------------------------------
* HTML Collections vs NodeLists
* ---------------------------------
*
* An HTMLCollection is a list of nodes. An individual node may be accessed by either ordinal index or the
* node’s name or id attributes. Collections in the HTML DOM are assumed to be live meaning that they are
* automatically updated when the underlying document is changed.
*
* A NodeList object is a collection of nodes. The NodeList interface provides the abstraction of an ordered
* collection of nodes, without defining or constraining how this collection is implemented. NodeList objects
* in the DOM are live or static based on the interface used to retrieve them
*
* **/
/**
* ------------------
* var this = self
* ------------------
*
* self is being used to maintain a reference to the original this even as the context is changing. It's a
* technique often used in event handlers (especially in closures).
*
* **/
var obj = {
outFunction: function() {
console.log('(this == obj): '+(this == obj)); // true
var self = this;
function innerFunction() {
console.log('(this == obj): ' + (this == obj)); //false
console.log('(self === obj): ' + (self === obj)); //true
}
return innerFunction;
}
}
// This code will return inner function and won't execute it
var inner = obj.outFunction();
inner(); // Invoke inner function
/**
* ---------------------------
* append() vs appendChild()
* ----------------------------
*
* The main difference is that appendChild() is a DOM function meanwhile append() is a JavaScript function.
*
* **/
var text = document.createTextNode('Miscellaneous features in JS');
document.getElementById("divId").appendChild(text);
document.getElementById("divId").append(' Example !!!');
/**
* ------------------------------
* dot notation vs brackets
* ------------------------------
*
* 1) Square bracket notation allows the use of characters that can't be used with dot notation:
* var foo = myForm.foo[]; // incorrect syntax
* var foo = myForm["foo[]"]; // correct syntax
*
* 2) square bracket notation is useful when dealing with property names which vary in a predictable way:
* for (var i = 0; i < 10; i++) {
* someFunction(myForm["myControlNumber" + i]);
* }
*
* 3) Square bracket notation allows access to properties containing special characters and selection of
* properties using variables
* var foo = myResponse.bar.Baz; // incorrect syntax
* var foo = myResponse["bar.Baz"]; // correct syntax
*
*
* * */
/**
* -------------------
* async vs defer
* -------------------
*
*
* <script src=script.js/>
*
* The HTML file will be parsed until the script file is hit, at that point parsing will stop and a request
* will be made to fetch the file. The script will then be executed before parsing is resumed.
*
* <script async src="script.js"/>
*
* async downloads the file during HTML parsing and will pause the HTML parser to execute it when it has
* finished downloading.
*
* <script defer src="script.js"/>
*
* defer downloads the file during HTML parsing and will only execute it after the parser has completed.
* defer scripts are also guaranteed to execute in the order that they appear in the document.
*
* **/
/**
* -------------------------------
* async() vs await() in ajax
* -------------------------------
*
*
* An async() function can contain an await() expression, which pauses the execution of the async() function and waits for the passed
* Promise's resolution, and then resumes the async() function's execution and returns the resolved value.
*
* **/
function resolve() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved after await() !!!');
}, 2000);
});
}
async function asyncCall() {
console.log('async() function calling !');
var result = await resolve();
console.log(result); // expected output: 'resolved'
}
asyncCall();
/* *
* --------------------
* Request.headers
* --------------------
*
* The headers read-only property of the Request interface contains the Headers object associated with the request.
*
* **/
var myRequest = new Request('flowers.jpg');
var myHeaders = myRequest.headers; // Headers {}
var myHeaders = new Headers();
myHeaders.append('Content-Type', 'image/jpeg');
var myInit = {
method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default'
};
var myRequest = new Request('flowers.jpg', myInit);
myContentType = myRequest.headers.get('Content-Type');
console.log('Request.headers: ' + myContentType); // returns 'image/jpeg'
/**
* -------------------------
* JavaScript Error Types
* -------------------------
*
* 1) EvalError:- Creates an instance representing an error that occurs regarding the global function eval().
* 2) InternalError:- Creates an instance representing an error that occurs when an internal error in the JavaScript
* engine is thrown. E.g. "too much recursion"
* 3) RangeError:- Creates an instance representing an error that occurs when a numeric variable or parameter is
* outside of its valid range.
* 4) ReferenceError:- Creates an instance representing an error that occurs when de-referencing an invalid reference.
* 5) SyntaxError:- Creates an instance representing a syntax error that occurs while parsing code in eval().
* 6) TypeError:- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
* 7) URIError:- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.
*
*
* Examples:-
*
* constt syntax = 'val' //SyntaxError
*
* const booleanVal = true;
* booleanVal.slice(-1); //TypeError
*
* const name = receivedName; //ReferenceError
*
* 'string'.repeat(-1); //RangeError
*
* decodeURIComponent('%'); //URIError
* **/
/**
* ------------------------------
* ViewState vs SessionState
* -------------------------------
*
* View State
*
* – Maintained at page level only.
* – View state can only be visible from a single page and not multiple pages.
* – Information stored on the client’s end only.
* – View state will retain values in the event of a postback operation occurring.
* – View state is used to allow the persistence of page-instance-specific data.
*
* Session State
*
* – Maintained at session level.
* – Session state value availability is in all pages available in a user session.
* – Information in session state stored in the server.
* – In session state, user data remains in the server. The availability of the data is
* guaranteed until either the user closes the session or the browser is closed.
* – Session state is used for the persistence of user-specific data on the server’s end.
*
* **/
// unshift() :- The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
var arr = [1, 2, 3];
console.log(arr.unshift(4, 5)); // expected output: 5
console.log('unshift(): ' + arr); // expected output: Array [4, 5, 1, 2, 3]
// shift() :- The shift() method removes the first element from an array and returns that removed element.
var arr = [1, 2, 3];
var firstElement = arr.shift();
console.log('shift(): ' + arr); // expected output: Array [2, 3]
console.log('firstElement: ' + firstElement); // expected output: 1
/**
* -----------------------------------
* firstchild vs firstelementchild
* -----------------------------------
*
* <ul id="myList">
* <li>Coffee</li>
* <li>Tea</li>
* </ul>
*
* var list = document.getElementById("myList").firstElementChild.innerHTML;
* console.log('firstElementChild: ' + list); //Coffee
*
*
* firstchild
*
* <ul id="myList"><li>Coffee</li><li>Tea</li></ul>
*
* var list = document.getElementById("myList").firstChild.innerHTML;
* console.log('firstChild: ' + list); //Coffee
*
* Note:- If you add whitespace before the first li element, the result will be "undefined".
* **/
/**
* -----------------
* History Object
* -----------------
*
* **/
window.history.back(); // Goes to the previous page in session history
window.History.forward() // Goes to the next page in session history
window.History.go() // Loads a page from the session history, identified by its relative location to the current page
window.History.pushState() // Pushes the given data onto the session history stack with the specified title and, if provided, URL
window.History.replaceState() // Updates the most recent entry on the history stack to have the specified data, title, and, if provided, URL
/**
* ---------------------------
* Shallow Copy vs Deep Copy
* ---------------------------
*
* Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object.
* If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
*
* A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied
* along with the objects to which it refers.
*
* **/
/**
*
* ----------------------
* Variable Shadowing
* -----------------------
*
***/
var x = 4;
function example() {
var x = 5; // x is shadowing the outer scope's x variable
}
/**
* -------------------
* Yield Keyword
* -------------------
*
* The yield keyword is used to pause and resume a generator function (function* or legacy generator function).
**/
function* foo(index) {
while (index < 5) {
yield index++;
}
}
const iterator = foo(0);
console.log(iterator.next().value); // expected output: 0
console.log(iterator.next().value); // expected output: 1
/**
* -------------------
* await Keyword
* -------------------
*
* The await operator is used to wait for a Promise. It can only be used inside an async function.
*
**/
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 20000);
});
}
async function f1() {
var x = await resolveAfter2Seconds(10);
console.log(x); // 10
}
f1();
/**
* -----------------
* in Operator
* -----------------
*
* The "in" operator returns true if the specified property is in the specified object or its prototype chain.
*
**/
var car = {make: 'Honda', model: 'Accord', year: 1998};
console.log('make' in car); // expected output: true
/**
* -----------------------
* instanceof Operator
* -----------------------
*
* The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
**/
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
var auto = new Car('Honda', 'Accord', 1998);
console.log(auto instanceof Car); // expected output: true
console.log(auto instanceof Object); // expected output: true
</script>
</html>