Let
let is similar to var but let has scope. let is only accessible in the block level it is defined.
example:
1 | if (true) { |
and
1 | let a = 50; |
Const
Const is used to assign a constant value to the variable. And the value cannot be changed. Its fixed.
example:
1 | const a = 50; |
Whenever you define a const variable, Javascript references the address of the value to the variable.
example:
1 | const LANGUAGES = ['Js', 'Ruby', 'Python', 'Go']; |
the variable ‘LANGUAGES’ actually references to the memory allocated to the array. So you cannot change the variable to reference some other memory location later. Throughout the program it only references to the array.
Arrow Function
1 | // Old Syntax |
and
1 | let NewOneWithParameters = (a, b) => { |
There are two things to explain here.
- If you have a function with single parameter, you don’t need (). In our case element is the parameter.
- And If you have single line as the body of the function you don’t need {} and also JS will implicitly returns the value after executing the function. You don’t have to use return keyword.
- Arrow functions shine best with anything that requires
this
to be bound to the context, and not the function itself.
For of loop
for..of iterates through list of elements (i.e) like Array and returns the elements (not their index) one by one.
1 | let arr = [2,3,4,1]; |
and
1 | let string = "Javascript"; |
Spread attributes
1 | let SumElements = (arr) => { |
consider the same example with spread attributes:
1 | let SumElements = (...arr) => { |
Math.max is a simple method that returns the maximum element from given list. It doesn’t accept an array.
1 | let arr = [10, 20, 60]; |
So lets use our savior:
1 | let arr = [10, 20, 60]; |
Maps
Map holds key-value pairs. It’s similar to an array but we can define our own index. And indexes are unique in maps.
1 | var map = new Map(); |
Sets
Sets are used to store the unique values of any type.
1 | var sets = new Set(); |
Static methods
1 | class Example { |
you can call the function without creating any instance for the class.
Getters and Setters
1 | class People { |
Promises
They are used to make async operations such as API request, file handling, downloading images, etc.
Before promises, programmers used to define callbacks. Callbacks are normal functions in Javascript which executes when the async operation is complete.
three states in promises
- Pending: In this state the promise is just executing the async operation. For example, It’s making some API request to the server or downloading some images from cdn. from this state promise can move to either to Fulfilled or to Rejected
- Fulfilled: If the promise has reached this state, then it means that the async operation is complete and we have the output. For example, we have the response from the API.
- Rejected: If the promise has reached this state, it means that the async operation is not successful and we have the error which caused the operation to fail.
1
2
3
4
5
6
7
8const apiCall = new Promise(function(resolve, reject) {
if ( API request to get some data ) {
resolve("The request is successful and the response is "+ response);
}
else {
reject("The request is not successful. The error is "+error);
}
});Then the resolve function is called if we get the response from the server. And if there is some error reject function is called with the error message.
We use handlers to get the output from the promise.
Handlers are just functions which executes when some event occurs such as clicking a button, moving the cursor, etc.
So we can use handlers to handle when the resolve function is called or **reject **function is called.
- The handler then executes its function parameter when the resolve function is called inside the promise.
1
2
3
4
5
6// calling the promise with some handlers.
apiCall.then(function(x) {console.log(x); })
// Output
The request is successful and the response is {name: "Jon Snow"}- Catch handler looks out for reject function.
1
2
3
4
5
6
7
8
9
10
11apiCall
.then(function(x) {
console.log(x);
})
.catch(function(x) {
console.log(x);
})
// Assuming the request is not successful ( reject function is called in the promise. )
Output:
The request is not successful
Async / Await
async
1 | async function hello() { |
The above code is equivalent to the below code:
1 | function hello() { |
example:
1 | async function hello(a, b) { |
Don’t forget that async function will return a promise. So of course, you can call resolve and reject function inside async function too.
example:
1 | async function Max(a, b) { |
await
It makes the Javascript to wait until you get the response from the endpoint. And then it resumes the execution.
await can be used only inside async function. It doesn’t work outside async function
1 | async function hello() { |
Array
Array Map
1 | let arr = [1,2,3,4,5]; |
And also note we have to return some value in the end. Which will be the modified value of that element. If you didn’t return anything then the particular element will be undefined.
One more thing I like to add is the second and third parameter is only optional. Only the first parameter is mandatory. for example :
1 | let modifiedArr = arr.map(function(element) { |
write the map operator with arrow functions:
1 | let modifiedArr = arr.map((element, index) => { |
better:
1 | let modifiedArr = arr.map(element => element * 10); |
Array Filter
1 | let arr = [1, 2, 3, 4, 5, 6] |
try by arrow function:
1 | let modifiedAarr = arr.filter((element, index) => element%2 == 0) |
we have to return a boolean value for each element of the array. If you won’t return any boolean value at the end then the filter takes it as false and deletes the element.
Array Reduce
Array reduce is used to aggregate all the elements of an array and return a single value.
1 | let arr = [1,2,3,4,5,6] |
Unlike filter and map, reduce takes a function with four parameters and also a additional element. Unlike filter and map, the first two parameters are mandatory. Other two are optional.
The first parameter is the aggregator element.In our case it’s 0.
Like filter and map you have to return the end result.
write the same code with arrow functions:
1 | let totalSum = arr.reduce((sum, element) => element+sum, 0) |
Template Literals
1 | let name = "Srebalaji"; |
Imports and Exports
1 | //app.js |
and:
1 | //app.js |
If you are using * to import values then you have to use alias (i.e) names that will refer to imported values. In our example we have used variables as alias.
Using * to import values doesn’t import default value. You have to import it separately.
for example:
import addition, * as variables from './app'
Destructuring objects and arrays
1 | let person = {firstName: "Jon", lastName: "Snow", age: 23} |
Extend and Super
1 | class Person{ |
And then we have used super keyword to call the constructor of the parent class. And we also have called the method declared in the parent class using super.
Generator functions
- Generator functions are written using the
function*
syntax. When called initially, generator functions do not execute any of their code, instead returning a type of iterator called a Generator. - When a value is consumed by calling the generator’s next method, the Generator function executes until it encounters the yield keyword.
- Each
yield
in a generator basically represents an asynchronous step in a more synchronous/sequential process — somewhat likeawait
in anasync
function.
- Each
- The function can be called as many times as desired and returns a new Generator each time, however each Generator may only be iterated once.
some method
includes
construct an array of the items, and use
includes
:1
['a', 'b', 'c'].includes('b')