Javascript

JavaScript Arrays

Share

The JavaScript Arrays object is a global object that is used to store multiple values in a single variable.

The JavaScript Arrays object is a global object that is used to store multiple values in a single variable i.e. collection of elements.

Syntax:

var cars = [
"Fiat",
"BMW",
"Nissan"
];

Note: Never put a comma after the last element (like “Nissan”,). This can be effected is inconsistent across different browsers.

Using keyword new:

var cars = new Array("Fiat", "BMW", "Nissan");

Use [] instead because, there is no need to use the JavaScript’s new Array().

Read Also: Detect Browser in JavaScript

How to access:

By index number, you can an array element.

var firstCar = cars[0];

cars[0] is the first element
cars[1] is the second element
cars[2] is the third element

So, for last element:

var lastCar = cars[cars.length - 1];

Length of an Array:

The length property of an array returns the length of an array.

console.log(cars.length);

Looping an Array:

cars.forEach(function (item, index, array) {
console.log(item, index);
});

Add to the end:

var newArray = cars.push("Innova");

Remove from the end:

var lastArray = cars.pop();

Remove from the front:

var first = cars.shift();

Add to the front:

var newLength = cars.unshift("Alto");

Find the index:

var pos = cars.indexOf("Innova");

Remove an item by Index Position:

var removedItem = cars.splice(pos, 1);

Copy an Array:

var carsCopy = cars.slice();

Recognize an Array:

typeof cars;

The difference between Arrays and Objects is that arrays use numbered indexes whereas objects use named indexes.

View Comments

  • Arrays are a special type of objects. The typeof operator in JavaScript returns object for arrays.

Recent Posts

Warm Comfort: Choosing the Best Hot Water Bottle for Cozy Nights

Introduction: As the chill of winter settles in or a bout of cold weather strikes,…

10 hours ago

One Location, Different Perspectives: The Allure of Dubai Marina Apartments

Nestled along the glittering waterfront of the City of Gold, Dubai Marina beckons to discerning…

10 hours ago

Role Of Gojek Clone In Growth Campaigns For Your Business

When was the last time you heard that a clone app like Gojek could efficiently…

15 hours ago

How to Optimize Your E-Commerce Pages and Improve UX?

The e-commerce market is growing and evolving at a rapid pace. More and more people…

1 day ago

What Not to Do When Navigating Through a Personal Injury Claim?

Navigating through a personal injury claim can be a complex and daunting process. If you've…

1 day ago

Overview of Reputation, Services, and Features of IplWin

IplWin stands as a reliable and enthralling platform for Indian punters, offering a captivating blend…

3 days ago