High-level programming language.
In JavaScript, data types are the classifications we give to different kinds of data that we use in programming. In this article, we will explore the different data types in JavaScript and understand their characteristics.
JavaScript is a dynamically typed language, which means that the same variable can be used to hold different data types. In JavaScript, there are two categories of data types: Primitive and Non-primitive.
Primitive data types are the most basic data types in JavaScript. They include:
A string is a sequence of characters. In JavaScript, strings are enclosed within quotes. For example:
let name = "John Doe";
The Number data type is used to represent numeric values. It can be used to represent both integers and floating-point numbers. For example:
let age = 30; let weight = 72.5;
The Boolean data type can hold only two values: true
or false
. It is typically used to store values like yes (true) or no (false), on (true) or off (false), etc.
let isAdult = true;
The Null data type has only one value: null
. It represents a reference that points to a nonexistent or invalid object or address.
let empty = null;
A variable that has not been assigned a value is of type undefined
.
let test; console.log(test); // Output: undefined
Introduced in ES6, a symbol is a unique and immutable data type that is often used as an identifier for object properties.
let symbol1 = Symbol('symbol');
The non-primitive data types are Objects. An object is a collection of properties, and a property is an association between a name (or key) and a value.
let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The main difference between primitive and non-primitive data types is that primitive data types store values directly, while non-primitive data types store references to the values.
JavaScript is a loosely typed language, which means it automatically converts types as needed during the execution of the program. This is known as type coercion. For example, when you try to add a number and a string, JavaScript will convert the number to a string before performing the operation.
let result = 5 + "7"; // Output: "57"
In conclusion, understanding data types in JavaScript is fundamental to being able to write effective code. Each data type has its own set of behaviors and capabilities, and knowing these can help you choose the right data type for the task at hand.