πŸ“˜ Understanding the Basics of JavaScript: Data Types and Data Structures

Santwan PathakSantwan Pathak
12 min read

πŸ”° 1. Introduction

One of the first steps to becoming proficient in JavaScript is to understand its core foundations: data types and data structures. These elements determine how data is stored, accessed, and manipulated throughout your code.

In this blog, we will explore the different types of data JavaScript supports, how they behave, and the built-in structures available to organize and manage this data effectively. This understanding will not only make your code more robust but also prepare you for solving complex programming problems efficiently.

🧱 2. JavaScript Data Types

βž” 2.1. Classification

JavaScript broadly classifies its data types into two major categories based on how they are stored and accessed in memory. This classification helps developers better manage data flow and understand the behavior of variables during assignment and manipulation.

Primitive Types:

These represent simple and immutable values. They are stored directly in the memory location associated with the variable and include types like String, Number, Boolean, Undefined, Null, Symbol, and BigInt. Each holds a single value and operations on them do not affect other variables.

Non-Primitive (Reference) Types:

These refer to complex data types. Instead of storing the actual value, the variable holds a reference (or address) to the memory location where the data is stored. These types include Object, Array, Function, and other built-in objects like Map, Set, etc. They are mutable and shared by reference, which can affect multiple variables pointing to the same data.

βž” 2.2. Primitive Data Types

πŸ’‘
(Immutable, stored by value)

Primitive data types in JavaScript are the most basic units of data.

