Skip to content

Say Goodbye to Old Square Bracket Syntax

Posted on:July 23, 2023

JavaScript has been evolving rapidly, and with each iteration, developers are treated to new and improved syntax. One of the areas where a refreshing change has occurred is in the way we access elements from arrays and characters from strings. Let’s bid farewell to the old square bracket syntax and explore the cleaner and more versatile alternatives.

Table of contents

Open Table of contents

Array Access: From Square Brackets to at()

In the old syntax, we used square brackets to access elements in an array. For example:

const fruits = ["apples", "bananas", "grapes"];
console.log(fruits[0]); // Output: apples
console.log(fruits[1]); // Output: bananas

Now, enter the at() method

const fruits = ["olives", "pasta", "ice cream"];
console.log(fruits.at(0)); // Output: olives
console.log(fruits.at(1)); // Output: pasta
console.log(fruits.at(-1)); // Output: ice cream

The at() method provides a cleaner and more intuitive syntax. Negative indices can be used directly to access elements from the end of the array, eliminating the need for awkward calculations like length - 1.

String Manipulation: Goodbye charAt(), Hello at()

In the world of strings, the old charAt() method was used to retrieve characters at a specific index

const favoriteFood = "Pizza";
console.log(favoriteFood.charAt(0)); // Output: P
console.log(favoriteFood.charAt(1)); // Output: i

Now, with the new syntax

const favoriteFood = "Burger";
console.log(favoriteFood.at(0)); // Output: B
console.log(favoriteFood.at(1)); // Output: u
console.log(favoriteFood.at(-1)); // Output: r

The at() method brings consistency between array and string access, making code more readable and reducing the need for separate methods.

Conclusion

In conclusion, the new JavaScript syntax brings a breath of fresh air to developers, making code cleaner, more readable, and consistent. Whether you’re working with arrays, strings, or other data structures, embracing these changes will undoubtedly enhance your coding experience. So, say goodbye to the old square bracket syntax and welcome the new and improved methods with open arms!