Table of Contents
Access nested properties
What is the difference between midpoint notation and square bracket notation in JavaScript object syntax?
How to add properties to existing JavaScript objects?
How to delete attributes from JavaScript objects?
What are the methods in JavaScript objects?
How to iterate over properties of JavaScript objects?
What is the "this" keyword in a JavaScript object?
What is the constructor in JavaScript?
What is the object prototype in JavaScript?
How to check if there are properties in JavaScript objects?
What is object destruction in JavaScript?
Home Web Front-end JS Tutorial Object Syntax in JavaScript

Object Syntax in JavaScript

Feb 24, 2025 am 09:52 AM

Object Syntax in JavaScript

Key Points

  • Understanding JavaScript objects are essential for successful development in the language, as many built-in data types are represented as objects. An object is a composite data type built from primitives and other objects, and its properties describe aspects of an object.
  • Objects can be created and accessed in JavaScript in a variety of ways. Object literal notation (in braces) allows for quick creation of objects with key/value pairs. Object properties can be accessed through dot notation or square bracket notation, which provides greater flexibility for variable attribute names or attribute names containing special characters.
  • Functions used as objects' properties are called methods and can be called using point notation and square bracket notation. Attributes and methods can be added to an existing object through assignment statements, and properties of nested objects can be accessed by linking dots and/or bracket references together.

JavaScript objects are the cornerstone of the language. Many built-in data types (such as errors, regular expressions, and functions) are represented as objects in JavaScript. To be a successful JavaScript developer, you must have a firm grasp of how objects work. This article will teach you the basics of JavaScript object creation and manipulation. Objects are composite data types, built from primitives and other objects. An object's building block is often referred to as its field or attribute . Attributes are used to describe certain aspects of an object. For example, attributes can describe the length of the list, the color of the dog, or the date of birth of a person.

Create an object

Creating objects in JavaScript is easy. The language provides a syntax called object literal notation for quickly creating objects. The object text is represented in braces. The following example creates an empty object without attributes.

1

var object = {};

Copy after login
Copy after login
Copy after login

In braces, the attribute and its values ​​are specified as a list of key/value pairs. The key can be a string or an identifier, while the value can be any valid expression. The list of key/value pairs is separated by commas, and each key and value is separated by a colon. The following example uses literal notation to create an object with three attributes. The first attribute foo stores the number 1. The second attribute bar is specified using a string and also stores the string value. The third property baz stores an empty object.

1

2

3

4

5

6

var object = {

  foo: 1,

  "bar": "some string",

  baz: {

  }

};

Copy after login
Copy after login
Copy after login

Please pay attention to the use of spaces in the previous example. Each attribute is written on a separate line and indented. The entire object can be written on a single line, but the code written in this format is easier to read. This is especially true for objects with many properties or nested objects.

Access attributes

JavaScript provides two notations of accessing object properties. The first and most common one is called point notation. In dot notation, the property is accessed by giving the name of the host object, followed by a period (or dot), and then the property name. The following example shows how to read and write properties using point notation. If the initial stored value of object.foo is 1, its value will become 2 after executing this statement. Note that if object.foo does not have a value yet, it will be undefined.

1

var object = {};

Copy after login
Copy after login
Copy after login

Another syntax for accessing object properties is called square bracket notation . In square bracket notation, the object name is followed by a set of square brackets. In square brackets, the property name is specified as a string. The example of the previous point notation has been rewritten below to use square bracket notation. While the code may look different, it is functionally equivalent to the previous example.

1

2

3

4

5

6

var object = {

  foo: 1,

  "bar": "some string",

  baz: {

  }

};

Copy after login
Copy after login
Copy after login

Square bracket notation is more expressive than dot notation because it allows variables to specify all or part of the attribute name. This is possible because the JavaScript interpreter automatically converts expressions in square brackets into strings and then retrieves the corresponding properties. The following example shows how to dynamically create attribute names using square bracket notation. In this example, the attribute name foo is created by concatenating the contents of the variable f with the string "oo".

1

object.foo = object.foo + 1;

Copy after login

Square bracket notation also allows attribute names to contain prohibited characters in dot notation. For example, the following statement is completely legal in square bracket notation. However, if you try to create the same property name in the dot notation, you will encounter a syntax error.

1

object["foo"] = object["foo"] + 1;

Copy after login

Access nested properties

The properties of nested objects can be accessed by linking dots and/or square bracket references together. For example, the following object contains a nested object named baz, which contains another object named foo, which has a property named bar that stores the value 5.

1

2

3

var f = "f";

 

object[f + "oo"] = "bar";

Copy after login

