Data Types

Explore the fundamental data types in JavaScript, including both primitive and reference types, which form the basis for handling and manipulating data in programs.

Present State

JavaScript supports a dynamic typing system where variables can hold multiple types during execution. Data types in JavaScript are broadly categorized into primitive types (like string, number, boolean, null, undefined, symbol, bigint) and reference types (like objects, arrays, functions). Understanding these types is crucial for writing robust and predictable code.

Code Example

This code snippet demonstrates how various data types are used in JavaScript:

JavaScript Data Types

// Primitive types
let name = "Alice";            // String
let age = 25;                  // Number
let isStudent = true;          // Boolean
let unknown = undefined;       // Undefined
let empty = null;              // Null
let id = Symbol("id");         // Symbol
let bigIntValue = 123456789012345678901234567890n; // BigInt

// Reference types
let person = { name: "Alice", age: 25 }; // Object
let colors = ["red", "green", "blue"];   // Array
function greet() { console.log("Hello"); } // Function
          

This code demonstrates:

  • Declaration and usage of primitive data types
  • Creation of object and array reference types
  • Usage of BigInt and Symbol for special use cases

Description

JavaScript variables can hold different types of data. These are categorized into:
  • Primitive Types: These include string, number, boolean, null, undefined, symbol, and bigint. They are immutable and stored by value.
  • Reference Types: Includes objects, arrays, and functions. These are mutable and stored by reference.
Type checking can be performed using typeof for most types and Array.isArray() or instanceof for reference types.

Applications

  • Web Development: Store user inputs, preferences, and responses.
  • APIs and Backend: Handle structured data with objects and arrays.
  • Form Validation: Check and enforce types for user input fields.
  • Data Structures: Build complex logic using objects and arrays as data containers.

Multiple Choice Questions

Q1: What type does typeof null return?

  • A. "null"
  • B. "object"
  • C. "undefined"
  • D. "boolean"

Answer: B. "object"

Q2: Which of the following is a reference type?

  • A. Number
  • B. String
  • C. Object
  • D. Boolean

Answer: C. Object

Q3: What is the result of typeof NaN?

  • A. "NaN"
  • B. "undefined"
  • C. "number"
  • D. "object"

Answer: C. "number"

Q4: Which statement is true about BigInt?

  • A. It can store decimal values.
  • B. It's used for representing very large integers.
  • C. It is a reference type.
  • D. It replaces the number type.

Answer: B. It's used for representing very large integers.