Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I throw an error when accessing an object key that doesn't exist? [duplicate]

This one's a long shot...

In Javascript, I was accessing an object attribute that I was certain existed, but I had a typo was in the name of the key, so was returning undefined and creating a bug.

How can I write code equivalent to the following, but that throws an error because the key does not exist?

var obj = {'myKey': 'myVal'},
    val = obj.myKye;

I'm trying to find a solution that doesn't require me writing a wrapper function that I use every time I want to access a member of an object. Is it possible? Is there another, 'stricter' technique in Javascript for accessing object attributes?

like image 833
Trindaz Avatar asked Jun 21 '13 05:06

Trindaz


People also ask

Can object have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

How do you define an object in JavaScript?

In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc.


2 Answers

You can't...

If you want to be very careful hasOwnProperty will let you check if property is defined.

function GetSafe(obj, propertyName)
{
   if (obj.hasOwnProperty(propertyName)) return obj[propertyName];
   return "Unknown property:"+ propertyName; // throw or some other error reporting.
}
var obj = {'myKey': 'myVal'};
alert(GetSafe(obj, "myKey"));
alert(GetSafe(obj, "myKye"));
like image 69
Alexei Levenkov Avatar answered Nov 03 '22 00:11

Alexei Levenkov


Try this:

function invalidKeyException(message) {
   this.message = message;
   this.name = "invalidKeyException";
}

var obj = {'myKey': 'myVal'},
val = obj.myKye;
if (val == undefined)
    throw new invalidKeyException("Key does not exist.");

JSFiddle: http://jsfiddle.net/r2MM4/

(Look at the console)

like image 27
Hanlet Escaño Avatar answered Nov 02 '22 23:11

Hanlet Escaño