JavaScript Data Types

Understanding the fundamental data types in JavaScript

JavaScript Data Types

JavaScript is a dynamically typed language, which means variables can hold different types of data. Understanding these data types is crucial for effective programming.

Primitive Data Types

JavaScript has six primitive data types:

  • String: Textual data
  • Number: Numeric data (integers and floating-point numbers)
  • Boolean: Logical entity (true or false)
  • Undefined: A variable that has been declared but not assigned a value
  • Null: Intentional absence of any object value
  • Symbol: Unique identifier (introduced in ES6)
let name = "John"; // String
let age = 30; // Number
let isStudent = true; // Boolean
let job; // Undefined
let salary = null; // Null
let id = Symbol('id'); // Symbol

Object Data Type

In addition to primitive data types, JavaScript has an Object data type. Objects are used to store collections of data and more complex entities.

let person = {
name: "John",
age: 30,
isStudent: true
};

Special Data Types

JavaScript also has some special data types:

  • Array: A special type of object used to store multiple values in a single variable
  • Function: A callable object
  • Date: Represents a single moment in time in a platform-independent format

Type Coercion

JavaScript is a loosely typed language, which means it can automatically convert between types. This is known as type coercion.

console.log("5" + 2); // Outputs: "52" (string)
console.log("5" - 2); // Outputs: 3 (number)

Checking Data Types

You can use the typeof operator to check the type of a variable:

console.log(typeof "Hello"); // Outputs: "string"
console.log(typeof 42); // Outputs: "number"
console.log(typeof true); // Outputs: "boolean"

Understanding data types is fundamental to working with JavaScript effectively. It helps in writing more efficient and error-free code.