The following expression accesses nested property bar. The first expression uses dot notation, while the second expression uses square bracket notation. The third expression combines two notations to achieve the same result.

1

object["!@#$%^&*()."] = true;

Copy after login

Expressions like those shown in the previous examples may cause performance degradation if used incorrectly. It takes time to evaluate each point or square bracket expression. If you use the same property multiple times, it is best to access the property only once and then store the value in a local variable for use in all future purposes. The following example uses bar multiple times in a loop. However, instead of wasting time calculating the same value over and over, store bar in a local variable.

1

2

3

4

5

6

7

var object = {

  baz: {

    foo: {

      bar: 5

    }

  }

};

Copy after login

Function as method

When a function is used as an object property, it is called the method. Like properties, methods can also be specified in object literal notation. The following example shows how to achieve this.

1

2

3

object.baz.foo.bar;

object["baz"]["foo"]["bar"];

object["baz"].foo["bar"];

Copy after login

Methods can also be called using dot notation and square bracket notation. The following example uses these two notations to call the sum() method in the previous example.

1

var object = {};

Copy after login
Copy after login
Copy after login

Add attributes and methods

Object literal notation is useful for creating new objects, but it cannot add properties or methods to existing objects. Fortunately, adding new data to an object is as simple as creating an assignment statement. The following example creates an empty object. Then use the assignment statement to add two attributes foo and bar and a method baz. Note that this example uses dot notation, but square bracket notation is equally effective.

1

2

3

4

5

6

var object = {

  foo: 1,

  "bar": "some string",

  baz: {

  }

};

Copy after login
Copy after login
Copy after login

Conclusion

This article introduces the basic knowledge of JavaScript object syntax. It is crucial to master these contents because it forms the basis for the rest of the language. They say you have to learn to walk before you can run. Then, in the world of JavaScript, you must first understand objects to understand object-oriented programming.

Frequently Asked Questions about JavaScript Object Syntax (FAQ)

What is the difference between midpoint notation and square bracket notation in JavaScript object syntax?

In JavaScript, objects are collections of key-value pairs. You can access these values ​​using dot notation or square bracket notation. The dot representation is more direct and easier to read. Use it when you know the property name. For example, if you have an object named "person" that has a property named "name", you can access it like this: person.name.

On the other hand, square brackets are more flexible. It allows you to access properties using variables or attribute names that may not be valid identifiers. For example, if the property name contains spaces or special characters, or it is a number, you can access it like this: person['property name'].

How to add properties to existing JavaScript objects?

You can add properties to an existing JavaScript object using dot notation or square bracket notation. For point notation you just need to use the syntax object.property = value. For square bracket notation, the syntax is object['property'] = value. In both cases, if the property does not exist in the object, it is added.

How to delete attributes from JavaScript objects?

You can use the "delete" operator to delete properties from JavaScript objects. The syntax of the “delete” operator is delete object.property for point notation and delete object['property'] for square bracket notation. This will remove the attribute and its value from the object.

What are the methods in JavaScript objects?

The

method is a function stored as an object property. They are used to perform operations that utilize object data. You can define methods in an object using function syntax as follows: object.methodName = function() { / code / }.

How to iterate over properties of JavaScript objects?

You can use the "for...in" loop to iterate over properties of JavaScript objects. This loop will iterate over the object's so enumerable properties, including properties inherited from the prototype chain. The syntax is as follows: for (var property in object) { / code / }.

What is the "this" keyword in a JavaScript object?

The "this" keyword in a JavaScript object refers to the object to which it belongs. Inside the method, "this" refers to the owner object. In the constructor, "this" refers to the newly created object.

What is the constructor in JavaScript?

Constructors in JavaScript are special functions used to create objects of the same type. They are named in capital letters to distinguish them from ordinary functions. The "new" keyword is used to call the constructor and create a new object.

What is the object prototype in JavaScript?

Each JavaScript object has a prototype. A prototype is also an object, and all objects inherit properties and methods from its prototype. This is a powerful feature of JavaScript because it allows you to add new properties or methods to instances of object types.

How to check if there are properties in JavaScript objects?

You can use the "in" operator or the "hasOwnProperty" method to check whether properties exist in a JavaScript object. The "in" operator returns true if the property exists in an object or its prototype chain. The "hasOwnProperty" method returns true only if the property exists in the object itself.

What is object destruction in JavaScript?

Object destruction in JavaScript is a function that allows you to extract properties from objects and bind them to variables. This can make your code more concise and easy to read. The syntax is as follows: var { property1, property2 } = object.

The above is the detailed content of Object Syntax in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1660
14
PHP Tutorial
1260
29
C# Tutorial
1233
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles