Back to JavaScript
2025-12-096 min read

JavaScript Arrays and typeof Operator

Learn JavaScript Arrays and typeof Operator step by step with clear examples and exercises.

Title: Mastering JavaScript Arrays and typeof Operator - A full guide

Why This Matters

In this lesson, we delve into understanding the intricacies of JavaScript arrays and the typeof operator, two essential concepts for any JavaScript developer. Arrays help manage collections of data efficiently while the typeof operator is crucial in determining the type of a variable. These topics are vital for acing coding interviews, resolving real-world programming issues, and ensuring your code runs smoothly without errors.

Prerequisites

Before diving into arrays and the typeof operator, it's essential to have a solid understanding of:

  1. JavaScript basics such as variables, operators, control flow statements (if...else, loops), and basic concepts related to functions, objects, and error handling.
  2. Data types in JavaScript like numbers, strings, booleans, null, undefined, and symbols.
  3. Basic knowledge of DOM manipulation and event handling.

Core Concept

Arrays

An array is a collection of elements, each identified by an index starting from 0. In JavaScript, arrays can contain any type of data, including numbers, strings, booleans, objects, or even other arrays.

let myArray = [1, "hello", true, { name: "John" }, [1, 2, 3]];
console.log(myArray); // Output: [1, "hello", true, {...}, [1, 2, 3]]

Creating an Array

There are several ways to create an array in JavaScript:

  • Using square brackets [] with comma-separated values:
let myArray = []; // Empty array
let numbers = [1, 2, 3]; // Array of numbers
  • Using the Array constructor:
let myArray = new Array(); // Empty array
let colors = new Array("red", "green", "blue"); // Array with initial values

Accessing and Modifying Array Elements

To access an element in an array, use its index within the square brackets:

let myArray = [1, 2, 3];
console.log(myArray[0]); // Output: 1
console.log(myArray[2]); // Output: 3

To modify an element in an array, simply assign a new value to the specific index:

let myArray = [1, 2, 3];
myArray[0] = "apple";
console.log(myArray); // Output: ["apple", 2, 3]

Adding and Removing Elements

To add an element to the end of an array, use the push() method:

let myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // Output: [1, 2, 3, 4]

To add an element at a specific index, use the splice() method:

let myArray = [1, 2, 3];
myArray.splice(1, 0, "apple"); // Adds "apple" before index 1
console.log(myArray); // Output: [1, "apple", 2, 3]

To remove the last element from an array, use the pop() method:

let myArray = [1, 2, 3];
myArray.pop();
console.log(myArray); // Output: [1, 2]

To remove an element at a specific index, use the splice() method:

let myArray = [1, 2, 3];
myArray.splice(1, 1); // Removes one element at index 1
console.log(myArray); // Output: [1, 3]

Iterating Through an Array

To iterate through an array, you can use a for loop or the forEach() method:

let myArray = [1, 2, 3];
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]); // Outputs each element in the array
}

myArray.forEach((element) => console.log(element)); // Same output as above

Sorting and Searching Arrays

JavaScript provides several built-in methods for sorting and searching arrays:

  • sort() method sorts an array in ascending order by default. You can provide a comparison function to customize the sorting behavior.
  • indexOf() method returns the index of the first occurrence of a specified element, or -1 if not found.
  • includes() method checks whether an array includes a specified element and returns a boolean value.

typeof Operator

The typeof operator is used to determine the data type of a variable in JavaScript. It returns one of the following strings:

  • "undefined" for variables that have not been assigned a value
  • "boolean", "number", "string", "symbol", "object", or "function" for their respective data types
  • "object" for arrays, even though they are technically a special type of object in JavaScript
let myVar;
console.log(typeof myVar); // Output: "undefined"

let myBool = true;
console.log(typeof myBool); // Output: "boolean"

let myNum = 123;
console.log(typeof myNum); // Output: "number"

let myStr = "hello";
console.log(typeof myStr); // Output: "string"

