Skip to content

JavaScript Data Types

JavaScript data types define the kinds of values and the operations that can be performed on them. Understanding JavaScript data types is crucial for writing effective code. Data types in JavaScript can be divided into two main categories: Primitive Types and Reference Types.

Primitive Data Types

Primitive data types are the most basic data types. They are immutable and stored directly in stack memory. JavaScript has 7 primitive data types:

1. Number Type

The number type is used to represent both integers and floating-point numbers.

javascript
let integer = 42;           // Integer
let float = 3.14159;        // Floating-point number
let negative = -10;         // Negative number
let scientific = 1.23e5;    // Scientific notation

// Special number values
let infinity = Infinity;    // Positive infinity
let negativeInfinity = -Infinity; // Negative infinity
let notANumber = NaN;       // Not a Number

console.log(1 / 0);         // Infinity
console.log("not a number" / 2); // NaN

2. BigInt Type

BigInt is a numeric type that can represent arbitrarily large integers.

javascript
let bigNumber = 1234567890123456789012345678901234567890n;
let anotherBigNumber = BigInt("1234567890123456789012345678901234567890");

console.log(bigNumber + 1n); // Can perform operations

3. String Type

The string type is used to represent text data, enclosed in single quotes, double quotes, or backticks.

javascript
let singleQuote = 'Single quote string';
let doubleQuote = "Double quote string";
let backtick = `Backtick string`;

// Strings can contain quotes
let message = "He said: 'Hello!'";
let anotherMessage = 'She said: "Goodbye!"';

// Template strings (using backticks)
let name = "John";
let greeting = `Hello, ${name}!`; // Insert variable using ${}
console.log(greeting); // Output: Hello, John!

4. Boolean Type

The boolean type has only two values: true and false.

javascript
let isTrue = true;
let isFalse = false;

// Boolean values often come from comparison operations
let isGreater = 5 > 3;  // true
let isEqual = 5 === 3;  // false

// Used in conditional statements
if (isGreater) {
    console.log("5 is greater than 3");
}

5. Undefined Type

The undefined type has only one value: undefined. When a variable is declared but not assigned a value, its default value is undefined.

javascript
let emptyVariable;
console.log(emptyVariable); // undefined

let explicitUndefined = undefined;
console.log(explicitUndefined); // undefined

6. Null Type

The null type also has only one value: null. It represents "no value" or "empty value".

javascript
let emptyValue = null;
console.log(emptyValue); // null

// null is often used to initialize variables, indicating that there's no value yet
let user = null; // Indicates no user data yet

7. Symbol Type

Symbol is a unique, immutable data type, typically used as keys for object properties.

javascript
let sym1 = Symbol("description");
let sym2 = Symbol("description");

console.log(sym1 === sym2); // false, each Symbol is unique

// Symbols are often used as object property keys to avoid naming conflicts
let id = Symbol("id");
let user = {
    name: "John",
    [id]: 123
};

Reference Data Types

Reference types are stored in heap memory, and variables store references (addresses) pointing to the actual data. The main reference type in JavaScript is Object.

Object Type

An object is a collection of key-value pairs that can contain multiple data types and functions.

javascript
let person = {
    name: "John",
    age: 25,
    isStudent: true,
    hobbies: ["reading", "swimming", "coding"],
    address: {
        city: "New York",
        street: "Main Street"
    },
    greet: function() {
        return "Hello, I'm " + this.name;
    }
};

console.log(person.name); // Access property
console.log(person["age"]); // Another way to access property
console.log(person.greet()); // Call method

Array Type

An array is a special type of object used to store ordered collections of data.

javascript
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "string", true, {name: "John"}];

console.log(fruits[0]); // Access array element
console.log(fruits.length); // Get array length

// Array methods
fruits.push("grape"); // Add element
fruits.pop(); // Remove last element

Function Type

Functions are also objects. In JavaScript, functions are first-class citizens.

javascript
// Function declaration
function add(a, b) {
    return a + b;
}

// Function expression
let multiply = function(a, b) {
    return a * b;
};

// Arrow function
let subtract = (a, b) => a - b;

console.log(add(5, 3)); // 8
console.log(multiply(4, 2)); // 8
console.log(subtract(10, 3)); // 7

Date Type

The Date object is used to handle dates and times.

javascript
let now = new Date(); // Current date and time
let specificDate = new Date("2024-01-01"); // Specific date
let customDate = new Date(2024, 0, 1, 12, 0, 0); // Year, month, day, hour, minute, second

console.log(now.getFullYear()); // Get year
console.log(now.getMonth()); // Get month (0-11)
console.log(now.getDate()); // Get day

Type Detection

JavaScript provides several methods to detect data types:

typeof Operator

javascript
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (this is a historical bug in JavaScript)
console.log(typeof Symbol("id")); // "symbol"
console.log(typeof BigInt(123)); // "bigint"
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"

Array.isArray() Method

javascript
console.log(Array.isArray([])); // true
console.log(Array.isArray({})); // false

instanceof Operator

javascript
let arr = [];
let obj = {};

console.log(arr instanceof Array); // true
console.log(obj instanceof Object); // true
console.log(arr instanceof Object); // true (arrays are also objects)

Type Conversion

JavaScript automatically performs type conversion in certain situations:

Implicit Conversion

javascript
console.log("5" + 3); // "53" (string concatenation)
console.log("5" - 3); // 2 (numeric operation)
console.log(true + 1); // 2 (true converts to 1)
console.log(false + 1); // 1 (false converts to 0)

Explicit Conversion

javascript
// Convert to string
let num = 123;
let str = String(num); // "123"
let str2 = num.toString(); // "123"

// Convert to number
let strNum = "123";
let num1 = Number(strNum); // 123
let num2 = parseInt("123.45"); // 123
let num3 = parseFloat("123.45"); // 123.45

// Convert to boolean
let truthy = Boolean("hello"); // true
let falsy = Boolean(""); // false
let falsy2 = Boolean(0); // false
let falsy3 = Boolean(null); // false

Characteristics of Data Types

Immutability of Primitive Types

javascript
let str = "hello";
str[0] = "H"; // This won't change the string
console.log(str); // Still "hello"

// To change a string, you need to reassign it
str = "Hello";
console.log(str); // "Hello"

Mutability of Reference Types

javascript
let arr = [1, 2, 3];
arr[0] = 10; // Can directly modify array elements
console.log(arr); // [10, 2, 3]

let obj = {name: "John"};
obj.name = "Jane"; // Can directly modify object properties
console.log(obj); // {name: "Jane"}

Pass by Value vs Pass by Reference

javascript
// Primitive types are passed by value
let a = 10;
let b = a;
b = 20;
console.log(a); // 10 (a is unchanged)

// Reference types are passed by reference
let arr1 = [1, 2, 3];
let arr2 = arr1;
arr2[0] = 10;
console.log(arr1); // [10, 2, 3] (arr1 is also changed)

Summary

JavaScript data types include:

  1. Primitive Types (7 types):

    • Number
    • BigInt
    • String
    • Boolean
    • Undefined
    • Null
    • Symbol
  2. Reference Types (mainly Object):

    • Object
    • Array
    • Function
    • Date
    • RegExp, etc.

Understanding these data types and their characteristics is very important for writing high-quality JavaScript code. In the next chapter, we will learn about JavaScript's basic structure.

Content is for learning and research only.