Back to JavaScript
2026-04-196 min read

Data structures and types (JavaScript)

Learn Data structures and types (JavaScript) step by step with clear examples and exercises.

Title: Mastering JavaScript Data Structures and Types

Why This Matters

Understanding data structures and types is crucial for writing efficient, scalable, and maintainable code in JavaScript. It's essential for solving complex problems, handling large datasets, and optimizing performance. Moreover, a strong grasp of these concepts can help you identify and fix real-world bugs that might arise during development.

Prerequisites

Before diving into data structures and types, ensure you have a good understanding of the following topics:

  1. JavaScript syntax and variables
  2. Control structures (if-else, loops)
  3. Functions and function scopes
  4. Basic DOM manipulation
  5. Event handling
  6. Understanding the basics of JavaScript objects and arrays
  7. Familiarity with common JavaScript error messages and debugging techniques
  8. Understand the concept of variable hoisting and scope chains
  9. Learn about ES6 features like arrow functions, template literals, and destructuring assignments

Core Concept

Data Structures

JavaScript provides several built-in data structures to manage and organize complex data:

  1. Arrays: An ordered collection of elements, each identified by an index. Elements can be of any type (numbers, strings, objects, etc.).
let numbers = [1, 2, 3, 4, 5];
console.log(numbers[0]); // Output: 1
  1. Objects: A collection of key-value pairs used to store complex data. Keys are strings or symbols, and values can be of any type.
let person = { name: "John", age: 30 };
console.log(person.name); // Output: John

Arrays - Common Operations

  • Accessing elements: array[index]
  • Modifying elements: array[index] = value
  • Adding an element to the end: array.push(value)
  • Removing the last element: array.pop()
  • Inserting an element at a specific index: array.splice(index, 0, value)
  • Removing elements by index: array.splice(index, numberOfElementsToRemove)
  • Finding the index of an element: array.indexOf(value)
  • Reversing the order of elements: array.reverse()
  • Sorting the array in ascending order: array.sort() (default sorting is string comparison, not numerical)
  • Sorting the array in descending order: array.sort((a, b) => b - a)
  • Finding the maximum value: Math.max(...array) or array.reduce((acc, val) => Math.max(acc, val), Number.MIN_VALUE)
  • Finding the minimum value: Math.min(...array) or array.reduce((acc, val) => Math.min(acc, val), Number.MAX_VALUE)

Data Types

JavaScript has several primitive data types:

  1. Number: Represents numerical values, including integers and floating-point numbers.
let number = 42;
console.log(number); // Output: 42
  1. String: Represents sequences of characters, enclosed in single or double quotes.
let str = "Hello, World!";
console.log(str); // Output: Hello, World!
  1. Boolean: Represents true (true) or false (false).
let isDone = true;
console.log(isDone); // Output: true
  1. Null: Represents the intentional absence of any object value.
let nothing = null;
console.log(nothing); // Output: null
  1. Undefined: Represents a variable that has been declared but has not yet been assigned a value or has been explicitly set to undefined.
let undef;
console.log(undef); // Output: undefined
  1. Symbol: A new data type in ES6, used as unique keys for objects.
let sym = Symbol("uniqueKey");
let obj = { [sym]: "symbol value" };
console.log(obj[sym]); // Output: symbol value

Type Coercion

JavaScript automatically converts data types when necessary, a process known as type coercion. This can lead to unexpected behavior and bugs, so it's essential to understand how JavaScript handles different data types in various situations. For example:

let sum = 1 + "2"; // Output: "12" (string concatenation)
let product = 3 * "4"; // Output: 12 (multiplication followed by string conversion)
let comparison = 5 > "2"; // Output: true (numbers are converted to strings for comparison)

Worked Example

Let's create an array of numbers and manipulate its elements using various methods:

let numbers = [1, 2, 3, 4, 5];

// Accessing elements
console.log(numbers[0]); // Output: 1
console.log(numbers[numbers.length - 1]); // Output: 5

// Modifying elements
numbers[0] = 10;
console.log(numbers); // Output: [10, 2, 3, 4, 5]

// Adding an element to the end
numbers.push(6);
console.log(numbers); // Output: [10, 2, 3, 4, 5, 6]

// Removing the last element
numbers.pop();
console.log(numbers); // Output: [10, 2, 3, 4, 6]

