The Basic Data Types in JavaScript
JavaScript is a dynamically-typed language, which means that variables can hold values of different data types without the need for explicit declaration. JavaScript has several basic data types that form the foundation of the language. These data types are:
-
Primitive Data Types:
- Number: This data type represents both integers and floating-point numbers. It can also represent special numeric values like
Infinity
andNaN
(Not a Number). - String: This data type represents textual data. Strings can be enclosed in single quotes (
'
), double quotes ("
), or backticks (`
). - Boolean: This data type represents a logical value, either
true
orfalse
. - Undefined: This data type represents a variable that has been declared but not assigned a value, or an object property that does not exist.
- Null: This data type represents the intentional absence of any object value.
- Symbol: This data type represents a unique and immutable identifier. Symbols are primarily used as object property keys.
- Number: This data type represents both integers and floating-point numbers. It can also represent special numeric values like
-
Non-Primitive Data Types:
- Object: This data type is a collection of key-value pairs. Objects can be used to represent complex data structures, such as arrays, functions, and other objects.
Here are some examples of using these data types in JavaScript:
// Number
let age = 30;
let pi = 3.14;
let infinity = Infinity;
let notANumber = NaN;
// String
let name = "John Doe";
let message = 'Hello, world!';
let template = `The current age is ${age}`;
// Boolean
let isStudent = true;
let hasdiploma = false;
// Undefined
let myVariable;
console.log(myVariable); // Output: undefined
// Null
let person = null;
// Symbol
let id1 = Symbol('id');
let id2 = Symbol('id');
console.log(id1 === id2); // Output: false
// Object
let person = {
name: "John Doe",
age: 30,
isStudent: true
};
In this example, we demonstrate the usage of each of the basic data types in JavaScript. The primitive data types are straightforward, while the object data type allows for the creation of more complex data structures.
Understanding the basic data types in JavaScript is crucial for writing effective and efficient code. Knowing how to work with these data types, their properties, and their behaviors will help you navigate the JavaScript language with confidence.