The 7 JavaScript Data Types with Examples
In this tutorial, we'll cover the seven JavaScript data types and how you can apply them in real-world scenarios with code examples.
The seven JavaScript data types are:
Number
- An integer or floating-point number.String
- A sequence of characters representing textual data.Boolean
- A logical value of either true or false.Object
- Collections of key-value pairs, where the keys are strings and values can be any data type, including other objects. Objects are reference types, meaning when you assign an object to a variable, you're assigning a reference to the object, not the object itself.Symbol
- A unique and immutable value you can use as the key of an object property.undefined
- A declared variable without an assigned value.null
- A special value representing the intentional absence of any value.
JavaScript is a dynamically typed language, which means you don't have to specify the data type of a variable when you declare it. The data type is automatically inferred based on the value assigned to each variable.
Let's get into each of the data types in detail.
Number
In JavaScript, the number
data type represents numerical values, including integers and floating-point numbers. JavaScript uses the IEEE 754 standard for representing and manipulating numbers, meaning it can represent small and large numbers, as well as fractions and decimals.
- Largest safe integer: The largest possible integer is represented by
Number.MAX_SAFE_INTEGER
, and is equal to 253 - 1, or9007199254740991
. Numbers are signed, soNumber.MIN_SAFE_INTEGER
gives the minimum safe integer, which is-1
times the maximum safe integer. - Largest value: The largest possible value is represented by
Number.MAX_VALUE
, and is equal to 21024 - 1. The minimum value is-1
times the maximum value. - Smallest value: The smallest value greater than
0
is represented byNumber.MIN_VALUE
, and is equal to 2-1024. - Epsilon: The difference between
1
and the least number greather than1
is represented byNumber.EPSILON
, and is equal to 2-52. - Infinity: If a number runs outside the above limit, it will either be
Infinity
or-Infinity
. You can check for this case using the built-inNumber.isFinite()
function. - NaN: Short for "Not a Number" is represented when attempting to convert an invalid non-number value into a number. You can check against this value using
Number.isNaN
.
Here are some examples of how to assign number
values:
let x = 42; // integer
let y = 3.14; // floating-point number
let z = 1.23e6; // scientific notation for 1,230,000
You can also perform arithmetic operations such as addition, subtraction, multiplication, and division:
let a = 5 + 2; // 7
let b = 10 - 3; // 7
let c = 4 * 2; // 8
let d = 12 / 3; // 4
String
A string
is a primitive data type representing a sequence of alphanumeric characters.
To create a string, you can enclose a sequence of characters in either single quotes '...'
or double quotes "..."
:
let myString = 'Hello There!';
let anotherString = 'Here is another string.";
You can also use backticks ``...``
to create temporal literals, which are a special type of string that allows for embedded expressions:
let name = 'Josh';
let greeting = `Hello, ` + name + `!`;
console.log(greeting);
// Hello, Josh!
JavaScript includes several methods for string manipulation, including slice()
, substring()
, and replace()
.
Boolean
A boolean
is a primitive data type that can have one of two values: true or false. Booleans represent logical values and are often used in conditional statements and loops to control program flow.
Boolean values can be assigned to variables or returned from functions:
var isAdmin = true;
var isLoggedIn = false;
function isUserAdmin() {
return isAdmin;
}
In this example, the boolean variable isAdmin
is set to true and returned as such in the isUserAdmin()
function.
Boolean values can also be obtained through comparison operators, such as ==
(equal to), !=
(not equal to), >
, <
, >=
, and <=
:
let x = 5;
let y = 10;
let isGreaterThan = y > x; // returns true
let isEqual = x == y; // returns false
Object
An object is a composite data type that can store multiple key-value pairs. Objects are used to represent more complex data structures, such as arrays, functions, and custom data types.
You can create objects using curly braces {
and }
and can have zero or more properties. Each property is a key-value pair, where the key is a string or symbol, and the value can be any valid data type, including other objects:
let person = {
name: "Josh",
age: 30,
address: {
street: "123 Main St.",
city: "My Town",
state: "CO",
zip: 12345
}
};
In the above example, person
is an object created with three properties: name
, age
, and address
. The address
property is an object with four additional number and string properties.
You can access these properties using the following dot and bracket notation syntax:
console.log(person.name);
console.log(person["age"]);
console.log(person.address.city);
In addition to creating objects using literal notation, you can also create them using constructor functions or classes. Constructor functions are used to create new objects with the same set of properties and methods. Classes provide a more structured way of creating objects with inheritance and encapsulation:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log("Hi! I'm " + this.name + " and I'm " + this.age + " years old.");
}
}
let me = new Person("Josh", 30);
me.greet();
// output: "Hi! I'm Josh and I'm 30 years old."
In the example above, the Person
class is used to create a custom data type with two properties: name
and age
. The greet()
method is defined inside the class body and is used to access the object's properties using the this
keyword. The new
keyword creates a new instance of the Person
object and passes values for the two properties.
Symbol
A symbol
is a primitive data type used to create unique values you can use as object property keys.
You can create a new symbol with the Symbol()
function:
let mySymbol = Symbol();
You can also provide a string as a description for the symbol for debugging purposes:
let mySymbol = Symbol("My description here");
In addition to creating symbols using the Symbol()
method, you can also create symbols that are shared across multiple instances of an object using the Symbol.for()
function. When you call Symbol.for()
with a string, it will either return an existing symbol with the same string or create a new one if it doesn't exist:
let mySymbol1 = Symbol.for("mySymbol");
let mySymbol2 = Symbol.for("mySymbol");
console.log(mySymbol1 == mySymbol2)
// true
Symbols can be used as object property keys, and because they're unique, they can be used to avoid naming conflicts with other properties. Here's an example of using a symbol as an object property key:
let mySymbol = Symbol("My description here");
let myObject = {};
myObject[mySymbol] = "My value here";
console.log(myObject[mySymbol]);
// My value here
In this example, a symbol is used as a property key for the myObject
object, with a value of "My value here". The value is accessed using bracket notation with the symbol as the key.
undefined
undefined
is another primitive data type representing a variable without an assigned value. For example:
let myVar;
console.log(myVar);
// undefined
You can also explicitly assign the value of undefined
to a variable for the same output:
let myVar = undefined;
console.log(myVar);
// undefined
null
null
is the final primitive data type in JavaScript, representing the intentional absence of a value. Here's an example:
let myVar = null;
console.log(myVar);
// null
Differences Between undefined
and null
It's important to note that null
is different from undefined
. undefined
represents a variable that has not been assigned a value, while null
represents the intentional absence of any value. If you declare a variable or a property of an object but don't assign a value to it, its value is undefined
. If you want to explicitly set a value to indicate the absence of any object value, you should use null
.
Conclusion
Here, we discussed the seven different JavaScript data types and how to apply them in real-world scenarios.
Created: February 17, 2023
Comments
There are no comments yet. Start the conversation!