COMPUTER SCIENCE CAFÉ
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
JAVASCRIPT | ARRAYS
ON THIS PAGE
SECTION 1 | POPULAR METHODS AT A GLANCE
SECTION 2 | CREATING ARRAYS

SECTION 3 | ACCESSING ARRAY ELEMENTS
SECTION 4 | ADDING OR CHANGING ELEMENTS
SECTION 5 | REMOVING ELEMENTS
SECTION 6 | THE LENGTH METHOD
SECTION 7 | COMMON MISTAKES TO AVOID
​SECTION 8 | EXAMPLE USES

ALSO IN THIS TOPIC
GETTING STARTED

 ​VARIABLES & USER INPUT
 OPERATORS
CONDITIONALS (IF STATEMENTS)
​ITERATION (LOOPS)
YOU ARE HERE | ARRAYS (LISTS)
FUNCTIONS

FURTHER JAVASCRIPT

Picture
WHAT ARE ARRAYS
An array is a special type of data structure in JavaScript that allows you to store multiple values in a single variable. It organises these values in a sequential manner, where each value is assigned a unique index starting from zero. Think of an array as a list or a collection of items, where each item can be of any data type, including another array.

Arrays are incredibly versatile and are used for various reasons:
  • Organised Storage: Arrays provide a structured way to store multiple pieces of information together. Instead of having separate variables for each item, you can have a single array holding all the items.
  • Efficient Operations: With arrays, you can loop through and perform operations on multiple items at once, making data processing more efficient.
  • Dynamic Size: Arrays can grow or shrink in size as needed. You can add items to the end, remove items, or insert items in the middle.
  • Multifunctional: Arrays can hold any data type, including numbers, strings, objects, and even other arrays. This flexibility allows for complex data structures like multidimensional arrays.
  • Consistent Access: Items in an array are accessed by their index, making it easy to retrieve or update a specific item based on its position in the list.

In essence, arrays are fundamental in programming because they offer a way to group, manage, and manipulate multiple data points efficiently under a single variable name.
SECTION 1 | POPULAR JAVASCRIPT ARRAY METHODS AT A GLANCE
push() - Adds one or more elements to the end of an array: myArray.push(item)
unshift() - Adds one or more elements to the beginning of an array: myArray.unshift(item)
pop() - Removes the last element from an array: myArray.pop()
shift() - Removes the first element from an array: myArray.shift()
splice() - Adds/removes items to/from an array: myArray.splice(index, howmany, item1, ....., itemX)
reverse() - Reverses the order of the elements in an array: myArray.reverse()
indexOf() - Returns the first index at which a given element can be found: myArray.indexOf(item)
sort() - Sorts the elements of an array: myArray.sort()
slice() - Returns a shallow copy of a portion of an array: newArray = myArray.slice(start, end)
join() - Joins all elements of an array into a string: myString = myArray.join(separator)
concat() - Merges two or more arrays: newArray = myArray.concat(array2, array3, ...)
forEach() - Executes a function once for each array element: myArray.forEach(function(currentValue, index, arr), thisValue)
map() - Creates a new array with the results of calling a function for every array element: newArray = myArray.map(function(currentValue, index, arr), thisValue)
filter() - Creates a new array with every element in an array that pass a test: newArray = myArray.filter(function(currentValue, index, arr), thisValue)
find() - Returns the value of the first element in an array that pass a test: result = myArray.find(function(currentValue, index, arr), thisValue)
includes() - Checks if an array contains a specified element: myArray.includes(element, start)
some() - Checks if any of the elements in an array pass a test: myArray.some(function(currentValue, index, arr), thisValue)
every() - Checks if all elements in an array pass a test: myArray.every(function(currentValue, index, arr), thisValue)
reduce() - Reduces the array to a single value (from left-to-right): myArray.reduce(function(total, currentValue, currentIndex, arr), initialValue)
reduceRight() - Reduces the array to a single value (from right-to-left): myArray.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)
SECTION 2 | CREATING ARRAYS
​A List is an array of data that can be created and easily edited. A list is defined by the use of square brackets [ ] and you need to assign the list to a variable. Each element in a list has a numeric position and the positions start from 0: The example below:
Picture
It is also quite common to create an empty array, ready for population later in your program, to do this simply leave the [ ] empty:

