Table of Contents
Example (accessing object properties)
Accessing the object properties in JavaScript
Using the "in" operator raises an error when accessing object properties
grammar
Example
Using the in operator to throw an error while accessing the object properties in JavaScript
An error is thrown when accessing object properties using defineProperty() method
parameter
Using the defineProperty() method to throw an error while accessing the object properties in JavaScript
Using the Proxy() constructor to access object properties raises an error
Home Web Front-end JS Tutorial How to throw an error when using an object's properties?

How to throw an error when using an object's properties?

Aug 26, 2023 am 08:13 AM

How to throw an error when using an objects properties?

In JavaScript, objects contain properties in key-value format. We can access any property of an object using the property name by taking the object as a reference.

Sometimes, we try to access object properties that do not exist in the object. In this case we get undefined value. Let us understand it through the following example.

Example (accessing object properties)

In the example below, we create the object and add some properties. Additionally, we've added some nested properties. After that, we try to access the "prop5" property, which is a nested property of "prop4". The user can observe its value in the output.

Additionally, we try to access the "prop6" property, but the object returns undefined because it does not exist in the object.

<html>
<body>
   <h2 id="Accessing-the-object-properties-in-JavaScript">Accessing the object properties in JavaScript</h2>
   <div id="content"> </div>
   <script>
      let content = document.getElementById('content');
      let object = {
         name: 'Shubham',
         prop1: 'Hello',
         prop2: 'World',
         prop3: '!',
         prop4: {
            prop5: 'This is a nested object.'
         }
      }
      content.innerHTML = "The value of prop5 is : " + object.prop4.prop5;
      content.innerHTML += "<br> The value of prop3 is : " + object.prop3;
      content.innerHTML += "<br> The value of prop6 is : " + object.prop6;
   </script>
</body>
</html>
Copy after login

So, whenever a property does not exist in the object, we can throw an error stating that the property does not exist in the object.

Here we will learn a different way of throwing errors when accessing object properties.

Using the "in" operator raises an error when accessing object properties

The "in" operator allows us to check if a property exists in an object. We can use a key as the left operand of the "in" operator and an object as the right operand.

We can check whether the attribute exists in the object. If not, we can throw an error.

grammar

Users can use the "in" operator according to the following syntax to throw errors when accessing object properties.

if(key in obj){
}else {
   // throw error
}
Copy after login

In the above syntax, key is a property that is used to check whether it exists in the object.

Example

In the example below, we create the table_obj object and add some key-value pairs. The function named get_property_value() checks whether the property exists in the object. If the property exists in the object, the property value is returned. Otherwise, it will throw an error.

In the try-catch block, we catch an error. In the output, the user can observe that the get_property_value() function throws an error for the "table_price1" property instead of returning an undefined value for the property.

<html>
<body>
   <h3 id="Using-the-i-in-i-operator-to-throw-an-error-while-accessing-the-object-properties-in-JavaScript">Using the <i> in </i> operator  to throw an error while accessing the object properties in JavaScript</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      // creating an object for table details
      let table_obj = {
         table_name: "table1",
         table_type: "table",
         table_size: "10x10",
         table_color: "black",
         table_price: 1000
      }
      function get_property_value(key) {
         if (key in table_obj) {
            return table_obj[key];
         } else {
            throw new Error(key + " is not a valid property name.");
         }
      }
      try {
         content.innerHTML += "table_name : - " + get_property_value("table_name");
         content.innerHTML += "<br>" + get_property_value("table_price1");
      } catch (e) {
         content.innerHTML += "<br>" + e.message;
      }
   </script>
</body>
</html>
Copy after login

An error is thrown when accessing object properties using defineProperty() method

Javascript’s defineProperty() method allows us to add properties to objects. We can add getters for property descriptors that throw errors.

grammar

Users can use the defineProperty() method according to the following syntax to throw an error when accessing object properties.

Object.defineProperty(obj_name, 'prop_name', {
   get: () => {
      // throw an error
   }
});
Copy after login

In the above syntax, we pass the descriptor as the third parameter of the defineProperty() method. We can throw errors from the descriptor function of a specific property of an object.

parameter

  • Obj_name - This is the object name to which the attribute is added to the object.

  • Prop_name - This is the name of the property to be added to the object.

  • { get: () => { } } - It is the getters function for object properties.

Example

In the example below, we create an empty_obj object with zero properties. We use the defineProperties() method to add properties. As a descriptor, we added the get() method, which throws an error and displays an error message.

In the output, the user can observe that when we try to access the "prop1" property it throws an error.

<html>
<body>
   <h3 id="Using-the-i-defineProperty-i-method-to-throw-an-error-while-accessing-the-object-properties-in-JavaScript">Using the <i> defineProperty() </i> method to throw an error while accessing the object properties in JavaScript </h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      let empty_obj = {};
      Object.defineProperty(empty_obj, 'prop1', {
         get: () => {
            throw new Error('You cannot access prop1 property');
         }
      });
      try {
         content.innerHTML = "The value of prop1 property in the empty object is " + empty_obj.prop1;
      }
      catch (err) {
         content.innerHTML = "The error is : - " + err;
      }
   </script>
</body>
</html>
Copy after login

Using the Proxy() constructor to access object properties raises an error

The Proxy() constructor allows us to create a proxy for an object and override all descriptors of the object, such as getters and setters. Here we can override getters() and write a new function that can throw errors.

grammar

Users can use the following syntax to use the Proxy() constructor to throw errors when accessing object properties.

let proxy_obj = new Proxy(target_Obj, {
   get: function (target, prop) {
      // throw error
   },
});
Copy after login

In the above syntax, target_obj is an object for which a proxy is created. We have passed the object containing the get() method as the second parameter. In the get() method we can validate the object properties and throw an error if the object properties are invalid.

Example

In the following example, we use the Proxy() constructor to create a proxy for the targetObj object. When creating the proxy we check if the user accessed the "prop5" property. If not, we will always throw an error. This means that the "prop5" property can only be accessed from the object. However, it will return an undefined value for the "prop5" property because we haven't defined it in the object yet.

<html>
<body>
   <h3 id="Using-the-i-defineProperty-i-method-to-throw-an-error-while-accessing-the-object-properties-in-JavaScript">Using the <i> defineProperty() </i> method to throw an error while accessing the object properties in JavaScript </h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      let targetObj = {
         prop1: 'Hello',
      }
      let proxy_obj = new Proxy(targetObj, {
         get: function (target, prop) {
            if (prop != 'prop5') {
               throw new Error('You are only allowed to access prop5');
            }
         },
      });
      try {
         content.innerHTML += "The value of prop1 is: " + proxy_obj.prop1 + "<br>";
      } catch (e) {
         content.innerHTML += "The error is - " + e + "<br>";
      }
   </script>
</body>
</html>
Copy after login

The above is the detailed content of How to throw an error when using an object's properties?. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON File Example Colors JSON File Mar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript? What is 'this' in JavaScript? Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source Viewer Improve Your jQuery Knowledge with the Source Viewer Mar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development 10 Mobile Cheat Sheets for Mobile Development Mar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles