JavaScript Data Types

Primitive Data Types

In JavaScript, primitive data types are data that represent single values. They are immutable, meaning their values cannot be changed. JavaScript has six main primitive data types:

  1. String
  2. Number
  3. Boolean
  4. Undefined
  5. Null
  6. Symbol

1. String

Strings are sequences of characters used to represent text in JavaScript. Strings are wrapped in single (' '), double (" "), or template literals (` `).

Example:

let name = "Alice";
let greeting = 'Hello, world!';
let message = `Welcome, ${name}!`;  // Using template literals for string interpolation
console.log(message);  // Outputs: Welcome, Alice!

Common String Methods:

  • .length - Gets the length of a string.
  • .toUpperCase() - Converts string to uppercase.
  • .toLowerCase() - Converts string to lowercase.
  • .includes() - Checks if a string contains a substring.

2. Number

JavaScript has a single data type for numbers (both integers and floating-point numbers).

Example:

let age = 25;
let price = 19.99;
let total = age + price;
console.log(total); // Outputs: 44.99

Special Number Values:

  • Infinity - A value representing infinity.
  • NaN - Stands for “Not-a-Number”; a result of invalid mathematical operations.

Example of NaN:

console.log("hello" * 3); // Outputs: NaN

3. Boolean

Booleans represent one of two values: true or false. They are often used in conditional statements.

Example:

let isMember = true;
let hasAccess = false;
console.log(isMember && hasAccess); // Outputs: false

4. Undefined

A variable that has been declared but not assigned a value is undefined.

Example:

let user;
console.log(user); // Outputs: undefined

5. Null

null is an assignment value that represents no value. It is explicitly assigned to a variable to indicate that it’s empty.

Example:

let response = null;
console.log(response); // Outputs: null

6. Symbol

Introduced in ES6, Symbol is a unique, immutable data type that can be used as a key in an object. Symbols are useful when you want to create unique identifiers.

Example:

let sym1 = Symbol("id");
let sym2 = Symbol("id");
console.log(sym1 === sym2); // Outputs: false, because each symbol is unique

Practical Examples of Data Types and Variables

Here are some examples that combine variables and different data types:

Example 1: User Profile

const username = "john_doe"; // String
let age = 30;                // Number
let isVerified = true;       // Boolean
let membership = null;       // Null, indicating no membership

console.log(`Username: ${username}`);
console.log(`Age: ${age}`);
console.log(`Verified: ${isVerified}`);
console.log(`Membership: ${membership}`);

Example 2: Shopping Cart

let cartTotal = 0;
const taxRate = 0.08;
const cartItems = ["book", "pen"];

cartTotal = cartTotal + 10; // Adding book price
cartTotal = cartTotal + 1;  // Adding pen price

console.log(`Items: ${cartItems}`);
console.log(`Total: $${cartTotal + (cartTotal * taxRate)}`);

Complex Data Types

Objects

An object in JavaScript is a collection of key-value pairs, where the keys (or properties) are unique identifiers (usually strings), and the values can be of any data type (primitive or complex). Objects allow you to group related data and functionality together, which makes them extremely useful for representing real-world entities.

Creating an Object

You can create an object using the object literal syntax or the Object constructor.

Using Object Literal Syntax:

let person = {
    name: "Alice",
    age: 30,
    isMember: true
};

Using the Object Constructor:

let person = new Object();
person.name = "Alice";
person.age = 30;
person.isMember = true;

Accessing Object Properties

You can access object properties using dot notation or bracket notation.

Dot Notation:

console.log(person.name); // Outputs: Alice

Bracket Notation (useful if the property name is stored in a variable or contains special characters):

console.log(person["age"]); // Outputs: 30

Modifying Object Properties

You can modify existing properties or add new ones.

person.age = 31; // Modify an existing property
person.email = "[email protected]"; // Add a new property
console.log(person);

Deleting Object Properties

To remove a property, use the delete operator:

delete person.isMember;
console.log(person); // `isMember` property is removed

Nested Objects

