JavaScript has several built-in data types that are used to represent different kinds of values. Here are the main data types in JavaScript:
-
Primitive Data Types:
- Undefined: Represents an uninitialized variable or a function without a return value.
- Null: Represents the intentional absence of any object value.
-
Boolean:
Represents a logical entity and can have two values:
true or false
. - Number: Represents numeric values, including integers and floating-point numbers.
- String: Represents sequences of characters enclosed in single (' ') or double (" ") quotes.
-
Object Data Type:
-
Object:
Represents a collection of key-value pairs. Objects can be created using the
Object
constructor or object literal notation{}
.
-
Object:
Represents a collection of key-value pairs. Objects can be created using the
-
Composite Data Types:
- Array: Represents an ordered collection of values. Arrays can hold values of different data types.
-
Function:
Functions are a special type of object in JavaScript. They can be defined using the
function
keyword.
-
Special Data Types:
- Symbol: Introduced in ECMAScript 6 (ES6), symbols are unique and immutable primitive values, often used as keys for object properties.
JavaScript is a dynamically typed language, meaning you don't need to specify the data type of a variable explicitly; the interpreter determines the data type at runtime. Additionally, JavaScript is loosely typed, allowing for flexible type conversions.
Here's a simple example that demonstrates some of these data types:
let myUndefinedVar; // undefined
let myNullVar = null; // null
let myBooleanVar = true; // boolean
let myNumberVar = 42; // number
let myStringVar = "Hello, World!"; // string
let myObjectVar = { key: "value" }; // object
let myArrayVar = [1, 2, 3, "four", true]; // array
function myFunction() {
return "I am a function!";
}
In this example, variables are declared with different data types, including undefined, null, boolean, number, string, object, array, and function.