Understanding Data Types and Data Structures in Programming with JavaScript


JavaScript Logo

In software development, data types and data structures are essential elements that every programmer must master. These concepts not only form the foundation of any application but also define how data is handled and manipulated in a program. In this post, we’ll explore what data types and data structures are, using JavaScript, one of the most popular programming languages.

Data Types in JavaScript

JavaScript is a dynamically typed language, which means you don’t need to declare the type of a variable when you define it. However, understanding the available data types is crucial to avoid errors and write clear, efficient code.

1. Primitive Types

Primitive types are the most basic building blocks in JavaScript. Here are some examples:

  • number: Represents both integers and decimals.
let age = 25;
 
let price = 14.50;

Nota: The let keyword is used to declare a variable in JavaScript. In this case, we’re declaring a variable named age that will store the integer 25, and another named price that will store the decimal or floating-point number 14.50. We can omit this for now, as we’ll talk about variables later.

  • string: Represents strings of text.
let name = "Peter";
  • boolean: Represents truth values: true or false.
let isProgrammer = true;
  • null: Represents the intentional absence of any object value.
let nullValue = null;
  • undefined: Indicates that a variable has been declared but has not yet been assigned a value.
let notDefined = undefined;
 
// We can omit the assignment of undefined, and the value of notDefined will be exactly the same
let notDefined
  • symbol: Introduced in ES6, symbols are unique and immutable values that can be used as identifiers.
let id = Symbol("id");

2. Complex Types

In addition to primitive types, JavaScript also handles complex types that allow you to work with more advanced data structures.

  • object: A type that allows storing collections of data in key-value pairs.
let person = {
  name: "Peter",
  age: 25,
  isProgrammer: true
};
  • array: A special type of object that stores elements in an indexed collection. Each element within an array has an index, in JavaScript starting from 0.
let numbers = [1, 2, 3, 4, 5];
 
// To access the first element of this array, we would do the following
let firstElement = numbers[0]; // This would result in the value of the first element, which in this case is 1.

3. Functions and Custom Types

In JavaScript, functions are also a data type. They can be treated as values and can be assigned to variables, passed as arguments, and returned from other functions.

function greet(name) {
  return `Hello, ${name}`;
}
 
let message = greet("Peter"); // This would result in "Hello, Peter".

Additionally, you can define custom types using constructors or classes (introduced in ES6).

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
 
  greet() {
    return `Hello, I’m ${this.name} and I’m ${this.age} years old.`;
  }
}
 
let user = new Person("Peter", 25);
 
user.greet(); // This would result in "Hello, I’m Peter and I’m 25 years old";

Data Structures in JavaScript

Data structures are organized ways of storing and managing data in a program. Below, we’ll explore some of the most common data structures and how they are implemented in JavaScript.

1. Arrays

As we saw earlier, arrays are a type of complex data and are one of the most common data structures. They allow you to store multiple values in a single variable.

let names = ["Peter", "John", "Camila", "Natalia"];

With arrays, you can perform operations such as adding, removing, and iterating over elements, but we’ll cover this in a dedicated post.


Note: The following data structures are a bit more complex if you’re just starting to program. Don’t get discouraged if you don’t understand what the following code does, as it’s not necessary to know this when you’re beginning. Over time, you’ll acquire more and more concepts.


2. Linked Lists

Although they are not directly supported as a predefined data structure in JavaScript, linked lists can be implemented using constructor functions or classes.

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}
 
class LinkedList {
  constructor() {
    this.head = null;
  }
 
  add(value) {
    let newNode = new Node(value);
    if (!this.head) {
      this.head = newNode;
    } else {
      let current = this.head;
      while (current.next) {
        current = current.next;
      }
      current.next = newNode;
    }
  }
}
 
let list = new LinkedList();
list.add(10);
list.add(20);

3. Stacks and Queues

Stacks and queues are linear data structures that allow you to manage collections of elements in particular ways.

  • Stacks: Follow the LIFO (Last In, First Out) principle. The last element added is the first one to be removed.
class Stack {
  constructor() {
    this.elements = [];
  }
 
  push(element) {
    this.elements.push(element);
  }
 
  pop() {
    return this.elements.pop();
  }
}
 
let stack = new Stack();
stack.push(1);
stack.push(2);
let last = stack.pop(); // Returns 2

Note: push adds a new element to the end of the elements array, while pop removes the last element from that array.

  • Queues: Follow the FIFO (First In, First Out) principle. The first element added is the first one to be removed.
class Queue {
  constructor() {
    this.elements = [];
  }
 
  enqueue(element) {
    this.elements.push(element);
  }
 
  dequeue() {
    return this.elements.shift();
  }
}
 
let queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
let first = queue.dequeue(); // Returns 1

Note: shift returns the first element of the elements `array and removes it from that array.

4. Maps and Sets

  • Maps: Are structures that allow you to store key-value pairs, with keys that can be of any type.
let map = new Map();
map.set("one", 1);
map.set("two", 2);
let value = map.get("one"); // Returns 1
  • Sets: Store unique values, automatically eliminating duplicates.
let set = new Set();
set.add(1);
set.add(2);
set.add(2); // 2 won’t be added again

Conclusion

Understanding data types and data structures is essential for writing effective and efficient code. JavaScript, though a dynamically typed language, offers a wide range of data types and data structures that allow you to manage and organize information effectively. Whether you’re manipulating simple data or creating complex structures, mastering these concepts will enable you to develop more robust and scalable applications.

I hope this guide has helped you better understand these programming fundamentals in JavaScript! If you have any questions or suggestions, feel free to reach out!