They hold a single value and are immutable, meaning the value itself cannot be changed once assigned. When a primitive value is assigned to a variable, it is stored directly in that variable’s memory location.

  • String

    • Represents textual data (sequences of characters).

    • Enclosed in single ('), double ("), or backtick (` ) quotes.

    • Useful for labels, messages, template literals, and dynamic content.

    • Example:

        let name = 'Ravi';
        let greeting = "Namaste, dosto!";
        let message = `Good morning, ${name}! Kaise ho?`;
      

      The last line uses template literals (backticks ` ) to embed the value of the name variable directly into the string using ${name}. Template literals for dynamic string creation

  • Number

    • Used for both integer and floating-point calculations.

    • Special numeric values include NaN (Not a Number), Infinity, and -Infinity.

    • JavaScript does not differentiate between integers and floats; both are handled using the same Number type.

    • Helpful built-in methods include toFixed(), parseInt(), and parseFloat() for formatting and conversions.

    • Example:

        // Declare two numbers: one integer and one float
        let marks = 85;
        let percentage = 85.5;
      
        // Add them together
        let total = marks + percentage;
        console.log("Total marks:", total); // 170.5
      
        // Trying to subtract a number from a non-numeric string results in NaN (Not a Number)
        let invalid = "hello" - 2;
        console.log("Invalid calculation (string - number):", invalid); // NaN
      
        // Dividing a number by 0 in JavaScript gives Infinity
        let infiniteValue = 1 / 0;
        console.log("Division by zero gives:", infiniteValue); // Infinity
      
        // Using toFixed() to round a floating-point number to 2 decimal places
        let pi = 3.14159;
        console.log("Pi rounded to 2 decimal places:", pi.toFixed(2)); // 3.14
      
        // String that looks like a number
        let numString = "42.5";
        console.log(`numString variable: ${numString} and type: ` + typeof numString); // "string"
      
        // parseInt() converts to integer (drops decimal part)
        numString = parseInt(numString);
        console.log(`numString variable after parseInt: ${numString} and type: ` + typeof numString); // 42, number
      
        // Resetting value to string and using parseFloat()
        numString = "42.5";
        numString = parseFloat(numString);
        console.log(`numString variable after parseFloat: ${numString} and type: ` + typeof numString); // 42.5, number
      
  • Boolean

    • Represents a logical entity, often used to express binary decisions or toggle states.

    • Only two possible values: true and false.

    • Commonly used in conditionals, control flow, and logical operations such as comparisons (==, >, <) and equality checks.

    • Can be the result of expressions like 5 > 3 or a === b.

    • Useful in loops, toggles, form validations, and visibility toggling in UIs.

    • Example:

        let isLoggedIn = true;
        if (isLoggedIn) {
          console.log("Welcome back!");
        } else {
          console.log("Please log in.");
        }
      
        let hasAccess = 5 > 3;
        console.log("User has access:", hasAccess); // true
      
  • Undefined

    • A variable that has been declared but not assigned a value will automatically hold the value undefined in JavaScript.

    • It indicates the absence of initialization and serves as a placeholder for uninitialized memory.

    • undefined is a primitive type and is distinct from null.

    • Often returned by functions that do not explicitly return a value.

    • Useful in debugging to check if a variable was intentionally or unintentionally left uninitialized.

    • Example:

        let x;
        console.log(x); // undefined
      
        function sayHello() {
          console.log("Hello");
        }
        let result = sayHello();
        console.log(result); // undefined
      
  • Null

    • Represents an explicitly assigned empty or non-existent value, signifying intentional absence.

    • Unlike undefined, which indicates a variable hasn’t been assigned, null is set manually to represent an empty or neutral state.

    • Often used to reset or clear a variable’s value, especially before assigning a new value later in the program.

    • Commonly used in object fields, form handling, or when initializing values that are meant to be filled in later.

    • Example:

        let userSession = null; // No active session yet
      
        // Later, when a user logs in
        userSession = {
          username: "rahul123",
          token: "abcd1234"
        };
        console.log(userSession);
      
  • Symbol

    • Introduced in ES6 as a new primitive data type.

    • Used to create unique identifiers, often as keys in objects to avoid accidental overwriting or property name collisions.

    • Symbols are always unique, even if they have the same description, ensuring that each Symbol value is truly one-of-a-kind.

    • Particularly useful in situations where you want to add private or hidden properties to an object that won't interfere with other code or libraries.

    • Symbols are not enumerable in for...in loops and are skipped in JSON.stringify(), offering a degree of hidden behavior.

    • It will be discussed in more detail in my upcoming react blogs. There, you will able to visualize that.

    • Example:

      ```javascript const id1 = Symbol("userID"); const id2 = Symbol("userID");

      console.log(id1 === id2); // false

      const user = { name: "Amit",

};

console.log(user); // Symbol-keyed property won't show up in console directly console.log(userid1); // 101



**BigInt**

* Allows representation of integers beyond the safe integer limit of `Number`, which is `2^53 - 1` or `9007199254740991`.

* Declared by appending `n` to the end of an integer, like `12345678901234567890n`.

* Useful for preserving accuracy in domains like cryptography, finance, scientific calculations, or blockchain, where very large numbers are common.

* Unlike `Number`, `BigInt` does not support fractional values (decimals).

* Arithmetic between `BigInt` and regular `Number` types will throw an error unless explicitly converted.

* Example:

    ```javascript
    const big = 987654321987654321987654321n;
    console.log("BigInt value:", big);

    const small = 10;

    // This will throw an error:
    // console.log(big + small); // ❌ TypeError: Cannot mix BigInt and other types

    // Correct way:
    console.log(big + BigInt(small)); // βœ… Works fine

βž” 2.3. Non-Primitive Data Types

πŸ’‘
(Mutable, stored by reference)

Non-primitive data types in JavaScript are used to represent more complex structures and behaviors than primitive types. These data types do not hold actual values directly; instead, variables store a reference (or pointer) to the memory location where the data is stored. This means that when a reference-type value is assigned to another variable or passed to a function, both variables refer to the same object in memory.

These types are mutable, which allows their contents to be updated or changed without altering their memory reference. This makes them especially useful for modeling real-world entities, maintaining collections of data, or encapsulating behavior through reusable functions.

In JavaScript, the term β€œobject” refers to any data type that is non-primitive and behaves like a reference type β€” which includes Object, Array, Function, Map, Set, etc.

JavaScript provides several non-primitive types by default:

  • Object – A general-purpose structure used to store key-value pairs, often to represent structured data such as user profiles or configuration settings.

  • Array – A specialized object for storing ordered collections of values, frequently used for lists, queues, and data manipulation.

  • Function – A callable object that encapsulates a block of code and can be invoked with parameters to produce results or side effects.

  • Date, RegExp, Map, Set, etc. – Specialized built-in objects for tasks like date/time manipulation, pattern matching with regular expressions, and managing collections with unique keys or values.

πŸ“ƒ 3. JavaScript Data Structures

βž” 3.1. Array

  • Ordered collection of elements, where each item has a numeric index starting from 0.

  • Indexed access allows you to retrieve, update, or remove elements based on their position.

  • Arrays can store mixed data types (e.g., numbers, strings, objects), though they're commonly used for uniform lists.

  • Arrays are dynamic, meaning you can add or remove elements at runtime.

  • Common methods include:

    • .push() – adds an element to the end of the array

    • .pop() – removes the last element

    • .shift() – removes the first element

    • .unshift() – adds an element to the beginning

    • .map() – creates a new array by applying a function to each element

    • .filter() – returns a new array with elements that meet a condition

    • .forEach() – executes a function for each element, but does not return a new array

  • Example:

      // Here's our list of fruits
      let fruits = ["mango", "banana", "apple"];
      console.log("Original fruits:", fruits); // Output: Original fruits: ["mango", "banana", "apple"]
    
      // Now, let's add "orange" to the end of our list
      fruits.push("orange");
      console.log("Fruits after adding orange:", fruits); // Output: Fruits after adding orange: ["mango", "banana", "apple", "orange"]
    

    Later other array methods will be discussed in depth in a separate in any of the upcoming blog. Please search in my coffee and code blog if you interested in my blogs.

βž” 3.2. Object

  • Key-value pair structure where keys are strings (or Symbols) and values can be of any type including other objects.

  • Properties are the individual key-value pairs, and methods are functions stored as object properties.

  • Objects can be used to model real-world entities and group related data together, making them a fundamental building block in JavaScript programming.

  • You can dynamically add, update, or delete properties using either dot notation or bracket notation.

  • Dot notation is more concise and readable, while bracket notation is useful when property names are dynamic or contain special characters. Want to know more about this ? Click on LINK

  • Example:

      const student = {
        name: "Suman",
        age: 22,
        isGraduate: true
      };
    
      console.log(student.name);         // Access using dot notation
      console.log(student["age"]);       // Access using bracket notation
    
      student.city = "Kolkata";          // Add new property
      student["country"] = "India";     // Add using bracket notation
    
      delete student.isGraduate;         // Remove a property
      console.log(student);
    

βž” 3.3. Map

  • A Map is a built-in JavaScript object that stores data in the form of key-value pairs, similar to an object but with greater flexibility.

  • Unlike regular objects, Map maintains the insertion order of keys, which means the order in which you add elements is preserved.

  • One key advantage of Map is that keys can be of any data type, including objects, functions, or primitive types.

  • This makes Map especially useful when you need a reliable and predictable structure for associating values with unique identifiers.

  • Commonly used methods include:

    • .set(key, value) – Adds or updates an entry

    • .get(key) – Retrieves the value associated with the key

    • .has(key) – Checks whether a specific key exists

    • .delete(key) – Removes a key-value pair from the map

  • Example:

      const userRoles = new Map();
      userRoles.set("Suman", "Admin");
      userRoles.set("Ravi", "Editor");
      userRoles.set("Neha", "Viewer");
    
      console.log(userRoles.get("Ravi")); // Output: Editor
      console.log(userRoles.has("Neha")); // Output: true
    
      userRoles.delete("Suman");
      console.log(userRoles); // Map now has 2 entries
    

? Can Objects Also Have Keys of Any Data Type Like Map?

Short answer: Not really. Objects in JavaScript can only have strings or symbols as keys β€” even if you try to use another data type (like a number, object, or function), JavaScript will coerce it into a string.

πŸ’‘
What Does "Coerce" Mean in JavaScript? In JavaScript, type coercion refers to the automatic or implicit conversion of values from one data type to another. This can happen in operations involving different types.

When we say that JavaScript coerces object keys into strings in a normal object, we mean:

If you try to use a non-string (like an object or number) as a key in a regular JavaScript object, JavaScript will automatically convert β€” or coerce β€” it to a string behind the scenes.

πŸ”΄ Example with Object:

const obj = {};
const keyObj = { id: 1 };
obj[keyObj] = "value";

console.log(obj); // Output: { '[object Object]': 'value' }

Here, even though keyObj is an object, it was automatically converted to the string "[object Object]", meaning:

  • You lose uniqueness if multiple object keys stringify to the same value.

  • This behavior can cause key collisions.

βœ… Example with Map:

const map = new Map();
const keyObj = { id: 1 };
map.set(keyObj, "value");

console.log(map.get(keyObj)); // Output: "value"

Here, the Map retains the actual object reference as the key, preserving uniqueness and expected behavior.

FeatureObjectMap
Key types allowedStrings and Symbols onlyAny data type (object, function, etc.)
Key uniquenessBased on string conversionBased on actual reference
Use case for non-string keys❌ Not reliableβœ… Fully supported and reliable

βž” 3.4. Set

  • A Set is a built-in JavaScript object designed to store unique values, ensuring that no duplicates are present.

  • Sets are particularly useful when you want to track the presence or uniqueness of items, such as user IDs, tags, or selected filters.

  • Unlike arrays, Sets do not allow indexing, but they are iterable, meaning you can loop through their values using for...of or other iteration methods.

  • You can store any data type inside a Set: numbers, strings, objects, etc.

  • Commonly used methods include:

    • .add(value) – Adds a new unique value to the Set

    • .has(value) – Checks if a value exists in the Set

    • .delete(value) – Removes a specific value from the Set

  • Example:

      const selectedCourses = new Set();
      selectedCourses.add("Math");
      selectedCourses.add("Physics");
      selectedCourses.add("Math"); // Duplicate, won't be added again
    
      console.log(selectedCourses.has("Math")); // true
      console.log(selectedCourses); // Set(2) { 'Math', 'Physics' }
    
      selectedCourses.delete("Physics");
      console.log(selectedCourses); // Set(1) { 'Math' }
    
0
Subscribe to my newsletter

Read articles from Santwan Pathak directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Santwan Pathak
Santwan Pathak

"A beginner in tech with big aspirations. Passionate about web development, AI, and creating impactful solutions. Always learning, always growing."