let myFruits = [ ];
SECTION 3 | ACCESSING ARRAY ELEMENTS
As can be seen in section 1, Arrays in JavaScript are collections of items, and each item in the array is assigned a unique index. Understanding how to access these items is crucial when working with arrays. Below demonstrates how to access a element within a specified index of the array.

    
If you try to access an index that doesn't exist in the array, JavaScript will return undefined.
Code Editor

    
Accessing a range of elements within an array is commonly referred to as "slicing" or "subsetting" the array. In JavaScript, you can achieve this using the slice() method. Here's how to do it:

Accessing a Range of Elements Using the slice() Method:
The slice() method returns a shallow copy of a portion of an array into a new array object. It takes two arguments:
  • Start Index (inclusive): The beginning index from which to start slicing.
  • End Index (exclusive): The ending index up to which to slice. The element at this index will not be included.
If either of the arguments is omitted, the slice will go up to the end of the array.

    
Note how in the example above, we sliced the fruits array from index 1 to index 4, but the element at index 4 ("date") is not included in the result.

​
Using negative indices:
Negative indices count from the end of the array.

    
SECTION 4 | ADDING OR CHANGING ELEMENTS
MODIFYING VALUES
You can also use the index to modify/change an existing value in the array. To change a value, assign a new value to the specific index as can be seen below.

    
APPENDING ELEMENTS TO THE ARRAY
Using the push() method:
This method adds one or more elements to the end of an array and returns the new length of the array.
CORRECT STRUCTURE USED

    
​Using the unshift() method:
This method adds one or more elements to the beginning of an array and returns the new length.
WRONG STRUCTURE USED

    
Using the splice() method: 
Changes the contents of an array by removing, replacing, or adding elements.
Code Editor

    
Using the slice() method:
Returns a shallow copy of a portion of an array into a new array object.

    
Using the concat() method:
Merges two or more arrays and returns a new array.

    
SECTION 5 | REMOVING ELEMENTS FROM AN ARRAY
Using the pop() method:
This method removes the last element from an array and returns that element.

    
Using the shift() method:
This method removes the first element from an array and returns that element

    
REMOVING A SPECIFIED ELEMENT FROM THE ARRAY BASED ON ITS VALUE
​

REMOVE AN ITEM METHOD 1 | Using the indexOf() method with splice()
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if the element is not present. Once you have the index, you can use the splice() method to remove the item.

    
In the example above, we wanted to remove "banana" from the fruits array. We first found its index using indexOf(). Then, we used splice() to remove it. The splice() method takes two arguments: the index to start removing elements and the number of elements to remove.

REMOVE AN ITEM METHOD 2 | 
Using the filter() method​
The filter() method creates a new array with all elements that pass the test provided by a function. It's a more functional approach and can be useful if you want to remove multiple occurrences of an item.
THE TERNARY OPERATOR

    
In this example, we used the filter() method to create a new array that doesn't include any "banana" items.
REMOVING A SPECIFIED ELEMENT FROM THE ARRAY BASED ON ITS​ INDEX
To remove a value from an array based on its index, you can use the splice() method. The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

Using the splice() Method to Remove an Element by Index:
The splice() method requires two arguments:
  • Start Index: The index at which to start changing the array.
  • Delete Count: The number of elements to remove.
