Javascript Exception Handling and Block Binding

Silviaplabon
5 min readMay 6, 2021

try-catch-finally

The try/catch/finally statement is the exception-handling mechanism for javascript. The aim of the exception handling mechanism is to provide means of recognizing and reporting an ‘exceptional circumstance’ in order to take appropriate action.

A try/catch block is used mainly in JavaScript to handle errors. You use this when you don’t want an error in your script to break your code.

The role of try/catch is as follows:
try: program statements that you want to monitor for exceptions are contained in a try block.

catch: A catch statement involves declaring the type of exception you are trying to catch.

The try…catch construct has two main blocks: try, and then catch:

try {
// code may cause error
} catch(error){
// code to handle error
}

You can also add a throw or a clause with these statements in JavaScript. See what their role is.

throw: If an exception to be detected is thrown through a throw statement.

finally: This is an optional clause and is applicable in every circumstance.After the try block and catch-block(s) are completed, the final-block will run always. It always works, irrespective of whether or not an exception has been thrown.

Let one example will clear your confusion:

function getColor(colorName) {
if (colorName==”Red”) {
throw ‘RGB contain Red!’;
}
else if(colorName==”Green”){
throw ‘RGB contain Green’
}
else if(colorName==”Blue”){
throw ‘RGB contain Blue’
}
else{
throw ‘RGB doesn’t contain this color’
}
}
try {
getColor(Red);//Output will be RGB contain Red
}
catch (e) {
console.error(e);
}

Var Declarations and Hoisting

Hoisting is the process of treating variable declarations with var as if they were at the top of the function (or global scope if declared outside of a function). Find the following function specification for an example of what hoisting does:

function getValue(condition) {
if (condition) {
var value = “blue”;
return value;
}
else {
return null;
}
}

If you’re still not familiar with JavaScript, you might think that the variable value is only generated if the condition is valid. In reality, the variable value is generated irrespective of the situation. The JavaScript engine modifies the getValue function behind the scenes to look like this:

function getValue(condition) {
var value;
if (condition) {
value = “blue”;
return value;
}
else {
return null;
}
}

The declaration of value is moved to the top of the list, while the initialization stays put. That is, the variable’s value can still be accessed from inside the else clause. The variable will have an unknown value if accessed from there because it hasn’t been initialized.

It can take some time for new JavaScript developers to get used to declaration hoisting, and misinterpreting this peculiar behavior can lead to bugs. As a result, ECMAScript 6 adds block-level scoping options to make managing the lifecycle of a variable a little more efficient.

Block-level declarations are variables that are only available within the scope of a specific block. Block scopes are developed as follows:

  1. Inside of a function
  2. Inside of a block (indicated by the { and } characters)

Many C-based languages use block scoping, and the implementation of block-level declarations in ECMAScript 6 aims to give JavaScript the same flexibility (and uniformity).

Block Binding in Loops

Inside for loops, where the throwaway counter variable is intended to be used only within the loop, block-level scoping of variables is perhaps one of the most desired features by developers. In JavaScript, for example, it’s not unusual to see code like this:

for (var i=0; i < 10; i++) {
process(items[i]);
}
// i is still accessible here
console.log(i);

This example should function as expected in other languages where block-level scoping is the norm, and only the for loop should have access to the I variable. However, since the var declaration is hoisted in JavaScript, the variable I is still accessible after the loop is done. Instead, use let, as in the following code, to achieve the desired result:

for (let i=0; i < 10; i++) {
process(items[i]);
}
// i is not accessible here — throws an error
console.log(i)

The variable I only exists within the for loop in this case. The variable is destroyed until the loop is finished and is no longer available.

Global Block Bindings

Var behaves differently in global scope than let and const. When you use var in the global scope, for example, a new global variable is created, which is a property on the global object (in browsers, a window), but when you use let or const in the global scope, a new binding is created in the global scope but no property is applied to the global object (window in browsers). That means you can unintentionally overwrite an existing global with var, but you can’t overwrite with let or const. Here’s an illustration:

When var is used:

var greeting = ‘Hello, Good Morning’
console.log(window.greeting) // Hello, Good Morning
var person = ‘Hello there’
console.log(window.person) // Hello there

When let is being used:

let greeting = ‘Hello, Good Morning’
console.log(greeting) // Hello, Good Morning
console.log(window.greeting === greeting) // false
const person = ‘Hello there’
console.log(person) // Hello there
console.log(person in window) // false

Emerging Best Practices for Block Bindings

The convention used let instead of var during ES6 development and use const to limit the change. But as more developers are migrating, developers can change the variable value by following a convention using const as default and using.

Functions with Default Parameter Values

In ES5 and earlier a lot of additional code is required to simulate the default value. When the parameter is not officially passed when a function is called, ES6 makes it simpler to pass default parameter values. Examples include:

function add(num1, num2 = 0) {
return num1 + num2 }
console.log(add(20, 5)) // 25
console.log(add(20)) // 20

Working with Unnamed Parameters

Previous parameters passed without defining in JavaScript function are inspected by argument object. Although inspecting arguments works well in most cases, it can be somewhat difficult to work with this object. ES6 presents the remaining parameter to simplify working with unnamed parameters. The remaining parameter enables a variety of array arguments.

function add(…args) {// args is the name for the array
return args.reduce((accumulator, current) => accumulator + current, 0) }
console.log(add(5)) // 5
console.log(add(5, 3)) // 8
console.log(add(5, 2, 3)) // 10

block-level functions

ES6 allows block-level functions which are hoisted on top of the function or hoisted into the global scope. For example:

if (true) {
console.log(typeof doMath) // “function”
function doMath() {
// some code
}
doMath()
}
console.log(typeof doMath) // function

Arrow:

ES6 allows you to write a shorter arrow function syntax compared to a traditional function expression.

--

--

Silviaplabon

I'm a passionate and self-motivated software developer with about 1.5 years of experience