As a beginner in programming, one of the fundamental concepts you need to understand is data types. Data types are the building blocks of programming languages, and they define the type of data that can be stored in a variable.
Table of Contents
- What are Primitive Data Types?
The type of data that is stored in a variable is determined at runtime. This is different from statically typed languages like Java or C++ where you need to declare the data type of a variable before using it.
In this article, we will focus on primitive data types.
What are Primitive Data Types?
Let's take a closer look at each of these data types.
The number data type is used to represent numeric values. It includes integers, floating-point numbers, and exponential numbers. Here is an example:
let x = 5; let y = 3.14; let z = 123e5;
In this example, x is an integer, y is a floating-point number, and z is an exponential number.
You can perform mathematical operations on numbers using arithmetic operators such as +, -, *, and /.
The string data type is used to represent text. It is a sequence of characters enclosed in single or double quotes. Here is an example:
let greeting = "Hello, World!";
You can concatenate two or more strings using the + operator.
let firstName = "John"; let lastName = "Doe"; let fullName = firstName + " " + lastName; // "John Doe"
The boolean data type is used to represent true or false values. It is often used in conditional statements and loops. Here is an example:
let x = 5; let y = 10; let z = x > y; // false //or simply let isAdmin = true;
In this example, z is assigned the value false because x is not greater than y.
The undefined data type is used to represent a variable that has not been assigned a value. Here is an example:
let x; console.log(x); // undefined
In this example, x is declared but not initialized. When you try to access its value, it will be undefined.
The null data type is used to represent a variable that has been explicitly set to a null value. It is often used to indicate that a variable has no value. Here is an example:
let x = null;
In this example, x is assigned a null value.
The symbol data type represents a unique identifier. Symbols are often used as keys in objects to avoid naming collisions.
let id1 = Symbol("id"); let id2 = Symbol("id"); console.log(id1 === id2); // false