0
0
Javascriptprogramming~5 mins

Array creation in Javascript

Choose your learning style9 modes available
Introduction

Arrays help you keep many items together in one place. You can easily store and use lists of things like numbers, words, or objects.

When you want to store a list of your favorite movies.
When you need to keep track of scores in a game.
When you want to save multiple user names.
When you want to group related data like colors or dates.
Syntax
Javascript
const arrayName = [item1, item2, item3];

// or
const arrayName = new Array(item1, item2, item3);

You can create arrays using square brackets [] or the Array constructor.

Square brackets are simpler and more common.

Examples
This creates an array with three fruit names.
Javascript
const fruits = ['apple', 'banana', 'cherry'];
This creates an empty array with no items.
Javascript
const emptyArray = [];
This creates an array of numbers using the Array constructor.
Javascript
const numbers = new Array(1, 2, 3, 4);
This creates an array with just one item.
Javascript
const singleItemArray = ['onlyOne'];
Sample Program

This program creates three arrays: one with colors, one empty, and one with numbers. It then prints each array to show their contents.

Javascript
const colors = ['red', 'green', 'blue'];
console.log('Colors array:', colors);

const emptyList = [];
console.log('Empty array:', emptyList);

const numbers = new Array(10, 20, 30);
console.log('Numbers array:', numbers);
OutputSuccess
Important Notes

Creating arrays with [] is faster and easier than using new Array().

Arrays can hold any type of data, including numbers, strings, or even other arrays.

Remember, arrays start counting at 0, so the first item is at index 0.

Summary

Arrays store multiple items in one variable.

Use [] to create arrays easily.

Arrays can be empty or have many items.