JavaScript Basics | Arrays cover image

JavaScript Basics | Arrays

Jonathan Barrios • September 7, 2020

javascript

Introduction

Welcome to the JavaScript Basics series for beginners. In part 7 of JavaScript Basics, we'll dive into arrays and how the array object can get, insert, push, pop, shift, unshift, splice and sort data of many types. See you there!

Prerequisites

To get the most out of this course, you should know:

In Part 7 of JavaScript Basics, we'll focus on:

Future JavaScript Basics posts include:

Note: It takes years of focused practice to become a great JavaScript engineer. This JavaScript Basics course is an introduction to JavaScript fundamentals and will improve your coding skills, but don't expect to transform into a JavaScript expert overnight instantly. Remember, the JavaScript learning journey is a marathon, not a sprint.

Arrays

An array is an ordered collection of either primitive or object type data used to store multiple values in a single variable. Array items have a number attached to them, an index that allows you to access the item later. In JavaScript, the index starts at zero, and various methods can be applied to them.

// Array (most common)
const numbers = [1, 2, 3, 4, 5]
console.log(numbers)

// Array using the Array object
const numbers_obj = new Array(6, 7, 8, 9, 10)
console.log(numbers_obj)

// Array with strings
const drinks = ['tea', 'water', 'coffee', 'sparkling water', 'something stiff']
console.log(drinks)
console.log(drinks[3])

// Array party, everyone welcome
const party = [10, 'Yay!', true, new Date()]
console.log(party)

// Get array length
value = party.length
console.log(value)

// Is array?
value = Array.isArray(numbers)
console.log(value)

// Insert into arrays
numbers[0] = 99
console.log(numbers)

// Get array index
value = numbers.indexOf(99)
console.log(value)

// Push (end of array)
numbers.push(33)
console.log(numbers)

// Unshift (start of array)
numbers.unshift(101)
console.log(numbers)

// Remove from front
numbers.shift()
console.log(numbers)

// Remove from end
numbers.pop()
console.log(numbers)

// Splice
numbers.splice(1, 3)
console.log(numbers)

// Splice
numbers.splice(1, 3)
console.log(numbers)

// Sort
value = drinks.sort()
console.log(value)
value = numbers.sort()
console.log(value)

// Sort ascending
value = numbers.sort(function(a, b) {
  return a - b
})
console.log(value)

// Sort descending
value = numbers.sort(function(a, b) {
  return b - a
})
console.log(value)

Now that you finished part 7 of JavaSctipt Basics, we'll begin learning all about JavaScript Loops in Part 8. Follow me on Twitter @_jonathan_codes for more JavaScript Basics and other web development frameworks, databases, and more. As always, Happy coding! 👋🏼