A JavaScript array is a special variable that can store multiple values in a single variable.
Normally, a variable stores one value.
An array stores multiple values using square brackets [].
This array contains five elements.
Arrays can be created in two ways.
The literal method is recommended.
Arrays can contain different data types.
Use the length property to get the total number of elements.
The length changes automatically.
Array indexing starts from 0.
Accessing an invalid index returns undefined.
The at() method accesses elements by index.
Negative indexes access elements from the end.
Arrays can be traversed using different loops.
You can update an array element by specifying its index.
The existing values are replaced with new values.
New elements can be added by assigning values to a new index.
Using cities.length automatically adds an element at the end.
The push() method adds one or more elements at the end of an array.
push() is the recommended way to add elements at the end.
The unshift() method adds elements at the beginning of an array.
Multiple elements can also be added.
The pop() method removes and returns the last element.
The shift() method removes the first element.
JavaScript does not directly remove a middle element by value.
The filter() method creates a new array.
| Operation | Method |
|---|---|
| Find Size | length |
| Add at End | push() |
| Add at Beginning | unshift() |
| Remove Last | pop() |
| Remove First | shift() |
| Access Element | [] or at() |
| Loop Elements | for, forEach, for...of |
| Method | Purpose |
|---|---|
| length | Array size |
| push() | Add at end |
| pop() | Remove last |
| unshift() | Add at beginning |
| shift() | Remove first |
| at() | Access element |
| forEach() | Loop through array |
Which method adds a new element at the end of an array?