Javascript Array element index

Introduction

To get and set array values, use square brackets and the zero-based index:

let colors = ["red", "blue", "green"]; // define an array of strings 
console.log(colors[0]); // display the first item 
colors[2] = "black"; // change the third item 
colors[3] = "brown"; // add a fourth item 

The index within the square brackets indicates the value being accessed.

If the index is larger than the array length, the array length is expanded to be that index plus 1.

let languages = ['HTML', 'CSS'];
console.log(languages.length);// 2
//access (index into) an Array item
let first = languages[0];// HTML
console.log(first);//from  w w  w  . j  av  a 2s. c  om
let last = languages[languages.length - 1];// CSS
console.log(last);



PreviousNext

Related