let myArray = [1, 2, 3];
console.log(typeof myArray); // Output: "object" (even though it's an array)

Worked Example

Let's create a simple program that reads user input as numbers, stores them in an array, and calculates their sum using the reduce() method.

// Initialize an empty array to store user inputs
let numArray = [];

// Loop until the user enters "done"
while (true) {
const input = prompt("Enter a number or type 'done' to finish.");

// If the user entered "done", break out of the loop
if (input === "done") {
break;
}

// Try parsing the input as a number
let num;
try {
num = Number(input);
} catch (error) {
console.log("Invalid input. Please enter a valid number.");
continue;
}

// Add the parsed number to the array
numArray.push(num);
}

// Calculate the sum of the numbers in the array using reduce()
let total = numArray.reduce((sum, current) => sum + current);
console.log(`The sum of the entered numbers is: ${total}`);

Common Mistakes

  1. Forgetting to declare an array variable: Always declare your arrays using let, const, or var.
  2. Accessing non-existent indices: Be careful not to access indices that are out of bounds (i.e., less than 0 or greater than the length of the array).
  3. Modifying an array while iterating over it: This can lead to unexpected results and is generally best avoided. Instead, use methods like forEach() for iteration if you don't need to modify the array.
  4. Using typeof on objects or functions without checking their constructor: The typeof operator will return "object" for arrays and functions. To check if a variable is an array, use the Array.isArray() method. For functions, check the constructor property (e.g., function MyFunction() {}, so myVariable.constructor === MyFunction).
  5. Not handling edge cases: Always consider edge cases such as empty arrays, null values, or non-numeric inputs when working with arrays and numbers.

Practice Questions

  1. Write a function that takes an array of numbers and returns the sum of all even numbers in the array.
function sumEvenNumbers(arr) {
return arr.reduce((sum, num) => (num % 2 === 0 ? sum + num : sum), 0);
}
  1. Write a program that reads user input as strings, stores them in an array, and calculates the length of the longest string using the reduce() method.
// Initialize an empty array to store user inputs
let strArray = [];

// Loop until the user enters "done"
while (true) {
const input = prompt("Enter a string or type 'done' to finish.");

// If the user entered "done", break out of the loop
if (input === "done") {
break;
}

// Add the parsed string to the array
strArray.push(input);
}

// Calculate the length of the longest string in the array using reduce()
let maxLength = strArray.reduce((max, current) => Math.max(max.length, current.length), 0);
console.log(`The length of the longest string is: ${maxLength}`);
  1. Given the following arrays:
let arr1 = [1, 2, 3];
let arr2 = ["apple", "banana", "cherry"];
let arr3 = [true, false, null];
  • Write a single line of code to concatenate all three arrays into one.
let combinedArray = [...arr1, ...arr2, ...arr3];
  • Write a single line of code to find the total number of elements in all three arrays combined.
let totalElements = arr1.length + arr2.length + arr3.length;

FAQ

  1. Why does typeof return "object" for arrays?
  • JavaScript treats arrays as a special type of object, which is why typeof returns "object". However, arrays have additional methods and properties that make them behave differently from regular objects.
  1. How can I find the index of an element in an array?
  • You can use the indexOf() method to find the index of an element in an array: myArray.indexOf(element). If the element is not found, it returns -1.
  1. What happens if I try to access an index that is out of bounds in an array?
  • Accessing an index that is out of bounds will return undefined for properties and throw a RangeError: Index out of range for methods like push(), pop(), etc. Be careful when working with arrays, as this can lead to unexpected behavior or errors in your code.
  1. What are some common array methods that I should know?
  • Some commonly used array methods include push(), pop(), shift(), unshift(), splice(), forEach(), map(), filter(), reduce(), sort(), indexOf(), and includes(). Familiarize yourself with these methods to work efficiently with arrays in JavaScript.
JavaScript Arrays and typeof Operator | JavaScript | XQA Learn