Skip to content

Commit e19c53c

Browse files
authored
Important JS topics (#8)
1 parent 516b90d commit e19c53c

File tree

1 file changed

+333
-0
lines changed

1 file changed

+333
-0
lines changed

Js topics.md

+333
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,333 @@
1+
# Must learn topics in JAVA SCRIPT
2+
3+
## NOTE: ES6 (most important in JavaScript)
4+
5+
### JAVA SCRIPT:
6+
> JavaScript is a programming language that powers the dynamic behavior on most websites. Alongside HTML and CSS, it is a core technology that makes the web run.
7+
<ol>
8+
<li>Var, let, const</li>
9+
<li>Interactions: Alert, Prompt, Confirm</li>
10+
<li>Functions
11+
<ul>
12+
<li>Arrow function</li>
13+
<li>IIFE function</li>
14+
</ul>
15+
</li>
16+
<li>Object method , this</li>
17+
<li>New operator</li>
18+
<li>JSON methods
19+
<ul>
20+
<li>JSON.parse</li>
21+
<li>JSON.stringify</li>
22+
</ul>
23+
</li>
24+
<li>Prototype
25+
<ul>
26+
<li>Prototypal Inheritance</li>
27+
<li>F.Prototype</li>
28+
<li>Native prototypes</li>
29+
<li>Prototype methods, objects without __proto__</li>
30+
</ul>
31+
</li>
32+
<li>Callbacks
33+
<ul>
34+
<li>Callback hell</li>
35+
</ul>
36+
</li>
37+
<li>Promise
38+
<ul>
39+
<li>Promise Chaining</li>
40+
<li>Promise.all</li>
41+
<li>Promise.allSettled</li>
42+
<li>Promise.race</li>
43+
<li>Promise.resolve/reject</li>
44+
</ul></li>
45+
<li>Implicit Try....Catch</li>
46+
<li>Regular Expressions</li>
47+
<li>Closures</li>
48+
<li>Arrays</li>
49+
<li>Fake namespaces</li>
50+
<li>DOM manipulation</li>
51+
<li>Event Handlers</li>
52+
<li>Fetch Api</li>
53+
<li>Get</li>
54+
<li>Post (error is coming in it)</li>
55+
<li>JQuery
56+
<ul>
57+
<li>Events</li>
58+
<li>Effects</li>
59+
<li>Selectors</li>
60+
<li>HTML</li>
61+
<li>CSS</li>
62+
<li>DOM</li>
63+
</ul></li>
64+
<li>AJAX
65+
<ul>
66+
<li>XML Http</li>
67+
<li>Request</li>
68+
<li>Response</li>
69+
</ul></li>
70+
</ol>
71+
72+
## Keywords
73+
74+
### let Keyword
75+
> let creates a local variable in JavaScript & can be re-assigned. Initialization during the declaration of a let variable
76+
> is optional. A let variable will contain undefined if nothing is assigned to it
77+
> - eg. let count;
78+
79+
### const Keyword
80+
> A constant variable can be declared using the keyword const. It must have an assignment. Any attempt of re-assigning a const variable will result in JavaScript runtime error.
81+
> - eg. const numberOfColumns = 4;
82+
83+
## Promises
84+
85+
#### States of a JavaScript Promise
86+
```
87+
const promise = new Promise((resolve, reject) => {
88+
const res = true;
89+
// An asynchronous operation.
90+
if (res) {
91+
resolve('Resolved!');
92+
}
93+
else {
94+
reject(Error('Error'));
95+
}
96+
});
97+
98+
promise.then((res) => console.log(res), (err) => alert(err));
99+
```
100+
>A JavaScript Promise object can be in one of three states: pending, resolved, or rejected.
101+
102+
> While the value is not yet available, the Promise stays in the pending state. Afterwards, it transitions to one of the two states: resolved or rejected.
103+
104+
>A resolved promise stands for a successful completion. Due to errors, the promise may go in the rejected state.
105+
106+
>In the given code block, if the Promise is on resolved state, the first parameter holding a callback function of the then() method will print the resolved value. Otherwise, an alert will be shown.
107+
108+
### Avoiding nested Promise and .then()
109+
```
110+
const promise = new Promise((resolve, reject) => {
111+
setTimeout(() => {
112+
resolve('*');
113+
}, 1000);
114+
});
115+
116+
const twoStars = (star) => {
117+
return (star + star);
118+
};
119+
120+
const oneDot = (star) => {
121+
return (star + '.');
122+
};
123+
124+
const print = (val) => {
125+
console.log(val);
126+
};
127+
128+
// Chaining them all together
129+
promise.then(twoStars).then(oneDot).then(print);
130+
```
131+
> In JavaScript, when performing multiple asynchronous operations in a sequence, promises should be composed by chaining multiple .then() methods. This is better practice than nesting.
132+
133+
> Chaining helps streamline the development process because it makes the code more readable and easier to debug.
134+
### Chaining multiple .then() methods
135+
```
136+
const promise = new Promise(resolve => setTimeout(() => resolve('dAlan'), 100));
137+
138+
promise.then(res => {
139+
return res === 'Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?')
140+
}).then((res) => {
141+
console.log(res)
142+
}, (err) => {
143+
alert(err)
144+
});
145+
```
146+
> The .then() method returns a Promise, even if one or both of the handler functions are absent. Because of this, multiple .then() methods can be chained together. This is known as composition.
147+
148+
> In the code block, a couple of .then() methods are chained together. Each method deals with the resolved value of their respective promises.
149+
## Async-await
150+
### Resolving JavaScript Promises
151+
```
152+
let promise1 = Promise.resolve(5);
153+
let promise2 = 44;
154+
let promise3 = new Promise(function(resolve, reject) {
155+
setTimeout(resolve, 100, 'foo');
156+
});
157+
158+
Promise.all([promise1, promise2, promise3]).then(function(values) {
159+
console.log(values);
160+
});
161+
// expected output: Array [5, 44, "foo"]
162+
```
163+
> When using JavaScript async...await, multiple asynchronous operations can run concurrently. If the resolved value is required for each promise initiated, Promise.all() can be used to retrieve the resolved value, avoiding unnecessary blocking.
164+
165+
### Async Await Promises
166+
```
167+
function helloWorld() {
168+
return new Promise(resolve => {
169+
setTimeout(() => {
170+
resolve('Hello World!');
171+
}, 2000);
172+
});
173+
}
174+
175+
async function msg() {
176+
const msg = await helloWorld();
177+
console.log('Message:', msg);
178+
}
179+
180+
msg(); // Message: Hello World! <-- after 2 seconds
181+
```
182+
> The async...await syntax in ES6 offers a new way write more readable and scalable code to handle promises. It uses the same features that were already built into JavaScript.
183+
184+
### JavaScript async…await advantage
185+
> The JavaScript async...await syntax allows multiple promises to be initiated and then resolved for values when required during execution of the program. As an alternate to chaining .then() functions, it offers better maintainablity of the code and a close resemblance synchronous code.
186+
187+
### Async Function Error Handling
188+
```
189+
let json = '{ "age": 30 }'; // incomplete data
190+
191+
try {
192+
let user = JSON.parse(json); // <-- no errors
193+
alert( user.name ); // no name!
194+
} catch (e) {
195+
alert( "Invalid JSON data!" );
196+
}
197+
```
198+
> JavaScript async functions uses try...catch statements for error handling. This method allows shared error handling for synchronous and asynchronous code.
199+
200+
## Requests
201+
202+
### HTTP GET request
203+
204+
> HTTP GET requests are made with the intention of retrieving information or data from a source (server) over the web.
205+
206+
> GET requests have no body, so the information that the source requires, in order to return the proper response, must be included in the request URL path or query string.
207+
208+
### Asynchronous calls with XMLHttpRequest
209+
```
210+
const xhr = new XMLHttpRequest();
211+
xhr.open('GET', 'mysite.com/api/getjson');
212+
```
213+
> AJAX enables HTTP requests to be made not only during the load time of a web page but also anytime after a page initially loads. This allows adding dynamic behavior to a webpage. This is essential for giving a good user experience without reloading the webpage for transferring data to and from the web server.
214+
215+
> The XMLHttpRequest (XHR) web API provides the ability to make the actual asynchronous request and uses AJAX to handle the data from the request.
216+
217+
> The given code block is a basic example of how an HTTP GET request is made to the specified URL.
218+
219+
### The query string in a URL
220+
```
221+
const requestUrl = 'http://mysite.com/api/vendor?name=kavin&id=35412';
222+
```
223+
> Query strings are used to send additional information to the server during an HTTP GET request.
224+
225+
> The query string is separated from the original URL using the question mark character ?.
226+
227+
> In a query string, there can be one or more key-value pairs joined by the equal character =.
228+
229+
> For separating multiple key-value pairs, an ampersand character & is used.
230+
231+
> Query strings should be url-encoded in case of the presence of URL unsafe characters.
232+
233+
### XMLHttpRequest GET Request Requirements
234+
```
235+
const req = new XMLHttpRequest();
236+
req.responseType = 'json';
237+
req.open('GET', '/myendpoint/getdata?id=65');
238+
req.onload = () => {
239+
console.log(xhr.response);
240+
};
241+
242+
req.send();
243+
```
244+
> The request type, response type, request URL, and handler for the response data must be provided in order to make an HTTP GET request with the JavaScript XMLHttpRequest API.
245+
246+
> The URL may contain additional data in the query string. For an HTTP GET request, the request type must be GET.
247+
248+
### HTTP POST request
249+
> HTTP POST requests are made with the intention of sending new information to the source (server) that will receive it.
250+
251+
> For a POST request, the new information is stored in the body of the request.
252+
253+
### HTTP POST request with the XMLHttpRequest API
254+
```
255+
const data = {
256+
fish: 'Salmon',
257+
weight: '1.5 KG',
258+
units: 5
259+
};
260+
const xhr = new XMLHttpRequest();
261+
xhr.open('POST', '/inventory/add');
262+
xhr.responseType = 'json';
263+
xhr.send(JSON.stringify(data));
264+
265+
xhr.onload = () => {
266+
console.log(xhr.response);
267+
};
268+
```
269+
> To make an HTTP POST request with the JavaScript XMLHttpRequest API, a request type, response type, request URL, request body, and handler for the response data must be provided. The request body is essential because the information sent via the POST method is not visible in the URL. The request type must be POST for this case. The response type can be a variety of types including array buffer, json, etc.
270+
271+
### JSON Formatted response body
272+
```
273+
fetch('url')
274+
.then(
275+
response => {
276+
console.log(response);
277+
},
278+
rejection => {
279+
console.error(rejection.message);
280+
);
281+
```
282+
> The .json() method will resolve a returned promise to a JSON object, parsing the body text as JSON.
283+
284+
### promise url parameter fetch api
285+
```
286+
287+
fetch('url')
288+
.then(
289+
response => {
290+
console.log(response);
291+
},
292+
rejection => {
293+
console.error(rejection.message);
294+
);
295+
```
296+
> A JavaScript Fetch API is used to access and manipulate requests and responses within the HTTP pipeline, fetching resources asynchronously across a network.
297+
298+
> A basic fetch() request will accept a URL parameter, send a request and contain a success and failure promise handler function.
299+
300+
> In the example, the block of code begins by calling the fetch() function. Then a then() method is chained to the end of the fetch(). It ends with the response callback to handle success and the rejection callback to handle failure.
301+
The example block of code shows .json() method that returns a promise that resolves to a JSON-formatted response body as a JavaScript object.
302+
303+
### async await syntax
304+
```
305+
const getSuggestions = async () => {
306+
const wordQuery = inputField.value;
307+
const endpoint = `${url}${queryParams}${wordQuery}`;
308+
try{
309+
const response = __~await~__ __~fetch(endpoint, {cache: 'no-cache'});
310+
if(response.ok){
311+
const jsonResponse = await response.json()
312+
}
313+
}
314+
catch(error){
315+
console.log(error)
316+
}
317+
}
318+
```
319+
> The async…await syntax is used with the JS Fetch API fetch() to work with promises. In the code block example we see the keyword async placed the function. This means that the function will return a promise. The keyword await makes the JavaScript wait until the problem is resolved.
320+
321+
322+
### Good Resources to learn JavaScript:
323+
324+
1. https://javascript.info/
325+
2. https://www.w3schools.com/js/DEFAULT.asp
326+
3. https://www.codecademy.com/learn/introduction-to-javascript
327+
328+
329+
330+
331+
332+
333+

0 commit comments

Comments
 (0)