// Inserting an element at index 2
numbers.splice(2, 0, 15);
console.log(numbers); // Output: [10, 2, 15, 3, 4, 6]

// Removing elements by index (removes the first two elements)
numbers.splice(0, 2);
console.log(numbers); // Output: [15, 3, 4, 6]

// Finding the index of an element
let index = numbers.indexOf(15);
console.log(index); // Output: 0

// Sorting the array in ascending order
numbers.sort();
console.log(numbers); // Output: [3, 4, 6, 15]

// Sorting the array in descending order
numbers.sort((a, b) => b - a);
console.log(numbers); // Output: [15, 6, 4, 3]

// Finding the maximum value
console.log(Math.max(...numbers)); // Output: 15

// Finding the minimum value
console.log(Math.min(...numbers)); // Output: 3

Common Mistakes

  1. Forgetting to initialize arrays: Always ensure that you initialize your arrays before using them.
let numbers = []; // Correct

// Incorrect: JavaScript will create an array with a single undefined element
let numbers = [undefined];
  1. Incorrect array indexing: Remember that array indices start at 0, and going out of bounds can lead to errors or unexpected behavior.
// Correct: Accessing valid elements
console.log(numbers[0]); // Output: undefined (if not initialized)
console.log(numbers[1]); // Output: 2 (if numbers = [1, 2, 3])

// Incorrect: Going out of bounds
console.log(numbers[-1]); // ReferenceError: Invalid array index
console.log(numbers[numbers.length]); // undefined

Common Mistakes - Arrays (Continued)

  1. Misusing the assignment operator: Be careful when using the = operator with arrays, as it creates a new array instead of modifying the existing one.
let numbers = [1, 2];
let numbersCopy = numbers; // Both variables now point to the same array
numbers[0] = 3; // Changing numbers also changes numbersCopy
console.log(numbers); // Output: [3, 2]
console.log(numbersCopy); // Output: [3, 2]

let numbers2 = [1, 2];
let numbers3 = numbers2.slice(); // Creating a copy of the array using the slice method
numbers3[0] = 4; // Changing numbers3 does not affect numbers2
console.log(numbers2); // Output: [1, 2]
console.log(numbers3); // Output: [4, 2]

Practice Questions

  1. Write a function that takes an array and returns the sum of its elements.
function sumArray(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
console.log(sumArray([1, 2, 3, 4])); // Output: 10
  1. Create an object with properties for a person's name, age, and occupation. Add methods to update the person's age and occupation.
let person = {
name: "John",
age: 30,
occupation: "Developer",
updateAge: function(newAge) {
this.age = newAge;
},
updateOccupation: function(newOccupation) {
this.occupation = newOccupation;
}
};
console.log(person); // Output: { name: "John", age: 30, occupation: "Developer" }
person.updateAge(31);
console.log(person); // Output: { name: "John", age: 31, occupation: "Developer" }
person.updateOccupation("Engineer");
console.log(person); // Output: { name: "John", age: 31, occupation: "Engineer" }
  1. Write a function that checks if a given value is a number, string, boolean, null, or undefined.
function checkType(value) {
if (typeof value === 'number') {
return "Number";
} else if (typeof value === 'string') {
return "String";
} else if (value === true || value === false) {
return "Boolean";
} else if (value === null) {
return "Null";
} else if (value === undefined) {
return "Undefined";
} else {
return "Unknown Type";
}
}
console.log(checkType("Hello")); // Output: "String"
console.log(checkType(42)); // Output: "Number"
console.log(checkType(true)); // Output: "Boolean"
console.log(checkType(null)); // Output: "Null"
console.log(checkType(undefined)); // Output: "Undefined"
console.log(checkType({})); // Output: "Object"

FAQ

  1. What happens when you try to access an invalid index in an array?
  • In JavaScript, trying to access an invalid index (out of bounds) will return undefined for arrays and throw a RangeError for strings.
  1. What is the difference between null and undefined?
  • null represents the intentional absence of any object value, while undefined means that a variable has been declared but not yet assigned a value or has been explicitly set to undefined.
  1. How do I create a new array with specific values using a loop?
  • You can create a new array with specific values using a loop (for, for-of, or while) and the push method:
let numbers = [];
for (let i = 0; i < 10; i++) {
numbers.push(i);
}
console.log(numbers); // Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Data structures and types (JavaScript) | JavaScript | XQA Learn