0% completed
Objects are a fundamental part of JavaScript, allowing you to store collections of data and more complex entities. Unlike primitive data types that hold only a single value (such as strings or numbers), objects can store varied data types and represent real-world entities more effectively by grouping related data and functionality.
In JavaScript, an object is a standalone entity
, with properties and types. Think of it as a container for values in a key:value
pair format. These values can be properties and functions (methods when inside objects).
Real Life Objects, Properties, and Methods
Consider a real-world object: a car
.
A car has properties like color, brand, and model, and it can perform actions like driving and braking. These properties and actions collectively define what a car is and what it can do.
Creating Objects with Object Literals
The simplest way to create an object in JavaScript is using object literals:
- Object Literal: This is defined by using curly braces
{}
. - Properties:
color
,brand
, andmodel
are properties of the car object, each storing values describing the car. - Method:
drive
is a method, a function defined within an object, allowing the car object to perform actions.
Accessing Object Properties
In JavaScript, object properties can be accessed in two main ways:
- Using dot notation.
- Using bracket notation.
Each method has its use cases and benefits.
Dot Notation
Dot notation is straightforward and easy to read, making it the preferred way to access properties when you know the property name ahead of time.
Bracket Notation
Bracket notation is more versatile than dot notation, allowing access to properties using dynamic keys (e.g., stored in variables) or keys that might not be valid identifier names.
Dot vs. Bracket Notation
- Dot Notation: Offers cleaner syntax but requires the property name to be a valid JavaScript identifier and known at the time of coding.
- Bracket Notation: Provides flexibility to use variables for property names or property names that aren't valid identifiers (e.g., containing spaces or starting with numbers). It's slightly more verbose but indispensable in scenarios requiring dynamic property access.
Understanding when to use dot notation versus bracket notation allows you to access object properties effectively, adapting to different scenarios encountered in JavaScript programming.
Updating Object Properties
JavaScript allows you to update the properties of an object after it has been created. This can be done using both dot notation and bracket notation, offering flexibility depending on the scenario.
Example: Updating Properties
Let's consider an object representing a book:
In this example:
- Initial Object: A
book
object is created withtitle
,author
, andyear
properties. - Dot Notation Update: The
year
property of thebook
is updated to2021
using dot notation. Dot notation is straightforward and works well when you know the property name at the time of coding.book.year = 2021;
directly sets theyear
property to a new value.
- Bracket Notation Update: The
author
property is updated to "John Doe" using bracket notation. This method is useful for property names that are dynamic or not valid identifiers.book["author"] = "John Doe";
allows theauthor
property to be updated to a new value, demonstrating the flexibility of bracket notation for property names that might come from variables or need to be computed dynamically.
Methods in Object
Object methods are functions that belong to an object, allowing the object to perform actions or operations based on its properties. These methods are essential for encapsulating behavior within objects, making them more modular and self-contained.
Defining and Accessing Object Methods
To define a method, you simply create a function as a property of an object. You can then access and execute this method using either dot notation
or bracket notation
, followed by parentheses to invoke the function.
Consider an object representing a person that includes a method to greet:
In this example:
- Object with a Method: The
person
object has three properties:firstName
,lastName
, andgreet
. Thegreet
property is a method defined as a function. - The
this
Keyword: Inside thegreet
method,this
refers to theperson
object.this.firstName
andthis.lastName
access the object'sfirstName
andlastName
properties, respectively. - Executing the Method:
person.greet();
calls thegreet
method on theperson
object. This executes the function defined ingreet
, printing a greeting message to the console using the object's properties.
JavaScript Native Objects
JavaScript native objects, also known as built-in objects
, are fundamental objects provided by the JavaScript language itself. They are available for use in any JavaScript environment, serving as the building blocks for performing common tasks like mathematical operations, working with dates, or handling text. These objects offer a wide range of functionality out-of-the-box, from basic data manipulation to complex operations.
List of JavaScript Native Objects
Here are some of the key native objects in JavaScript:
-
String: Represents and manipulates a sequence of characters. Provides methods for searching, slicing, and manipulating text.
-
Number: Provides a wrapper for primitive numeric values. Offers constants and methods for working with numbers.
-
Boolean: Represents a logical entity with two values, true or false. Used in conditions and loops.
-
Array: Used to store multiple values in a single variable. Includes methods for adding, removing, and iterating over items.
-
Object: The base object for many JavaScript objects. Provides a structure for storing keyed collections and complex entities.
-
Function: Represents executable code and can be invoked. Functions in JavaScript are first-class objects.
-
Date: Provides methods for working with dates and times, allowing for the creation, manipulation, and formatting of date objects.
-
RegExp (Regular Expression): Used for matching text with patterns. Facilitates complex text searches and replacements.
-
Math: A collection of mathematical constants and functions. Helps perform mathematical tasks on numbers.
-
JSON (JavaScript Object Notation): Used for parsing and formatting JSON data, a common format for data exchange.
-
Promise: Represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
-
Symbol: Provides a way to create unique identifiers for object properties, ensuring they are unique and immutable.
These native objects form the foundation of JavaScript programming, enabling developers to perform essential tasks and implement complex features with ease. Understanding these objects and their methods is crucial for effective JavaScript development.
JavaScript Object Methods
Method Name | Description |
---|---|
Object.assign() | Copies the values of all enumerable own properties from one or more source objects to a target object. |
Object.create() | Creates a new object with the specified prototype object and properties. |
Object.defineProperty() | Adds a new property to an object, or modifies an existing property on an object, and returns the object. |
Object.defineProperties() | Adds or modifies multiple properties at once on an object, and returns the object. |
Object.entries() | Returns an array of a given object's own enumerable string-keyed property [key, value] pairs. |
Object.freeze() | Freezes an object. A frozen object can no longer be changed. |
Object.getOwnPropertyDescriptor() | Returns a property descriptor for a named property on an object. |
Object.getOwnPropertyDescriptors() | Returns an object containing all own property descriptors for an object. |
Object.getOwnPropertyNames() | Returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly upon a given object. |
Object.getOwnPropertySymbols() | Returns an array of all symbol properties found directly upon a given object. |
Object.getPrototypeOf() | Returns the prototype (i.e., the value of the internal [[Prototype]] property) of the specified object. |
Object.is() | Determines whether two values are the same value. |
Object.isExtensible() | Determines if extending of an object is allowed. |
Object.isFrozen() | Determines if an object was frozen. |
Object.isSealed() | Determines if an object is sealed. |
Object.keys() | Returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would. |
Object.preventExtensions() | Prevents new properties from ever being added to an object. |
Object.seal() | Prevents other code from deleting properties of an object. |
Object.setPrototypeOf() | Sets the prototype (i.e., the internal [[Prototype]] property) of a specified object to another object or null. |
Object.values() | Returns an array of a given object's own enumerable property values. |
Examples
Let's explore some of above methods with examples.
Object.create()
The Object.create()
method creates a new object, using an existing object as the prototype of the newly created object.
- A
personPrototype
object is defined with agreet
method. Object.create(personPrototype)
creates a newperson
object withpersonPrototype
as its prototype.person.name = 'Alice'
adds aname
property toperson
.- Calling
person.greet()
accesses thegreet
method from the prototype and outputs a greeting.
Object.entries()
Object.entries()
method returns an array of a given object's own enumerable string-keyed property [key, value]
pairs.
Object.entries(car)
converts thecar
object into an array of[key, value]
pairs, preserving the property structure in array format.
Object.keys()
The Object.keys()
method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
Object.keys(user)
retrieves an array ofuser
object's keys, allowing for easy iteration or inspection of the object's properties.
Object.values()
Object.values()
method returns an array of a given object's own enumerable property values.
Object.values(user)
extracts the values from theuser
object into an array, making it straightforward to work with just the values of an object.
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible