In JavaScript and TypeScript, variables can hold values of different data types. Understanding the different data types is important for writing clean and efficient code. This blog post will explain the different data types available in JavaScript and TypeScript and provide code examples to help you understand how they work.
Primitive Data Types
The most basic data types in JavaScript and TypeScript are called primitive data types. These include:
String: a sequence of characters represented in quotation marks, e.g.
"Hello World"
Number: a numeric value, e.g.
42
Boolean: a value that represents either
true
orfalse
Undefined: a value that represents the absence of a value
Null: a value that represents a deliberate non-value
Symbol (added in ECMAScript 6): A unique and immutable primitive value, used to represent a value that is hidden to other code.
Here is an example of declaring variables with the primitive data types in JavaScript:
let name = "Esther White"; // String
let age = 30; // Number
let isHappy = true; // Boolean
let notDefined = undefined; // Represents an undefined or non-existent value
let empty = null; // Represents a null or non-existent value
let id = Symbol("id");
TypeScript (which is a superset of JavaScript, so it includes all the data types in JavaScript as well as some additional ones):
Tuple: An array with a fixed number of elements, each of which may be of a different type.
Enum: A way to give more friendly names to sets of numeric values.
Any: A type that represents any value.
Void: A type that represents the absence of a value.
Never: A type that represents a value that never occurs.
And here is an example of declaring variables with the primitive data types in TypeScript:
let name: string = "Esther White"; // String
let age: number = 30; // Number
let isHappy: boolean = true; // Boolean
Symbol
const mySymbol = Symbol("mySymbol"); // Create a new symbol with an optional description
let obj = {
[mySymbol]: "Hello, world!" // Use the symbol as a property key
};
console.log(obj[mySymbol]); // This will output "Hello, world!"
Tuples (TypeScript only):
typescriptCopy codelet myTuple: [string, number] = ["Alice", 30]; // Tuple with two elements, the first one is a string and the second one is a number
Enums (TypeScript only):
typescriptCopy codeenum Color {
Red,
Green,
Blue
}
let myColor: Color = Color.Red;
Any (TypeScript only):
typescriptCopy codelet myVariable: any = "Hello"; // Can hold any type of value
myVariable = 42;
myVariable = true;
Void (TypeScript only):
typescriptCopy codefunction sayHello(): void {
console.log("Hello, world!");
}
Never (TypeScript only):
typescriptCopy codefunction throwError(message: string): never {
throw new Error(message);
}
Null and Undefined in TypeScript
In TypeScript, null
and undefined
are each a subtype of all other types, which means that you can assign null
or undefined
to any variable of any type. However, if you try to assign null
or undefined
to a variable that is not explicitly defined as allowing those values, TypeScript will raise an error.
By using a union type that includes null
or undefined
, you explicitly allow a variable to hold those values, in addition to any other type that the variable can hold. This is useful when you want to indicate that a variable may not always have a value, or when you want to distinguish between a value that is null
or undefined
and a value that is of a different type.
For example, consider the following function that takes a parameter of type string
:
typescriptCopy codefunction printMessage(message: string): void {
console.log(message);
}
If you call this function with a value of null
or undefined
, TypeScript will raise an error:
typescriptCopy codeprintMessage(null); // Error: Argument of type 'null' is
// not assignable to parameter of type 'string'.
printMessage(undefined); // Error: Argument of type 'undefined' is
// not assignable to parameter of type 'string'.
To allow the function to accept null
or undefined
as a valid input, you can define the parameter as a union type:
typescriptCopy codefunction printMessage(message: string | null | undefined): void {
if (message === null || message === undefined) {
console.log("Message is null or undefined.");
} else {
console.log(message);
}
}
Now, the function can accept a value of null
or undefined
as a valid input, and you can handle those cases separately from the case where the input is a string.
I hope this clarifies why union types are often used to allow variables to hold null
or undefined
values in TypeScript.
NaN
NaN
stands for "Not a Number" and is a value of the Number
data type in JavaScript and TypeScript. It is a special value that is produced when a mathematical operation or function fails to return a valid number.
For example, if you try to divide a number by zero, the result is NaN
. Similarly, if you try to perform a mathematical operation on a non-numeric value, such as a string or an object, the result is also NaN
.
In JavaScript and TypeScript, NaN
is considered to be a number value, but it is not equal to any other value, including itself. This means that you can use the isNaN()
function to check whether a value is NaN
.
Here's an example in JavaScript:
let x = 5 / 0; // This will return Infinity
let y = "Hello" / 5; // This will return NaN
console.log(isNaN(x)); // This will return false
console.log(isNaN(y)); // This will return true
Object Data Types
In addition to the primitive data types, JavaScript and TypeScript also support object data types. An object is a collection of properties and methods that are assigned to a single variable. Objects can be created using object literals or object constructors.
Here is an example of creating an object in JavaScript:
let person = {
firstName: "Esther",
lastName: "White",
age: 30,
isMarried: false,
job: "Developer"
};
And here is an example of creating an object in TypeScript:
let person: object = {
firstName: "Esther",
lastName: "White",
age: 30,
isMarried: false,
job: "Developer"
};
Array Data Types
Another type of object in JavaScript and TypeScript is an array. An array is an ordered collection of elements of any data type, including other arrays. Arrays can be created using array literals or the Array constructor.
Here is an example of creating an array in JavaScript:
let fruits = ["apple", "banana", "orange"];
And here is an example of creating an array in TypeScript:
let fruits: string[] = ["apple", "banana", "orange"];
Objects and Arrays with CONST
It's worth noting that object types and array types can also be declared using const
, which is used to declare variables that cannot be reassigned. This is useful when you want to ensure that the value of a variable remains unchanged throughout your code.
For example, when declaring an object or array using const
, you can still add or modify properties and elements within the object or array, but you cannot reassign the entire object or array to a new value.
Here is an example of declaring an object using const
in JavaScript:
const person = {
firstName: "Esther",
lastName: "White",
age: 30,
isMarried: false,
job: "Developer"
};
person.age = 31; // valid
person = {}; // invalid
And here is an example of declaring an array using const
in TypeScript:
const fruits: string[] = ["apple", "banana", "orange"];
fruits.push("peach"); // valid
fruits = ["grape"]; // invalid
Remember that you can use the type annotations in TypeScript to make your code even more robust and maintainable.
Understanding the different data types in JavaScript and TypeScript is an essential aspect of writing clean and efficient code. This blog post has covered the five primitive data types (string, number, boolean, undefined, and null), object data types, and array data types. Remember that you can use the type annotations in TypeScript to make your code even more robust and maintainable.