Part 2: Data Types in JavaScript
JavaScript has several built-in data types that are divided into primitive and non-primitive (reference) types. Let’s go over each of these:
--- Non-Primitive ---
Object: Objects are collections of key-value pairs. They are the most important data type in JavaScript, as nearly everything (arrays, functions, dates, etc.) is an object.
let person = {
?name: "John",
?age: 30,
?isEmployed: true
};
?Array: Arrays are a special type of object used to store ordered collections of values (elements). Arrays can hold any type of data, including other arrays and objects.
let fruits = ["Apple", "Banana", "Cherry"];
?Function: Functions are also objects in JavaScript. They can be stored in variables, passed as arguments to other functions, and returned from other functions.
function greet() {
?return "Hello!";
}
?--- Special Data Types ---
?NaN (Not-a-Number): NaN is a special value that results from operations that don’t produce a valid number, such as dividing zero by zero or parsing invalid strings into numbers.
?let result = 0 / 0; // NaN
let invalid = Number("abc"); // NaN
?
--- Infinity and -Infinity ---
These values represent positive and negative infinity, respectively. They result from dividing by zero or performing other operations that exceed the bounds of the Number type.
领英推荐
let infinity = 1 / 0; // Infinity
let negativeInfinity = -1 / 0; // -Infinity
?
---Type Checking---
You can check the type of a variable using the typeof operator.
console.log(typeof "Hello");?// string
console.log(typeof 42);??????// number
console.log(typeof true);????// boolean
console.log(typeof undefined); // undefined
console.log(typeof null);????// object (this is a known quirk in JavaScript)
console.log(typeof Symbol()); // symbol
console.log(typeof BigInt(12345)); // bigint
console.log(typeof {});??????// object
?
---Summary ---
Primitive Types: String, Number, Boolean, Undefined, Null, Symbol, BigInt.
Non-Primitive Types: Objects, Arrays, Functions.
Special values like NaN, Infinity, and -Infinity are part of the Number data type but represent specific states.
Each data type has unique properties and behavior, and understanding them is crucial for mastering JavaScript development.
Remember, every expert was once a beginner!