Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why is 'class' a reserved word in JavaScript?
The class keyword is a reserved word in JavaScript because it was designated as a "future reserved word" in ECMAScript 5 and later implemented in ECMAScript 6 (ES2015) to introduce class-based object-oriented programming.
Future Reserved Words in ECMAScript 5
ECMAScript 5 specification defined several future reserved words to allow for possible language extensions:
class enum extends super const export import
These words were reserved in ECMAScript 5 even though they had no functionality yet, ensuring they would be available for future language features without breaking existing code.
Implementation in ECMAScript 6
In ECMAScript 6 (ES2015), the class keyword was officially implemented to provide syntactic sugar for JavaScript's prototype-based inheritance:
Syntax
class ClassName [extends ParentClass] {
// class body
}
Example: Basic Class Declaration
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name} and I'm ${this.age} years old`;
}
}
const john = new Person("John", 25);
console.log(john.greet());
Hello, I'm John and I'm 25 years old
Example: Class with Inheritance
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}
class Dog extends Animal {
speak() {
return `${this.name} barks`;
}
}
const dog = new Dog("Buddy");
console.log(dog.speak());
Buddy barks
Why Reserve Keywords in Advance?
JavaScript engines reserve keywords early to:
- Prevent Breaking Changes: Ensures existing code won't break when new features are added
- Language Evolution: Allows gradual introduction of new syntax without compatibility issues
- Parser Consistency: Maintains consistent parsing rules across different JavaScript versions
Conclusion
The class keyword was reserved in ECMAScript 5 as a future reserved word and implemented in ECMAScript 6 to provide cleaner syntax for object-oriented programming. This forward-planning approach ensures JavaScript can evolve without breaking existing codebases.
