10 Exciting Topics You Need to Learn to Make Your Knowledge More Stronger in JS Part-1
Arrow Function
Arrow function is the newest feature in the ES6 version of JavaScript. It allows creating function more cleanly.
An arrow function doesn’t need function keyword. This type of function declares under a variable which is the function name. Then bracket parenthesis needs to pass arguments. If there is only one argument then no need for bracket parenthesis.
The Spread Operator(…)
The spread operator is a new addition to the features available in the JavaScript ES6 version. The spread operator is used to expand or spread an iterable or an array. For example,
const arr = ['My', 'name', 'is', 'Genius'];
console.log(arr); //output:["My", "name", "is", "Genius"]
console.log(...arr); //output: My name is Genius
You can also use the spread syntax ...
to copy the items into a single array. For example
const arr1 = ['one', 'two'];
const arr2 = [...arr1, 'three', 'four', 'five'];
console.log(arr2);
// Output: ["one", "two", "three", "four", "five"]
Default Parameters
The concept of default parameters is a new feature introduced in the ES6 version of JavaScript. This allows us to give default values to function parameters. Let’s take an example,
function sum(x = 3, y = 5) {
return x + y;
}
console.log(sum(5, 15)); output:20
console.log(sum()); output: 8
Also, function can be passed as a default parameter
function sum(x = 1, y = x, z = x + y) {
console.log( x + y + z );
}
sum(); output:4
try …catch method
The try...catch
statement is used to handle the exceptions. Its syntax is:
try {
// body of try
}
catch(error) {
// body of catch
}
The main code is inside the try block. While executing the try block, if any error occurs, it goes to the catch block. The catch block handles the errors as per the catch statements.
If no error occurs, the code inside the try block is executed and the catch block is skipped.
const a= 100,b;
try {
console.log(a/b);
console.log(a); //if b=0 then it gives an error then catch will execute
}
catch(error) {
console.log('An error caught');
}
Hoisting
Hoisting in JavaScript is a behavior in which a function or a variable can be used before declaration. For example,
console.log(a); // undefined
var a;
The above program works and the output will be undefined. The above program behaves as
var a;
console.log(a); // undefined