Level Up Your JavaScript: ES5 vs ES6
Muhammad Ahsan
Full Stack Developer | React, Node & Next Expert | Dedicated to Advancing Expertise in DevOps | Remote Developer
JavaScript has come a long way since ES5. ES6 (ECMAScript 2015) introduced a wealth of features that make our code cleaner, more concise, and more powerful. Let's dive into some key differences:
1. Variables:
Example (ES5 vs. ES6):
JavaScript
// ES5 (scope issue)
for (var i = 0; i < 3; i++) {
console.log(i); // logs 0, 1, 2 (unexpected!)
}
console.log(i); // logs 3 (var leaks scope)
// ES6 (block scope)
for (let i = 0; i < 3; i++) {
console.log(i); // logs 0, 1, 2
}
console.log(i); // ReferenceError: i is not defined
2. Functions:
Example (ES5 vs. ES6):
JavaScript
// ES5
var numbers = [1, 2, 3];
numbers.forEach(function(number) {
console.log(number * 2);
});
// ES6 (arrow function)
const numbers = [1, 2, 3];
numbers.forEach(number => console.log(number * 2));
3. Classes:
Example (ES5 vs. ES6):
JavaScript
// ES5 (prototype)
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log("Hi, my name is " + this.name);
};
// ES6 (class)
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log("Hi, my name is " + this.name);
}
}
4. Other Improvements:
By embracing ES6, you can write more modern, maintainable, and expressive JavaScript. What are your favorite features of ES6? Share your thoughts in the comments!