Declaration of sleek, contemporary code becomes a cake-walk when you master these JavaScript keywords
Each programming language usually includes a syntax aimed at increasing developer productivity and a comprehensive standard library. A typical grammar specification in a programming language comprises various components like literals, identifiers, expressions, functions, classes, and the likes. These components often use special reserved terms or ‘keywords’ that cannot be used for customized identifiers. While learning a new programming language, the majority of developers don’t make it a point to memorize all these language-specific keywords. However, familiarizing oneself with all the keywords of a particular language can significantly augment your understanding of the language and enhance programming efficiency.
Contemporary JavaScript boasts around 46 implemented reserved keywords, along with several others that are yet to be implemented. Many of these originated from initial JavaScript editions, while the existing ECMAScript standards have also incorporated a multitude of fresh keywords. Familiar keywords to most programmers include if, else, return, for, while, and function. However, there are other keywords that don’t see frequent use as compared to the aforementioned fundamental ones.
In this narrative, I’m going to delve into some essential JavaScript terminology that, as an adept JavaScript programmer, you ought to be familiar with. Possessing knowledge of these terms, beyond the commonly-used ones, aids in crafting tidy JavaScript coding efficaciously, eliminating the need to trawl through tech forums. Furthermore, these key terminologies can serve as a tool for seasoned developers to assess the proficiency of their peers in the JavaScript language during technical evaluations. These terms also encourage you to further explore the intricate inner workings of JavaScript.
static
In the pre-ES6 era, programmers implemented basic object-oriented programming (OOP) concepts in JavaScript by adopting the prototype-based paradigm. In this approach, function definitions served the purpose of classes, attaching methods to the prototype object. When objects were instantiated, these prototypes provided the necessary methods and fields. TypeScript found favor among some developers due to its superior OOP support. However, ES6 introduced contemporary and programmer-friendly terminologies to define OOP classes, even boasting advanced OOP functionalities that rival TypeScript.
Familiar OOP JavaScript terms include class
, extends
, new
, this
, and super
. You can assign private properties within classes using the #
prefix.
The static keyword helps determine static properties in JavaScript classes:
class BasicLoan {
static INTEREST_RATE = 13.5;
static details() {
console.log(`Interest Rate : ${BasicLoan.INTEREST_RATE}%`);
console.log(`Availability : Confirmed`);
}
}
BasicLoan.details();
#
prefix:
static #INTEREST_RATE = 13.5;
debugger
Debugging is a crucial process in creating software systems devoid of bugs. A simple console.log
statement is useful in spotting an error in less intricate build scenarios, however, for more demanding modules, tailored debugger instruments are required. Chrome DevTools is a popular choice amongst developers for managing debugging-related tasks by placing breakpoints within the codes.
Traditionally, breakpoints are manually established using the DevTools interface to initiate the debugging process. Conversely, the debugger
keyword has the capability to automatically set a breakpoint at a chosen location, thus, the browser debugger interrupts at the specific code line only when the debugger interface is active.
Examine the code snippet below:
const numbers = [1, 2, 4, 5];
const reversedNumbers = numbers.slice().reverse();
debugger;
console.log(numbers, reversedNumbers);
On running this script on Chrome, DevTools autonomously allows you to review the code situated around the debugger
keyword by pausing the code at the exact line where debugger was inserted.
Debugging is instrumental in eradicating software bugs, thereby enhancing the product’s quality.
instanceof
JavaScript employs the notion of prototypes to acquire the characteristics of objects from predefined templates, commonly referred to as prototypes. The prototype of the object, often termed as its creating template, is automatically adjoined to its proto property by JavaScript after a bare object is established. This approach forms a prototype chain and paves the way to apply fundamental OOP concepts such as class inheritance.
The instanceof
operator contrasts the prototype of an object with a provided creator, as exemplified in the code below:
const currentDate = new Date();
console.log(currentDate instanceof Date); // returns true
class Vehicle {}
const myVehicle = new Vehicle();
console.log(myVehicle instanceof Vehicle); // returns true
class SportsCar extends Vehicle {}
const mySportsCar = new SportsCar();
console.log(mySportsCar instanceof Vehicle); // returns true
As evident from the given examples, the instanceof
operator can be utilized to verify if an object is a product of a specific class or function. However, manually changing prototype fields can lead to unpredictable consequences.
finally
Developers deploy different error-handling strategies in their software’s source code. Those programming in intermediate-level languages typically utilize methods centred around error-codes, whereas contemporary languages like JavaScript promote the use of a try-catch-based approach to error management.
In the realm of JavaScript development, a common feature often used is a universal try-catch block, but surprisingly, many developers overlook the combination of try-catch-finally.
The importance of the finally
block lies in its operation regardless of an exception thrown by the catch block. This unique feature allows for the inclusion of tidying up code, ensuring its execution within the finally
block.
Consider the following exemplary excerpt of a code:
function convertDigitToWord(num) {
if (num < 0 || num > 3)
throw new Error('Invalid or unsupported digit');
return ['zero', 'one', 'two', 'three'][num];
}
try {
console.log(convertDigitToWord(0));
console.log(convertDigitToWord(8));
} catch (error) {
console.log(error.message);
} finally {
console.log('Process completed');
}
In the above-mentioned code, Process completed
gets printed post the execution of codes in both the try and catch blocks. When dealing with swift automation scripts, the catch block can be omitted, resorting to a try-finally approach as shown below:
try {
console.log(convertDigitToWord(0));
console.log(convertDigitToWord(8)); // throws
console.log(convertDigitToWord(2));
} finally {
console.log('This block always executes');
}
console.log('This line will not be executed');
do
It’s common to repeatedly use code fragments with conventional loop structures. We often resort to using the for
loop structure when working with list iteration and situations where the start and end points are well-defined (like processing a part of an array). Conversely, the while
loop structure is handy when we need to repeat code but the end point is not foreseeable (such as when drawing data from a stream).
The while
loop runs the interior commands only if the condition turns out to be true. However, the do-while loop has a unique trait — it carries out its operation at least once, even if the criteria is false right from the outset:
let counter = 0;
let numberArray = [];
do {
numberArray.push(counter);
counter++;
} while(counter > 0 && counter < 5);
console.log(numberArray); // [0, 1, 2, 3, 4]
While the while loop is generally preferred for its comprehensibility, there might arise instances when the do-while
loop proves to be a superior choice!
void
Possessing over a decade’s worth of web development experience, you surely recall the useful role played by the void
operator during various development situations. Although the use of javascript:
pseudo protocol format is not endorsed in contemporary web development, it’s undeniable that previous developers have heavily utilized it for crafting hyperlinks that execute JavaScript. Such hyperlinks followed a method of execution similar to this:
The exclusion of the void operator from this script would result in the replacement of document content instead of altering the document title.
This occurrence is due to the browser’s alteration of document content with output data returned from the javascript:
pseudo protocol. The line of code in this context returns Hi
from the assignment.
The function of the void
operator is to execute a code statement and return undefined. In this case, the returned undefined value avoids unnecessary tampering with the document content.
Previous developers also devised links that essentially remain inactive, using this method:
Moreover, it’s notable that one parenthesis pair in an IIFE can be omitted by employing the void operator:
void function() {
console.log('Hi');
}();
Inquiring about the void
keyword can serve as an effective measure to determine whether a developer has experience that extends beyond the old JQuery era.
yield
The generator function, an innovative concept in JavaScript, was introduced with ES6. This innovative feature explores further than the conventional function ideas, offering a method to write functions that can be resumed and continued. These generator functions adhere to the standard iterator protocol, allowing developers to produce new values utilizing the yield
keyword. The yield
keyword enables you to pause and generate a fresh result from a generator function.
Consider this example code snippet:
function* squaredNumbersGenerator(n) {
for(let i = 1; i <= 4; i++) {
yield i ** 2;
}
}
let numberIterator = squaredNumbersGenerator(1);
console.log(numberIterator.next().value); // 1
console.log(numberIterator.next().value); // 4
console.log(numberIterator.next().value); // 9
console.log(numberIterator.next().value); // 16
console.log(numberIterator.next().value); // undefined
In the code above, the yield
keyword is instrumental in halting the for loop and delivering the next squared number when the iterator protocol’s next() method is activated. The for-of loop makes it easy to retrieve every value generated as noted below:
let numberIterator = squaredNumbersGenerator(1);
for (let num of numberIterator) {
console.log(num);
}
delete
The utilization of JavaScript objects is a common occurrence in our programming scripts, making object modification a consistent necessity in JavaScript platforms. With the standard .
notation, introducing or altering object properties is a simple task. The delete
command serves the purpose of eliminating a specific attribute from a JavaScript object:
Consider this example:
let documentInfo = {
id: 100,
title: 'My title',
size: 'A2',
content: ''
};
delete documentInfo.content;
console.log(Object.keys(documentInfo).length); // 3
Erasing an element from an array does not alter its size; instead, it clears the chosen element. Therefore, it’s best to employ the built-in splice
method to properly excise an element:
Consider an array of numbers:
let numberArray = [1, 2, 1, 0];
delete numberArray[1];
console.log(numberArray[1]); // undefined
console.log(numberArray.length); // 4
numberArray.splice(1, 1); // Remove the element at index 1
console.log(numberArray); // [1, 1, 0]
Upon more exploration, you’ll notice that delete
operates as an unset operator within the browser console. However, using delete
to unset variables isn’t advised as it’s impossible to remove variables in JavaScript’s strict mode.