SWITCH STATEMETN SYNTAX

    
SECTION 6 | THE LENGTH METHOD
​The length property of an array in JavaScript returns the number of elements present in that array. It's not a method but a property. This property is both readable and writable, meaning you can use it to determine the size of an array and also to set the size of the array.

    
The length property is a fundamental property of arrays in JavaScript. It's essential for various operations, especially when iterating over arrays or when you need to dynamically adjust the size of an array. Properties like this mean as a coder you do not need to know the length of the data you are dealing with, you can simply make JavaScript do the work for you.
    SECTION 7 | COMMON MISTAKES TO AVOID
    ​Here are some of the most common mistakes beginners often make when dealing with arrays in JavaScript:
    • Off-by-One Errors: Forgetting that array indices start at 0, not 1. This can lead to accessing an incorrect element or even accessing an undefined index.
    • Modifying Arrays While Iterating: Changing the size of an array (adding or removing elements) while looping through it can lead to unexpected behaviour.
    • Confusing Length with the Last Index: The length property gives the number of elements, not the last index. The last index is length - 1.
    • Using Incorrect Methods: For example, using push() (which adds to the end) when unshift() (which adds to the beginning) was intended, and vice versa.
    • Not Checking for undefined: Trying to access an array index that doesn't exist will return undefined, not an error. Always check if an element exists before using it.
    • Forgetting that Arrays are Objects: Arrays in JavaScript are objects, and they can have string keys and properties. This can sometimes lead to unexpected behaviour when iterating or checking the length.
    • Using Arrays as Associative Arrays: JavaScript arrays are meant to be used with numeric indices. For key-value pairs, objects should be used.
    • Not Realizing that Array Methods Mutate: Some array methods, like splice(), modify the original array, while others, like slice(), return a new array. It's essential to know the difference.
    • Forgetting to Declare Arrays: Trying to push an item into an undeclared variable thinking it's an array will throw an error.
    • Using == Instead of === for Array Comparisons: Arrays are reference types, so == and === compare references, not content. To compare the content of two arrays, you'd need a function that checks each element.
    • Over-relying on the length Property: Reducing the length property will truncate the array, but increasing it won't add new elements; it'll just create "holes" in the array.
    • Not Using Array-specific Methods: JavaScript provides powerful array methods like map(), filter(), and reduce(). Not leveraging these can lead to more verbose and less efficient code.
    SECTION 8 | EXAMPLE USES
    ​FIND THE AVERAGE
    This program takes a series of numbers from the user, stores them in an array, and then calculates and displays the average of the numbers.
    1. Ask the user how many numbers they want to enter.
    2. Use a loop to get the specified number of inputs from the user and store them in an array.
    3. Calculate the sum of the numbers in the array.
    4. Divide the sum by the number of elements to get the average.
    5. Display the average to the user.
    FIND THE AVERAGE
    
        
    REVERSE WORDS
    This program that takes a sentence from the user and displays the words in reverse order.
    1. Ask the user to enter a sentence.
    2. Split the sentence into an array of words.
    3. Use a loop to reverse the order of the words.
    4. Join the reversed array back into a string.
    5. Display the reversed sentence to the user.
    REVERSE WORDS
    
        
    ​
    Picture
    SKI TEAMS
    TASK 1 | CREATE A PROGRAM THAT DOES THE FOLLOWING

    1: Ask the user for the time it took to complete the ski course
    2: IF they complete the course in less than 2 minutes then they are in team A. Output ' Congratulations - You are in Team A' 3: If they complete the course in 2 minute or more and less than 3 minutes then they are on team B. Output ' Congratulations - You are in Team B'
    ​4: Otherwise they are on team C. Output ' Congratulations - You are in Team C'

    TASK 2 | CREATE A PROGRAM THAT DOES THE FOLLOWING
    A Ski company sells lift passes and wants you to create a program that does the following
    1: Ask the user if they want a day pass or week pass
    2: If the user wants a day pass then ask the user how old they are
        2b: If the user is less that 11 years old the the day pass is $40
        2c: If the user is greater than 64 years old then the day pass is $20
        2d: Otherwise the day pass is $60
    3: If the user wants a week pass then ask the user how old they are
        3b: If the user is less that 11 years old the the week pass is $100
        3c: If the user is greater than 64 years old then the day pass is $100
        3d: Otherwise the day pass is $200
    4: Output the cost of the correct pass in a user friendly statement
    Picture
    PARTY GUEST LIST
    OBJECTIVE
    Write a program that manages the guest list for a party. The program should take the number of invitees, their names, and then manage any 'no shows' by removing them from the list. If a 'no show' wasn't on the original list, the program should inform the user that they weren't invited.

    TASKS
    • Ask the user how many people are invited to the party.
    • Use a loop to get the names of all the invitees and store them in an array.
    • Ask the user if there are any 'no shows'.
    • If there are 'no shows', ask for their names one by one.
    • For each 'no show' name:
    • If the name is in the invitee list, remove it.
    • If the name isn't in the invitee list, display a message saying "they are not on the invitation list".
    • Finally, display the updated list of attendees.

    SAMPLE OUPUT
    How many people are invited to the party? 4
    Enter the name of invitee 1: Alice
    Enter the name of invitee 2: Bob
    Enter the name of invitee 3: Charlie
    Enter the name of invitee 4: David
    Are there any 'no shows'? (yes/no): yes
    Enter the name of the 'no show': Eve
    Eve is not on the invitation list.
    Enter the name of the 'no show': Charlie
    Updated attendees: Alice, Bob, David


    Picture
    NAVIGATION
    GETTING STARTED
    ​VARIABLES & USER INPUT
     OPERATORS
    CONDITIONALS (IF STATEMENTS)
     ​ITERATION (LOOPS)
    ARRAYS (LISTS)
    FUNCTIONS

    FURTHER JAVASCRIPT
    Picture
    SUGGESTIONS
    We would love to hear from you
    SUBSCRIBE 
    To enjoy more benefits
    We hope you find this site useful. If you notice any errors or would like to contribute material then please contact us.