DEV Community

Cover image for Everything You Need to Know About Arrays in JavaScript
Vinayagam
Vinayagam

Posted on

Everything You Need to Know About Arrays in JavaScript

Array in JavaScript

Definition of Array:
An Array in JavaScript is a special type of object used to store multiple values in a single variable. These values can be of any data type (numbers, strings, objects, functions, etc.) and are stored in an ordered list.
Arrays use index numbers to access elements. The index always starts from 0.

Example:

let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]);
Enter fullscreen mode Exit fullscreen mode

Output:
Apple

In the above example:

  • fruits is an array
  • "Apple" is stored at index 0
  • "Banana" at index 1
  • "Mango" at index 2

Important Features of JavaScript Arrays

  • Arrays are dynamic (size can grow or shrink).
  • They can store mixed data types.
  • Many built-in methods are available like:

    • push()
    • pop()
    • shift()
    • unshift()
    • map()
    • filter()
    • forEach()

1.What is an array in JavaScript?
Answer:
An array is a special variable that stores multiple values in a single variable using index numbers starting from 0.

2.What is the difference between push() and pop()?
Answer:

  • push() → Adds element at the end of array
  • pop() → Removes element from the end Example:
let arr = [1, 2];
arr.push(3);   
arr.pop();    
Enter fullscreen mode Exit fullscreen mode

Output:
[1,2,3]
[1,2]

3.What is the difference between shift() and unshift()?
Answer:

  • shift() → Removes first element
  • unshift() → Adds element at the beginning example:
let arr = [2, 3];
arr.unshift(1); 
arr.shift();    
Enter fullscreen mode Exit fullscreen mode

Output:
[1,2,3]
[2,3]

4.How are arrays different from normal variables?
Answer:
A normal variable stores only one value at a time, whereas an array can store multiple values in a single variable using index positions.

5.What is the length property in array?
Answer:
The length property returns the total number of elements in an array.

let arr = [10, 20, 30];
console.log(arr.length);
Enter fullscreen mode Exit fullscreen mode

Output:
3

6.Can an array store different data types?
Answer:
Yes. JavaScript arrays can store mixed data types.

let data = [10, "Hello", true, {name: "John"}];
Enter fullscreen mode Exit fullscreen mode

7.Are JavaScript arrays fixed in size?
Answer:
No, JavaScript arrays are dynamic. Their size can grow or shrink during program execution.

8.What is the difference between map() and forEach()?
Answer:

  • map() → Returns a new array
  • forEach() → Does not return a new array
let numbers = [1,2,3];
let newArr = numbers.map(num => num * 2);
numbers.forEach(num => console.log(num));
Enter fullscreen mode Exit fullscreen mode

Output:
[2,4,6]

Top comments (0)