Onjsdev

Share


Javascript Arrays


By onjsdev

Dec 5th, 2023

If you're just getting started with programming or JavaScript, arrays are essential data structures that allow you to organize values efficiently.

What is an Array?

An array in JavaScript is a special type of variable that can hold multiple values. These values can be of any data type, such as numbers, strings, or even other arrays

How To Create An Array In Javascript

To create an array in JavaScript, you can use the [] (square brackets).

Here's a simple example:

// Creating an empty array
let myArray = [];

// Creating an array with values
let fruits = ['apple', 'banana', 'orange'];

How To Access Array Elements

Array elements are accessed using their indices. The first element is at index 0, the second at index 1, and so on. You can access an element by specifying its index inside square brackets.

let fruits = ['apple', 'banana', 'orange'];

// Accessing elements
console.log(fruits[0]); // Output: 'apple'
console.log(fruits[1]); // Output: 'banana'
console.log(fruits[2]); // Output: 'orange'

How To Modify Array Elements

You can easily modify array elements by assigning new values to specific indices.

let fruits = ['apple', 'banana', 'orange'];

// Modifying elements
fruits[1] = 'grape';
console.log(fruits); // Output: ['apple', 'grape', 'orange']

How To Get Array Length

To get the number of elements in an array, you can use the length property.

let fruits = ['apple', 'banana', 'orange'];

// Getting array length
console.log(fruits.length); // Output: 3

Common Array Methods

JavaScript provides a variety of built-in methods for manipulating arrays.

Here are a few commonly used ones:

  • push(element): Adds an element to the end of the array.
  • pop(): Removes the last element from the array.
  • unshift(element): Adds an element to the beginning of the array.
  • shift(): Removes the first element from the array.
  • splice(start, deleteCount, item1, item2, ...): Adds or removes elements at a specific index.
let fruits = ['apple', 'banana', 'orange'];

// Using array methods
fruits.push('grape');
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'grape']

fruits.pop();
console.log(fruits); // Output: ['apple', 'banana', 'orange']

fruits.unshift('kiwi');
console.log(fruits); // Output: ['kiwi', 'apple', 'banana', 'orange']

fruits.shift();
console.log(fruits); // Output: ['apple', 'banana', 'orange']

fruits.splice(1, 1, 'melon');
console.log(fruits); // Output: ['apple', 'melon', 'orange']

Conclusion

Arrays are essential structures in every programming languages and javascript is not an exception. Remember that you experiment with different array methods and explore their capabilities.

Thank you for reading.