Skip to main content

Javascript Data Types

Introduction

JavaScript is a dynamic type language, which means you don't have to specify the type of data that a variable is going to hold. However, it's still important to understand the different types of data that JavaScript can handle. In JavaScript, data types are used to identify the type of data used in a program. These data types are broadly categorized into two types: Primitive and Non-Primitive.

Primitive Data Types

Primitive data types in JavaScript are immutable, which means their values cannot be changed. These include:

  1. Number: This data type includes any integer or floating-point numeric value. For example:
let age = 25; // integer
let weight = 65.5; // floating point
  1. String: A string data type is a sequence of characters. For example:
let name = "John Doe"; // string
  1. Boolean: This data type has only two possible values—true or false. For example:
let isAdult = true; // boolean
  1. Null: This type has only one value: null. It means no value or no object. It implies non-existence of value. For example:
let empty = null; // null
  1. Undefined: A variable that has not been assigned a value is of type undefined. For example:
let notDefined; // undefined
  1. Symbol: Introduced in ECMAScript 6, a symbol is a unique and immutable data type that is often used as an identifier for object properties. For example:
let sym = Symbol('description'); // symbol

Non-Primitive Data Types

Non-Primitive data types can hold multiple values and can be changed. They include:

  1. Object: An object is an instance which contains a set of key-value pairs. The values can be scalar values, functions or even other objects. For example:
let person = {firstName:"John", lastName:"Doe", age:25}; // object
  1. Array: An array is a group of like-typed variables that are referred to by a common name. Arrays in JavaScript can work with elements of different data types. For example:
let fruits = ["apple", "banana", "mango"]; // array
  1. Function: Functions are reusable pieces of code that can be isolated or kept together based on logic. They can take inputs and return output. For example:
function add(a, b) {
return a + b;
} // function

Typeof Operator

In JavaScript, you can use the typeof operator to find out what type of data a variable holds. For example:

let name = "John Doe";
console.log(typeof name); // Outputs: string

Conclusion

Understanding data types in JavaScript is crucial for writing efficient code. Different operations can be performed over different data types. Remember, JavaScript is a dynamically typed language, and it automatically assigns the data type to the variable based on its value.

In the next section, we'll explore more about variables and how to use them effectively in JavaScript.