Problem Statement
How do you create an array in JavaScript?
Explanation
Arrays are created using square brackets with elements separated by commas.
You can also create arrays using the Array constructor, but square bracket notation is more common and preferred.
Arrays can hold any data type: numbers, strings, objects, other arrays, or mixed types.
Arrays in JavaScript are zero-indexed, meaning the first element is at position 0.
Arrays are dynamic, so you can add or remove elements after creation.
Code Solution
SolutionRead Only
// Array literal (most common)
const numbers = [1, 2, 3, 4, 5];
const fruits = ['apple', 'banana', 'orange'];
// Mixed types
const mixed = [1, 'hello', true, null, {name: 'John'}];
// Empty array
const empty = [];
// Using Array constructor (less common)
const arr1 = new Array(1, 2, 3);
const arr2 = new Array(5); // Creates array with 5 empty slots
// Nested arrays
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Accessing elements (zero-indexed)
console.log(numbers[0]); // 1
console.log(fruits[1]); // 'banana'
console.log(numbers[numbers.length - 1]); // 5 (last element)