ECMAScript 2 (ES2) was the second official release of the language, published in 1998. In this article, we’ll explore the features and capabilities of ECMAScript 2, along with code examples.
The main goal of ES2 was to standardize the features that were already present in most web browsers at the time, including Netscape Navigator and Microsoft Internet Explorer.
New Features in ECMAScript 2:
Reserved Words
ES2 introduced a set of reserved words that were not used in the language before, including “do”, “in”, and “void”. These words could no longer be used as variable or function names.
// The following code will generate an error
var in = 10;
Lexical Conventions
ES2 standardized the syntax and layout of JavaScript code. This included rules for white space, line breaks, and comments. The goal was to make code easier to read and understand.
Type Conversion
ES2 introduced a set of functions for converting between data types, such as “Number()”, “String()”, and “Boolean()”. These functions allowed developers to easily convert data from one type to another, as needed.
var num = "10";
var numInt = Number(num); // Convert to number
var numStr = String(numInt); // Convert to string
Object Enhancements
ES2 introduced several enhancements to the “Object” data type, including the “prototype” property and the “constructor” property. These features allowed developers to create custom objects and define inheritance relationships between them.
// Define a new object constructor
function Person(name, age) {
this.name = name;
this.age = age;
}
// Add a method to the object's prototype
Person.prototype.sayHello = function() {
console.log("Hello, my name is " + this.name + ".");
};
// Create a new object
var person = new Person("John", 30);
// Call the object's method
person.sayHello();
Regular Expressions
ES2 introduced a new syntax for regular expressions, which are a powerful tool for matching and manipulating text. Regular expressions are defined using a pattern of characters and special symbols and can be used for tasks such as data validation and string manipulation.
// Test if a string contains a valid email address
var email = "john.doe@example.com";
var pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (pattern.test(email)) {
console.log("Valid email address");
} else {
console.log("Invalid email address");
}
Conclusion
ECMAScript 2 standardized many important features of the JavaScript language, making it easier for developers to create and maintain web applications. While many of the features introduced in ES2 are now considered basic, they provided the foundation for the many advancements and improvements that would come in later versions of the language.