Essential JS coding terms and how to use them

1. JavaScript try/catch/finally Statement
While writing codes it is very common that error happens and to handle these errors JS have 4 statements. These are try, catch, throw and finally.
Syntax:
try {
Lines of code
}
catch(err) {
Lines of code to check errors
}
finally {
Lines of code which must be executed after try and catch
}
Example:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8">
<meta name=”viewport” content=”width=device-width, initial-scale=1.0">
<title>Error Handling</title>
</head>
<body>
<h3>Error Handling in JS</h3>
<p id=”errorMessage”></p>
<p id=”finally”></p>
<script type = “text/javascript”>
try
{
const result = Multiplication(10, 20); // Multiplication is not defined
}
catch(err){
document.getElementById(“error Message”).innerHTML = err;
}
finally{
document.getElementById(“finally”).innerHTML = “JS error check done!”;
}
</script>
</body>
</html>
2. JavaScript throw Statement
If we want to add custom error then the throw statement is required. Here is an example how can we use the throw statement in error handling.
<!DOCTYPE html>
<html lang=”en”><head>
<meta charset=”UTF-8">
<meta name=”viewport” content=”width=device-width, initial-scale=1.0">
<title>Throw error JS</title>
</head><body>
<p id=”demo”></p>
<p id=”errorMessage”></p>
<p id=”finally”></p><script type=”text/javascript”>
const number1 = 5, number2 = 5;
const sum = “SUM”;
document.getElementById(“demo”).innerHTML = sum;
try {
if (sum !== 10) throw “Result is not correct!”;
}
catch (err) {
document.getElementById(“errorMessage”).innerHTML = err;
}
finally{
document.getElementById(“finally”).innerHTML = “JS throw error check done!”;
}
</script>
</body></html>
3. JS Commenting
Sometimes its needed to add some comment in code to make it understandable to other coders. JavaScript allow codes to add comment in codes by two ways.
The first one is single line commenting and it starts with // sign and the comment continues till the end of the line. That means the execution does not occurred on the commented line.
Syntax:
// Add Comment
Example:
// Add two numbers
const number1 = 5;
const number2 = 10;
const sum = number1 + number2; // Sum is performed
The second way of commenting is multiline commenting and its needed when the coder wants to briefly write some lines about the code or some lines of codes which the coder does not want to execute.
Syntax:
/*
Add Comment Lines
Add Comment Lines
Add Comment Lines
*/
Example:
/*
const number1 = 5;
const number2 = 10;
const sum = number1 + number2;
*/const number1, number2, sum;
number1 = 5;
number2 = 10;
sum = number1 + number2;
Here the first block of codes will not be executed.
4. JavaScript Hoisting
One most significant default behavior of JavaScript is moving declarations to the top and it is called Hoisting. To avoid unexpected bugs all the variables should be at the beginning of every scope and it is the best practice.
To understand this topic lets see 2 examples. The result of the two examples will not be same because of the variables declaration.
Example:
<!DOCTYPE html>
<html><body><p id=”hoisting”></p>
<p id=”error”></p>
<script>
try {
const a = 10; // Initialize a
const b = 20; // Initialize b
display = document.getElementById(“hoisting”);
display.innerHTML = “a = “ + a + “ | b = “ + b;
}
catch(err){
document.getElementById(“error”).innerHTML = err;
}
</script></body></html>// Expected output: a = 10 | b = 20<!DOCTYPE html>
<html><body><p id=”hoisting”></p>
<p id=”error”></p>
<script>
try {
const a = 10; // Initialize a
display = document.getElementById(“hoisting”);
display.innerHTML = “a = “ + a + “ | b = “ + b;
const b = 20; // Initialize b
}
catch(err){
document.getElementById(“error”).innerHTML = err;
}
</script></body></html>// Expected output: ReferenceError: Cannot access ‘b’ before initialization
5. Block-Level Declarations
The Block-Level Declarations can be made with two ways. These are:
1.Inside of a function
2.Inside of a code block
let Declarations
Syntax for the let declaration syntax is as like as the syntax for var. To declare a variable one can basically replace var with let to declare a variable, but the limit is only the current code block.
Example:
function getValue(condition) {if (condition) {
let value = “black”;// existing codereturn value;
} else {// value doesn’t exist herereturn null;
}// value doesn’t exist here
}
6. Block Binding in Loops
For Block Binding in Loops we have to use let not var, cause var is being hoisted.
Follow the two examples below:
for (var i = 0; i < 10; i++) {
process(items[i]);
}// here i is still accessible
console.log(i); // 10
As the var declaration gets hoisted the variable i is still accessible after the loop is completed. To ignore this problem we can use let instead, as like as the following code:
for (let i = 0; i < 10; i++) {
process(items[i]);
}// here i is not accessible and an error occured here
console.log(i);
In this example, the variable i only exists within the for loop.
7. Functions with Default Parameter Values
To initialize functions with default values default parameters are used in ES6. A default parameter is used when an argument is either excluded or undefined. A default parameter can be anything from a number to another function.
function sum(a, b = 5) {
return a * b;
}console.log(sum(5, 2));
// expected output: 15console.log(sum(5));
// expected output: 10
8. The Spread Operator
In general, the Spread Operator doing the job of concatenation. Basically spread operator works as like as concat() method. It will give the output without changing the original value of the variable array where more than 1 values are expected.
For example:
const num1 = [1, 2, 3, 4, 5];
const num2 = [6, 7, 8, 9, 10];const num = […num1, …num2];
console.log(num) // expected output 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
9. Arrow Function
Arrow function is slightly different from a normal function and can’t be used in all situations.
With the comparison to traditional function it can be clearly understood.
For example in general function:
const x=7, y=8;
let sum = function(p, q){
return p + q
};
console.log(sum(x,y));
In arrow function:
const x=7, y=8;
let sum = (p, q) => {return p + q};
console.log(sum(x,y));
10. JS Coding Styles
Naming convention
Variable name and function name with camelCase format is recommended in JS.
Example:
let firstName = “John”;function multiplicationFunction(x, y) {
return x * y;
}
Space around operators
Space should be used around the operators and also after the commas.
Example:
const z = x + y;
const arr = [“a”, “b”, “c”];
Code indentation
2 spaces for indentation of code block.
const sum = function(p, q){
return p + q
};
Line length
If the line length of code is greater than 80 characters and it does not fit in one line, the best practice is to break the line in new line.
Example:
document.getElementById(“error”).innerHTML =
“JavaScript, often abbreviated as JS.”
Empty line between logical blocks
Example:
const x=7, y=8;let sum = (p, q) => {return p + q};console.log(sum(x,y));