𝗔𝗿𝗿𝗮𝘆𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
An array is an ordered list of values. You refer to each value as an element. Every element has an index number.
Key facts about JavaScript arrays:
- They hold mixed data types like numbers, strings, and booleans.
- They grow automatically. You do not need to set a size first.
Ways to create arrays:
Array Constructor You use the Array() function. let scores = new Array(10); This creates an array with 10 empty slots.
Array Literal This is the preferred method. Use square brackets. let colors = ['red', 'green', 'blue']; let emptyArray = [];
How to access elements:
JavaScript uses zero-based indexing. The first element is at index 0. let mountains = ['Everest', 'Fuji', 'Nanga Parbat'];
- mountains[0] returns 'Everest'.
- mountains[1] returns 'Fuji'.
You can change values by assigning a new one to an index. mountains[2] = 'K2';
Common array operations:
- Add to the end: use .push()
- Add to the start: use .unshift()
- Remove from the end: use .pop()
- Remove from the start: use .shift()
- Find an index: use .indexOf()
- Check if a value is an array: use Array.isArray()
To find the total number of elements, use the .length property.
Source: https://www.javascripttutorial.net/javascript-array/ Complete post: https://dev.to/pdhanush26/arrays-in-javascript-599a