Basics
JS Objects
JavaScript Object Basics
JavaScript objects store properties and methods, supporting class syntax.
What are JavaScript Objects?
In JavaScript, an object is a standalone entity, with properties and type. An object can be created with curly braces {}
, with an optional list of properties. A property is an association between a name (or key) and a value. The value of a property can be a function, which is then known as a method of the object.
Creating Objects: Object Literals
Object literals are the most common way to create objects in JavaScript. They are defined directly using curly braces. This is a simple and convenient way to create objects with properties and methods.
Accessing Object Properties
You can access the properties of an object in two ways: dot notation and bracket notation. Dot notation is the most common and readable method.
Here's how you can access properties:
Adding and Modifying Properties
JavaScript objects are mutable, meaning you can add, modify, or delete properties after the object is created. Here’s how you can do it:
Methods in Objects
A method is a function stored as a property of an object. Methods allow objects to perform actions. To define a method, you simply assign a function to a property.
Using 'this' Keyword
The this
keyword refers to the object it belongs to. It is used to access other properties of the object. In the context of an object method, this
refers to the object the method is called on.
Classes and Constructor Functions
JavaScript classes, introduced in ECMAScript 2015, provide a more structured syntax to create objects using constructor functions. Classes allow you to define object blueprints, with properties and methods.
Summary
JavaScript objects are a fundamental part of the language, used for storing data and functions. Understanding how to create and manipulate objects is crucial for effective JavaScript programming. With the introduction of classes, creating objects has become more structured and intuitive.
Basics
- Introduction
- Where To
- Output
- Syntax
- Comments
- Variables
- Scope
- Hoisting
- Errors
- Data Types
- Operators
- Ternary Operator
- Short-Circuit Evaluation
- If Else
- Switch
- Loops
- For...Of/For...In
- Functions
- this Keyword
- Objects
- Arrays
- Strings
- Template Literals
- Numbers
- Number Properties
- Dates
- Math
- Booleans
- Type Conversion
- Destructuring
- Spread/Rest
- RegExp
- Strict Mode
- Modules
- Security Basics
- Debugging
- Best Practices
- Mistakes
- Performance
- Reserved Words
- Sets
- Maps
- Bitwise
- Array Const
- Previous
- this Keyword
- Next
- Arrays