Hi everyone! Today we are going look at a very basic but very useful concept Array literals. Unlike a number or string element which represents a single element array are collection of similar data type. Arrays can have zero or more elements. In this article we are going to discuss about array literals in JavaScript.
Array are represented by set of elements enclosed in square brackets.
let x=[5,6,10,15,25];
console.log(x.length)
length property of Arrays will return 5.
Arrays and extra commas(,)
Presense of extra commas(,) in arrays affects the array length. Any two adjacent commas in an array leaves an empty slot for unspecified element. Let's look at few examples.
let x=[5,,6,7,8]
console.log(x.length);
And when you log x it will be
[5, <Empty element>, 6,7,8]
Here although only four elements are there in an array but the four commas (second empty ,) causes array length to be 5.
let x=[5,6,7,8,]
and when you log x it will be
[5,6,7,8]
Here again array has four elements and four commas(,) but the array length is 4 and not 5 this is because last comma is ignored.
Note: While using array iterating methods like Map this empty element is always skip.
It's always recommended to have extra comma at the end as it improves the readability of code when you are working on big arrays.
let fruits=["Apple",
"Banana",
"Mango",
"Jack fruit",
]
And also adding comma at end won't cause any merge conflict if multiple team members are adding elements to same array.
That's it for today!
Happy Coding.....