Importance of try, catch, spread operator, arrow function, default parameters, and clean code writing in javascript for beginners.

Syntax of try and catch:

try {} catch (err) {// error handling}
try {  
alert('Start of try runs'); //no errors here
.........;
alert('End of try runs'); //

} catch(err) {
alert('Catch is ignored, because there are no errors'); //
}
try {   alert('Start of try runs');
inis mona; // error ,a string without a variable!
alert('End of try ');
} catch(err) {
alert(`Error has occurred!`); //error is handled here
}

A Cleaner way to use for loop with if-else

let sum=0;
for(i=0;i<10;i++){
sum+=i;
}
let sum = 0 ; //spaces around operators
for (i = 0; i < 10; i++) { //add space after 'for'
sum += i; //use semicolon is best practice, beacuse it saves you from getting weird errors
}

For loop with nested if :

for (let i = 0; i <= 100; i++) {   
if (cond) {
..... // <- one more nesting level
}
}
for (let i = 0; i <= 100; i++) {   
if (!condition) continue;
}
function pow(x, n) {   
if (n < 0) {
alert("Negative 'n' not accepted");
return;
} else {

let result = 1;
for (let i = 0; i < n; i++) {
result *= x;
}
return result;
}
function pow(x, n) {   
if (n < 0) {
alert("Negative 'n' not accepted");
return;
}
let result = 1; for (let i = 0; i < n; i++) {
result *= x;
}
return result;
}

Use the spread operator and rest operator and get rid of the pains of writing extra code

const  values= [...value];

let arr = [1,2,3];
let arr2 = [4,5];
arr = arr.concat(arr2);console.log(arr); // [ 1, 2, 3, 4, 5 ]
let arr = [1,2,3];
let arr2 = [4,5];
arr = [...arr,...arr2];console.log(arr); // [ 1, 2, 3, 4, 5 ]
let arr = ['a','b','c'];
let arr2 = arr;
arr2.push('d');console.log(arr2); // output:["a", "b", "c", "d"]
console.log(arr); //output ["a", "b", "c", "d"]
let arr = ['a','b','c'];
let arr2 = [...arr];
console.log(arr); // [ 'a', 'b', 'c' ]arr2.push('d'); //inserting an element at the end of arr2console.log(arr2); // [ 'a', 'b', 'c', 'd' ]console.log(arr); // [ 'a', 'b', 'c' ]

Use Arrow function more and less normal function

function add(a, b) {
return a+b;
}
console.log(2,3) //5
const add =(a,b)=> a+b;
console.log(2,3) //5
const add =(a,b)=> ({result: a+b })console.log(2,3) //{result : 5}
function add (a, b){
return ({ result : a+b })
}
console.log(2,3) //{result : 5}

Use Default Parameters and handle undefined

function multiply(a, b = 1) {
return a * b;
}
console.log(multiply(5, 2));
// expected output: 10
console.log(multiply(5));
// expected output: 5

An Aspiring Mern Stack Developer