Importance of try, catch, spread operator, arrow function, default parameters, and clean code writing in javascript for beginners.
What is try and catch?
well, try and catch are called error handling methods. why we need this? Because none one wants the script to be crashed. But there’s a syntax construct try..catch
that allows us to “catch” errors so the script can do something more reasonable. Errors are the most common friends in our daily life. we have to meet and deal with them. some can be handle in run time, some may not and some may occur in a specific situation. But as a good programmer, we should deal with every type of error that can occur. Enough talk !. let’s dive into it.
Syntax of try and catch:
try {} catch (err) {// error handling}
How does it work?
- First, the code in
try {...}
is executed. - If there were no errors, then
catch(err)
is ignored: the execution reaches the end oftry
and goes on, skippingcatch
. - If an error occurs, then the
try
execution is stopped, and control flows to the beginning ofcatch(err)
. Theerr
variable (we can use any name for it) will contain an error object with details about what happened.
Let’s look at another example:
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'); //
}
Another Example where the error is present:
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
}
Caution:
try..catch
only works for runtime errors.
For try..catch
to work, the code must be runnable. In other words, it should be a valid JavaScript.
It won’t work if the code is syntactically wrong, these types of errors recalled parsing error. Because the javascript engine reads it first, runs it, and will not understand. In another word, it is an invalid javascript.
A Cleaner way to use for loop with if-else
As a beginner, we love to use for loop everywhere in our logic, because it is much easier to understand in comparison to while loop. And we use if-else statement inside of a for loop to check the condition and do something depends on it So why not learn and use it in a cleaner way? In the future, you will need to learn how to write clean code. So why not practice from today? enough of talking again, let’s see some examples.
Normal for loop :
let sum=0;
for(i=0;i<10;i++){
sum+=i;
}
Cleaner way to write:
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 :
we should always try to avoid nesting for loop too many levels deep. Because it is hard for other developers to read your code.
For example, in the loop, it’s good to use the “ continue“ statement to avoid extra nesting.
For example,
Normal way:
for (let i = 0; i <= 100; i++) {
if (cond) {
..... // <- one more nesting level
}
}
Cleaner Way:
for (let i = 0; i <= 100; i++) {
if (!condition) continue;
}
So, we can see adding a continue statement removes two curly braces and increases the readability of code.
Let’s see another example with an if-else and return statement.
Usual Style:
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;
}
Cleaner style:
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;
}
As we can see using one return statement, we do not need to write else blocks because if the condition is false, it will return to the loop will not execute the rest of the lines.
Use the spread operator and rest operator and get rid of the pains of writing extra code
The spread operator is a new addition to the set of operators in JavaScript ES6. It takes in an iterable (e.g an array) and expands it into individual elements. It also allows us the privilege to obtain a list of parameters from an array. Syntax of Spread operator is the same as the rest operator but it works completely opposite of it.
Syntax:
const values= [...value];
Let’s look at why we love spread operator and how to use it ?
Use Spread more and Less Concat()
The normal way to concat two arrays with Conact() method:
let arr = [1,2,3];
let arr2 = [4,5];arr = arr.concat(arr2);console.log(arr); // [ 1, 2, 3, 4, 5 ]
Let the spread operator do the concat job
let arr = [1,2,3];
let arr2 = [4,5];arr = [...arr,...arr2];console.log(arr); // [ 1, 2, 3, 4, 5 ]
looks so simple right? love it? But read the line below…
Caution: Though we can achieve the same result, but it is not recommended to use the spread in this particular case, as for a large data set it will work slower as when compared to the native concat() method.
So when to use rest and when to concat ?
Depending on the size of the data set.For small dataset go with spread and for large dataset go with concat.
Use Spread and not affect the original array :
Let’s look at the example below
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"]
Copying in this method and push element into it affects the original array. we can solve this spread operator. Let’s look how..
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' ]
We can see the spread operator did not affect the original array.
Use Arrow function more and less normal function
Arrow Function looks yummier in comparison with normal functions but not replaceable fully. There is some situation when we have to use normal functions instead of arrow functions especially with “this” operator.
Let’s look at some examples where it’s best to use arrow function instead of an arrow.
function add(a, b) {
return a+b;
}console.log(2,3) //5
Let’s look the same with an arrow function
const add =(a,b)=> a+b;
console.log(2,3) //5
Using the arrow function we are able to remove those curly braces and return statement.
You can also return it as an object format with arrow function
const add =(a,b)=> ({result: a+b })console.log(2,3) //{result : 5}
wheres using normal function would be like this:
function add (a, b){
return ({ result : a+b })
}console.log(2,3) //{result : 5}
Use Default Parameters and handle undefined
Default function parameters allow named parameters to be initialized with default values if no value or “undefined ” is passed.
function multiply(a, b = 1) {
return a * b;
}console.log(multiply(5, 2));
// expected output: 10console.log(multiply(5));
// expected output: 5
If we approach it with if statement we had to write extra code and check the condition for it.