Objects can contain other objects, allowing for nested data structures.

let student = {
    name: "Bob",
    contact: {
        email: "[email protected]",
        phone: "123-456-7890"
    },
    grades: {
        math: 90,
        science: 85
    }
---
};
console.log(student.contact.email); // Outputs: [email protected]

Common Object Methods

Some common methods for working with objects include:

  • Object.keys(obj) - Returns an array of the object’s keys.
  • Object.values(obj) - Returns an array of the object’s values.
  • Object.entries(obj) - Returns an array of key-value pairs in the object.

Example:

console.log(Object.keys(person));   // Outputs: ["name", "age", "email"]
console.log(Object.values(person)); // Outputs: ["Alice", 31, "[email protected]"]

Arrays

An array is a special type of object that stores an ordered list of values. Each value in an array is called an element and has an index that represents its position within the array. Arrays are often used to store lists or collections of data.

Creating an Array

You can create arrays using the array literal syntax or the Array constructor.

Using Array Literal Syntax:

let fruits = ["apple", "banana", "cherry"];

Using the Array Constructor:

let fruits = new Array("apple", "banana", "cherry");

Accessing Array Elements

Elements are accessed using their index. Indexes in arrays start from 0.

console.log(fruits[0]); // Outputs: "apple"
console.log(fruits[2]); // Outputs: "cherry"

Modifying Array Elements

You can modify elements in an array by assigning a new value to a specific index.

fruits[1] = "blueberry"; // Replace "banana" with "blueberry"
console.log(fruits);     // Outputs: ["apple", "blueberry", "cherry"]

Array Properties and Methods

Arrays have various properties and methods for working with elements:

  • .length - Returns the number of elements in the array.
  • .push() - Adds an element to the end of the array.
  • .pop() - Removes the last element of the array.
  • .shift() - Removes the first element of the array.
  • .unshift() - Adds an element to the beginning of the array.
  • .splice() - Adds/removes elements at a specified index.
  • .slice() - Extracts a section of the array.

Example of Using Array Methods:

fruits.push("orange");    // Adds "orange" to the end
console.log(fruits);      // Outputs: ["apple", "blueberry", "cherry", "orange"]

fruits.pop();             // Removes the last element
console.log(fruits);      // Outputs: ["apple", "blueberry", "cherry"]

fruits.unshift("mango");  // Adds "mango" to the beginning
console.log(fruits);      // Outputs: ["mango", "apple", "blueberry", "cherry"]

let citrus = fruits.slice(1, 3); // Extracts elements from index 1 to 2 (not inclusive of 3)
console.log(citrus);       // Outputs: ["apple", "blueberry"]

Looping Through Arrays

You can use various loops to iterate over arrays, such as for loops, forEach, or map.

Example with for Loop:

for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

Example with forEach Method:

fruits.forEach(function(fruit) {
    console.log(fruit);
});

Nested Arrays

Arrays can contain other arrays, forming a nested array or multidimensional array.

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
console.log(matrix[1][2]); // Outputs: 6 (second row, third column)

Practical Examples with Objects and Arrays

Here are a few examples that demonstrate how to use objects and arrays in a practical context:

Example 1: Representing a Library of Books

let library = [
    {
        title: "To Kill a Mockingbird",
        author: "Harper Lee",
        year: 1960
    },
    {
        title: "1984",
        author: "George Orwell",
        year: 1949
    },
    {
        title: "The Great Gatsby",
        author: "F. Scott Fitzgerald",
        year: 1925
    }
];

library.forEach(book => {
    console.log(`${book.title} by ${book.author}`);
});

Example 2: Student Grades with Nested Objects and Arrays

let student = {
    name: "John Doe",
    grades: {
        math: [85, 90, 78],
        science: [88, 72, 91],
        literature: [95, 88, 92]
    }
};

let averageMathGrade = student.grades.math.reduce((sum, grade) => sum + grade, 0) / student.grades.math.length;
console.log(`Average Math Grade: ${averageMathGrade}`);

Last updated on