JavaScript Braces vs Brackets

In JavaScript, arrays are a fundamental data structure used to store ordered collections of elements. While both braces and brackets are used with arrays, they serve distinct purposes.

This article clarifies the difference between these notations and their proper usage.

Table of Content

  • Braces {}
  • Brackets []

Braces {}

In JavaScript, braces are usually used to define objects instead of arrays. One can create an object with key-value pairs when you initialize an array with braces rather than brackets.

Syntax:

let arrayLikeObject = {0: 'apple', 1: 'banana', 2: 'orange', length: 3};

Example: To demonstrate creating a JavaScript object with key-value players using the braces.

JavaScript
let arrayLikeObject = 
    {0: 'apple', 1: 'banana', 2: 'orange', length: 3};

// Accessing elements
console.log(arrayLikeObject[0]);
console.log(arrayLikeObject[1]);
console.log(arrayLikeObject.length);

Output
apple
banana
3

Brackets []

The typical JavaScript notation for array creation is brackets. They represent an ordered set of values with non-negative integers providing an index.

Syntax:

let properArray = ['apple', 'banana', 'orange'];

Example: To demonstrate creating a JavaScript array using the brackets.

JavaScript
let properArray = ['apple', 'banana', 'orange'];

// Accessing elements
console.log(properArray[0]); // Output: 'apple'
console.log(properArray[1]); // Output: 'banana'
console.log(properArray.length); // Output: 3

Output
apple
banana
3

Contact Us