JavaScript Data Types
JavaScript supports various data types, including primitive types (string, number, boolean, null, undefined, symbol, bigint) and objects (arrays, functions, and more). Understanding data types is crucial for writing reliable and bug-free code.
Key Topics
Primitive Data Types
Primitive data types include strings, numbers, booleans, null, undefined, symbols, and bigints. They represent simple values.
let str = "Hello"; // string
let num = 42; // number
let isTrue = true; // boolean
let notDefined; // undefined
let emptyVal = null; // null
console.log(typeof str);
console.log(typeof num);
console.log(typeof isTrue);
console.log(typeof notDefined);
console.log(typeof emptyVal);
Output
> string
> number
> boolean
> undefined
> object
Explanation: The typeof
operator returns the data type of a variable. Note that null
is considered an object due to a legacy bug in JavaScript.
Complex Data Types
Complex data types include objects, arrays, and functions. They can store multiple values or represent complex structures.
let arr = [1, 2, 3]; // array
let person = {name: "John", age: 30}; // object
let greet = function() { return "Hello"; }; // function
console.log(typeof arr);
console.log(typeof person);
console.log(typeof greet);
Output
> object
> object
> function
Explanation: Arrays and objects are considered objects in JavaScript, while functions have their own type. These complex types allow for storing and manipulating structured data.
Checking Data Types
The typeof
operator is commonly used to check data types. It's essential for debugging and ensuring that variables contain expected values.
let value = "Sample Text";
if (typeof value === "string") {
console.log("It's a string!");
}
Output
> It's a string!
Explanation: The typeof
check ensures that value
is a string before logging the message.
JavaScript Usage in DOM
This DOM-based example demonstrates using data types to display different types of values on a webpage dynamically.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Data Types in DOM</title>
</head>
<body>
<h1>Data Types Demo</h1>
<button onclick="showDataTypes()">Show Types</button>
<div id="output"></div>
<script>
function showDataTypes() {
let num = 100;
let txt = "JavaScript";
document.getElementById("output").textContent = "Number: " + num + ", String: " + txt;
}
</script>
</body>
</html>
Key Takeaways
- Primitive Types: Include string, number, boolean, null, undefined, symbol, and bigint.
- Complex Types: Objects, arrays, and functions store structured data.
- Type Checking: Use
typeof
to verify variable types. - DOM Integration: Dynamically display different data types in the browser.