Object Definitions
JavaScript Objects: The Core Concept
Section titled “JavaScript Objects: The Core Concept”Objects are fundamental to JavaScript. Understanding them is key to mastering the language.
| In JavaScript, objects are collections of key-value pairs. These pairs are often called properties. |
|---|
While JavaScript has primitive data types (like strings, numbers, booleans), almost everything else behaves like an object or can be treated as one temporarily via wrapper objects.
- Primitive values (string, number, boolean, null, undefined, symbol, bigint) are not objects themselves, but string, number, and boolean primitives have corresponding object wrappers (
String,Number,Boolean) that provide methods. - Dates are always objects (
Date). - Math is a built-in global object with static properties and methods (
Math). - Regular expressions are objects (
RegExp). - Arrays are a special type of object.
- Functions are first-class objects.
- And, of course, custom objects you create are objects.
JavaScript’s primitive values are immutable, while objects are mutable.
Objects: Variables Containing Keyed Collections
Section titled “Objects: Variables Containing Keyed Collections”A simple variable holds a single value:
let personName = "John Doe"; // A string primitiveObjects, however, can hold many values, organized by keys (names). These key-value pairs are called properties.
const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"};| A JavaScript object is a collection of properties, where each property has a name (key) and a value. |
|---|
Object Properties
Section titled “Object Properties”The named values in JavaScript objects are called properties. Keys are typically strings (or Symbols), and values can be any data type, including other objects or functions.
For the person object above:
| Property Key | Property Value |
|---|---|
| firstName | ”John” |
| lastName | ”Doe” |
| age | 50 |
| eyeColor | ”blue” |
This key-value structure is similar to:
- Dictionaries in Python
- Hash maps or Hash tables in Java and C#
- Associative arrays in PHP
- Hashes in Ruby and Perl
Object Methods
Section titled “Object Methods”Methods are functions stored as object properties. They define actions that can be performed on or by an object.
const personWithMethod = { firstName: "Jane", lastName: "Doe", age: 30, eyeColor: "green", fullName: function() { return this.firstName + " " + this.lastName; }, // ES6 shorthand method syntax greet() { console.log("Hello, my name is " + this.fullName()); }};
console.log(personWithMethod.fullName()); // Output: Jane DoepersonWithMethod.greet(); // Output: Hello, my name is Jane Doe| JavaScript objects are dynamic collections of properties, some of which can be methods (functions). |
|---|
You will learn more about functions and the this keyword in subsequent chapters.
Creating JavaScript Objects
Section titled “Creating JavaScript Objects”There are several ways to create objects in JavaScript:
- Object Literal: The simplest and most common way.
- Constructor Functions: A traditional way to create multiple objects of the same type.
- ES6 Classes: Modern syntax for creating objects and implementing inheritance (syntactic sugar over constructor functions and prototypes).
- Using
new Object(): Generally discouraged in favor of object literals. - Using
Object.create(): Creates a new object with a specified prototype object.
Using an Object Literal
Section titled “Using an Object Literal”This is the most straightforward method. You define and create an object in one statement.
const car = { make: "Toyota", model: "Camry", year: 2021, startEngine() { console.log("Engine started!"); }};Using Constructor Functions (Pre-ES6 style)
Section titled “Using Constructor Functions (Pre-ES6 style)”Constructor functions are used to create multiple objects with the same structure and behavior.
function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; this.describe = function() { return `${this.firstName} ${this.lastName}, ${this.age} years old.`; };}
const myFather = new Person("John", "Doe", 50, "blue");const myMother = new Person("Sally", "Rally", 48, "green");
console.log(myFather.describe()); // John Doe, 50 years old.Using ES6 Classes (Modern Approach)
Section titled “Using ES6 Classes (Modern Approach)”ES6 classes provide a cleaner syntax for creating objects and dealing with inheritance. They are syntactic sugar over JavaScript’s existing prototype-based inheritance.
class Vehicle { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; }
getInfo() { return `${this.year} ${this.make} ${this.model}`; }}
const myCar = new Vehicle("Honda", "Civic", 2022);console.log(myCar.getInfo()); // 2022 Honda Civic| For simple, one-off objects, object literals are preferred. For creating blueprints for multiple similar objects, ES6 classes are the modern standard, though understanding constructor functions is helpful for older codebases or deeper JavaScript concepts. |
|---|
The this Keyword
Section titled “The this Keyword”In JavaScript, this refers to the object that is currently executing the code. Its value depends on how a function is called (the call site).
- In a method,
thisrefers to the owner object. - In a regular function (not a method, not an arrow function),
thisrefers to the global object (window in browsers, global in Node.js) in non-strict mode, orundefinedin strict mode. - In a constructor function (called with
new),thisrefers to the newly created instance. - In an event handler,
thisoften refers to the element that received the event. - Arrow functions do not have their own
thisbinding. They inheritthisfrom their surrounding (lexical) scope.
Understanding this is crucial and can be tricky. Its behavior is a common source of confusion for beginners. Resources like MDN Web Docs provide detailed explanations.
this is a keyword, not a variable. Its value cannot be reassigned. |
|---|
Built-in JavaScript Constructors and Literals
Section titled “Built-in JavaScript Constructors and Literals”JavaScript has built-in constructors for native objects like Object, String, Number, Boolean, Array, RegExp, Function, Date.
However, for String, Number, Boolean, Array, Object, and RegExp, it’s almost always better to use their literal forms for performance and readability:
// Preferred Literal Forms:const obj = {}; // Instead of new Object()const str = "hello"; // Instead of new String("hello")const num = 123; // Instead of new Number(123)const bool = true; // Instead of new Boolean(true)const arr = []; // Instead of new Array()const regex = /pattern/g; // Instead of new RegExp("pattern", "g")
// Function expressions/declarations are preferred over new Function()const greet = function() { console.log("Hello!"); };
// Date is an exception; you must use the constructorconst today = new Date();The Math object is a global, static object; you don’t use new with it (e.g., Math.random()).
Using constructors like new String("text") creates an object wrapper, not a primitive string. This can lead to unexpected behavior in comparisons.
JavaScript Objects are Mutable
Section titled “JavaScript Objects are Mutable”Objects in JavaScript are reference types. This means when you assign an object to a variable or pass it to a function, you are working with a reference (or pointer) to that object in memory, not a copy of the object itself.
const originalPerson = { firstName: "John", lastName: "Doe", age: 50};
const anotherPersonRef = originalPerson; // Both variables point to the SAME object
anotherPersonRef.age = 55; // Modifying through one reference affects the original
console.log(originalPerson.age); // Output: 55 (changed!)console.log(anotherPersonRef.age); // Output: 55This is different from primitive types (strings, numbers, booleans), which are immutable and copied by value.
To create a true copy of an object (either shallow or deep), you need to use techniques like the spread syntax ({...obj} for shallow copy), Object.assign({}, obj) (shallow copy), or more complex methods/libraries for deep copies. This is an important concept when you want to modify an object without affecting the original.