JavaScript : Data Types

In JavaScript, data types specify the type of data that a variable can hold. JavaScript is a loosely typed language, which means variables can hold values of any data type without explicitly specifying the data type. Here are the primary data types in JavaScript:

1. Primitive Data Types:


Primitive data types are the most basic data types in JavaScript. They include:

a. Number:
Represents numeric values, including integers and floating-point numbers.


let age = 30;
let pi = 3.14;

 

b. String:
Represents textual data enclosed within single (' ') or double (" ") quotes.


let name = "John";
let message = 'Hello';

 

c. Boolean:
Represents a logical value indicating true or false.


let isStudent = true;
let hasLicense = false;

 

d. Undefined:
Represents a variable that has been declared but not assigned a value.


let x;
console.log(x);  // Output: undefined

 

e. Null:
Represents the intentional absence of any object value.


let car = null;
 

f. Symbol:
Introduced in ECMAScript 6 (ES6), represents a unique and immutable data type.


let id = Symbol("id");
 

2. Complex Data Types:


Complex data types are collections of data and are composed of primitive data types or other complex data types. They include:

a. Object:
Represents a collection of key-value pairs, where each value is accessed by a unique key (property name).


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

 

b. Array:
Represents an ordered list of values, accessed by index starting from zero.


let colors = ["red", "green", "blue"];
 

Determining Data Types:


JavaScript provides the typeof operator to determine the data type of a variable or expression.


let x = 10;
console.log(typeof x);  // Output: "number"

let y = "Hello";
console.log(typeof y);  // Output: "string"

 

Dynamic Typing:


JavaScript is dynamically typed, meaning the data type of a variable can change during the execution of a program.


let z = 10;
z = "Hello";  // Now z holds a string value

 

Conclusion:


Understanding data types is crucial for writing JavaScript code. JavaScript's flexibility with data types allows for dynamic and versatile programming. By understanding the different data types available and how to use them, you can effectively store and manipulate data in your JavaScript programs.