JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to access array elements in JavaScript?

The items of an array are called elements. To access an array element, you have to write the array name, followed by square brackets and pass the index value of the element you want to access to the square brackets.

In JavaScript, arrays are zero-based, which means the indexing of elements starts from 0. So, the first element has an index value of 0, the second element has an index value of 1 and so on.

let games = ["Chess", "Table Tennis", "Jenga", "Scrabble"];
console.log(games[0]); //Chess
console.log(games[1]); //Table Tennis
console.log(games[2]); //Jenga
console.log(games[3]); //Scrabble

If you specify an index value that does not exist in the array, you will get undefined.

console.log(games[4]); //undefined

How to change an array element in JavaScript?

Using the same syntax that you use to access array elements, you can change it simply by assigning a new value. Suppose, you don't like Table Tennis and want to change it with Carrom Board then update it in the following way:

games[1] = "Carrom Board";
console.log(games); //["Chess", "Carrom Board", "Jenga", "Scrabble"]

Since Table Tennis is at first index position, you access it using that value and assign it a new value: Carrom Board.

Recommended Posts