erojas.devertek.io logo
Javascript Hacks

Modern JavaScript Features You Should Be Using

JavaScript has evolved significantly over the years, introducing powerful features that enhance code readability, maintainability, and efficiency. In this blog post, we'll explore eight modern JavaScript features that every developer should be familiar with: `let` and `const`, default parameters, template literals, destructuring assignment, arrow functions, the spread operator, rest parameters, and short-circuit evaluation.

1. Use `let` and `const` Instead of `var`

In the past, `var` was the only way to declare variables in JavaScript. However, `var` has function scope, which can lead to unexpected behavior. Modern JavaScript introduces `let` and `const` for block-scoped variable declarations.

  • `let`: Use for variables that can be reassigned.

  • `const`: Use for variables that should not be reassigned.

1let count = 0;
2if (true) {
3  let count = 1; // This 'count' is different from the 'count' outside the block
4}
5const pi = 3.14159;
6// pi = 3; // Error: Assignment to constant variable
7
8

2. Default Parameters

1Default parameters allow you to initialize function parameters with default values if no value or undefined is passed.
1
2function greet(name = 'Guest') {
3  return `Hello, ${name}!`;
4}
5console.log(greet()); // Hello, Guest!
6console.log(greet('Alice')); // Hello, Alice!
7

3. Template Literals

Template literals provide a more readable and convenient way to create strings, especially when embedding expressions and multi-line strings.

1const name = 'John';
2const message = `Hello, ${name}! Welcome to the JavaScript tutorial.`;
3console.log(message); // Hello, John! Welcome to the JavaScript tutorial.

4. Destructuring Assignment

Destructuring allows you to unpack values from arrays or properties from objects into distinct variables, making your code cleaner and more readable.

1// Array destructuring
2const numbers = [1, 2, 3];
3const [first, second, third] = numbers;
1console.log(first, second, third); // 1 2 3
2// Object destructuring
3const user = { name: 'Jane', age: 25 };
4const { name, age } = user;
1console.log(name, age); // Jane 25

5. Arrow Functions

1Arrow functions provide a concise syntax for writing function expressions. They also lexically bind the this value, making them useful in many situations.
1const add = (a, b) => a + b;
1console.log(add(2, 3)); // 5

6. Spread Operator

1The spread operator (...) allows an iterable (like an array or string) to be expanded in places where zero or more arguments or elements are expected.
1const arr1 = [1, 2, 3];
2const arr2 = [...arr1, 4, 5, 6];
1console.log(arr2); // [1, 2, 3, 4, 5, 6]
1const obj1 = { a: 1, b: 2 };
2const obj2 = { ...obj1, c: 3 };
1console.log(obj2); // { a: 1, b: 2, c: 3 }