put multiple elements in one const in javascript

To put multiple elements in one const in JavaScript, you can use an array or an object.

Using an array:

index.tsx
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits); // Output: ['apple', 'banana', 'orange']
108 chars
3 lines

In the above example, we have assigned an array of fruits to a const variable fruits. The const keyword ensures that the variable fruits cannot be reassigned to a different array or value.

Using an object:

index.tsx
const person = { name: 'John', age: 30, gender: 'Male'};
console.log(person); // Output: { name: 'John', age: 30, gender: 'Male' }
131 chars
3 lines

In the above example, we have assigned an object of a person with three properties to a const variable person. Similar to the array example, the const keyword ensures that the variable person cannot be reassigned to a different object or value.

Note that although the const keyword prevents the variable from being reassigned, it does not prevent the array or object itself from being modified. To ensure that the array or object is never modified, you can use Object.freeze method, but that is not recommended in all scenarios.

gistlibby LogSnag