JavaScript is a dynamically typed language, which means variables can hold different types of data. Understanding these data types is crucial for effective programming.
JavaScript has six primitive data types:
Numbers in JavaScript can be integers or floating-point values. There's no separate integer type.
let integerNumber = 42;
let floatingPointNumber = 3.14;
let scientificNotation = 1.23e5; // 123000
Strings are sequences of characters enclosed in single or double quotes.
let singleQuoted = 'Hello, World!';
let doubleQuoted = "JavaScript is awesome!";
let templateLiteral = `You can use ${singleQuoted} in template literals`;
Booleans represent true or false values, often used in conditional statements.
let isTrue = true;
let isFalse = false;
let comparison = 5 > 3; // true
These types represent the absence of a value, but in different ways:
let undefinedVariable;
console.log(undefinedVariable); // undefined
let nullValue = null;
console.log(nullValue); // null
Objects are collections of key-value pairs and can include functions (methods). Arrays and functions are also objects in JavaScript.
let person = {
name: "John",
age: 30,
isStudent: false
};
let colors = ["red", "green", "blue"];
function greet(name) {
return `Hello, ${name}!`;
}
You can use the typeof
operator to check the type of a value:
console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (this is a known quirk)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"
JavaScript performs automatic type conversion in certain situations. This can lead to unexpected results if not handled carefully.
console.log("5" + 3); // "53" (string concatenation)
console.log("5" - 3); // 2 (numeric subtraction)
console.log("5" == 5); // true (loose equality)
console.log("5" === 5); // false (strict equality)
===
) to avoid unexpected type coercion.Number()
, String()
, or Boolean()
.typeof
for type checking, but be aware of its limitations (e.g., with null
).Understanding JavaScript data types is fundamental to writing robust and error-free code. It's closely related to JavaScript variables and JavaScript operators, which you might want to explore next.