I have seen two ways of detecting whether a UA implements a specific JS property: if(object.property) and if('property' in object).
I would like to hear opinions on which is better, and most importantly, why. Is one unequivocally better than the other? Are there more than just these two ways to do object property detection? Please cover browser support, pitfalls, execution speed, and such like, rather than aesthetics.
Edit: Readers are encouraged to run the tests at jsperf.com/object-detection
if(object.property)
will fail in cases it is not set (which is what you want), and in cases it has been set to some falsey value, e.g. undefined, null, 0 etc (which is not what you want).
var object = {property: 0};
if(object.isNotSet) { ... } // will not run
if(object.property) { ... } // will not run
if('property' in object)
is slightly better, since it will actually return whether the object really has the property, not just by looking at its value.
var object = {property: 0};
if('property' in object) { ... } // will run
if('toString' in object) { ... } // will also run; from prototype
if(object.hasOwnProperty('property'))
is even better, since it will allow you to distinguish between instance properties and prototype properties.
var object = {property: 0};
if(object.hasOwnProperty('property')) { ... } // will run
if(object.hasOwnProperty('toString')) { ... } // will not run
I would say performance is not that big of an issue here, unless you're checking thousands of time a second but in that case you should consider another code structure. All of these functions/syntaxes are supported by recent browsers, hasOwnProperty has been around for a long time, too.
Edit: You can also make a general function to check for existence of a property by passing anything (even things that are not objects) as an object like this:
function has(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
Now this works:
has(window, 'setTimeout'); // true
even if window.hasOwnProperty === undefined (which is the case in IE version 8 or lower).
It really depends what you want to achieve. Are you talking about host objects (such as window and DOM nodes)? If so, the safest check is typeof, which works for all host objects I know of:
if (typeof object.property != "undefined") { ... }
Notes:
Avoid object.hasOwnProperty() for host objects, because host objects are not obliged to inherit from Object.prototype and therefore may not have a hasOwnProperty() method (and indeed in IE < 9, they generally do not).
A simple Boolean coercion (e.g. if (object.property) { ... }) is a poor test of the existence of a property, since it will give false negatives for falsy values. For example, for an empty textarea, if (textarea.selectionStart) { ... } will not execute the block even though the property exists. Also, some host object properties throw an error in older versions of IE when attempting to coerce to a Boolean (e.g. var xhr = new ActiveXObject("Microsoft.XMLHTTP"); if (xhr.responseXML) { ... }).
The in operator is a better test of the existence of a property, but there are once again no guarantees about support for it in host objects.
I recommend against considering performance for this kind of task. Choose the safest option for your project and only optimize later. There will almost certainly be much better candidates for optimization than property existence checks.
For more background on this, I recommend this excellent article by Peter Michaux.
Definitely if ('property' in object) is the right way to go. That actually tests if the property is in the object (or in its prototype chain, more on that below).
if (object.property) on the other hand, will coerce 'property' into a truth/flase value. If the property is unset, it will return "undefined", which will be coerced into false, and appear to work. But this will also fail for a number of other set values of properties. javascript is notoriously inconsistent in what it treats as truthy and falsy.
Finally, like I said above, 'property' in 'object' will return true if it's in anywhere in the prototype chain. If you want to test that's on the object itself, and not somewhere higher up in the chain, you use the hasOwnProperty method like so:
if (object.hasOwnProperty('property')) ...
The first one would fail if "property" is false of 0. To make sure that there actually exist a property you need to check that object.property !== undefined, or use the in-keyword.
[Edit]
There is also the hasOwnProperty-function, but I've never really used that one so I can't say much about it. Though I think it won't return true if the property is set in a prototype, which sometimes you want, other times you don't want.
This allows you to use window.hasOwnProperty as either referring to itself or something else, regardless of your scripting host.
// No enclosing functions here
if (!('hasOwnProperty' in this))
function hasOwnProperty(obj, prop) {
var method = Object.prototype.hasOwnProperty;
if (prop === undefined)
return method.call(this, obj);
return method.call(obj, prop);
}
//Example of use
var global = global || this; //environment-agnostic way to get the global object
var x = 'blah';
WScript.Echo(global.hasOwnProperty('x') ? 'true' : 'false'); //true
//Use as non-object method
var y = { z: false };
WScript.Echo(hasOwnProperty(y, 'z') ? 'true' : 'false'); //true
WScript.Echo(hasOwnProperty(y, 'w') ? 'true' : 'false'); //false
// true ಠ_ಠ
WScript.Echo(hasOwnProperty(global, 'hasOwnProperty') ? 'true' : 'false');
Related
I've heard similar questions, but not the answer that I wanted;
I do not count const because:
1).
it doesn't actually make it immutable, it only makes the reference immutable
2).
it messes with the scope, and I want it to work outside the block, too
3).
not all browsers support it yet
{
const hello = ["hello", "world"];
hello.push("!!!");
console.log(hello);//outputs "hello", "world", "!!!"
}
//and it doesn't, and shouldn't, work here
console.log(hello);
Just use Object.freeze
const immutableArray = Object.freeze([1,2,4])
You can use Object.freeze for this (obviously only on objects).
const hello = Object.freeze(["hello", "world"]);
// hello.push("!!!");
// will throw "TypeError: can't define array index property past the end of an array with non-writable length"
// hello.length = 0;
// will fail silently
// hello.reverse();
// will throw "TypeError: 0 is read-only"
// hello[0] = "peter";
// will fail silently
From MDN:
The Object.freeze() method freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. In addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in.
However, there is no keyword to define a completely immutable variable without using Object.freeze or Object.seal on the variable's value.
For a less restrictive approach Javascript also has Object.seal().
The way to do it without const is to use Object.defineProperty, and like I wanted, it behaves like var in terms of scope:
{
Object.defineProperty(typeof global === "object" ? global : window, "PI", {
value: Object.seal(3.141593),
enumerable: true,
writable: false,
configurable: false
});
}
console.log(PI); // 3.141593
The only problem is that it that it doesn't throw an error outside of strict mode.
I am utterly confused. I know this has been asked a million times. And I have looked at questions like:
Test if something is not undefined in JavaScript
Now the problem is when doing the check I have found multiple things you can do.
I need to check if an object is an array, to do that I check if the "length" property is there. Now what one would I use?
if (obj.length)
or
if (obj.length === undefined)
or
if (typeof obj.length === "undefined")
or
if (obj.length == null)
or something else?
I understand that === doesn't do any type conversion, and the if statement is just wanting a "truthy" or "falsey" value, meaning obj.length will return false if the length is 0, but that's not what we want. We want to now if it is defined. Which is why I go to type test. But which way is the best?
Here are some tests I did. 2, 3 and 4 work.
Sorry for the stuff in between. I was doing it in the console for this page.
Short answer:
if (obj instanceof Array) {
// obj is an array
}
Or, if you don't know whether obj is defined or not:
if ((typeof obj !== "undefined") && (obj instanceof Array)) {
// obj is an array
}
To discuss why yours aren't quite right:
obj.anyProperty will throw a ReferenceError if obj is undefined. This affects all four of the things you put.
if (obj.length) will evaluate to false for an empty array, which isn't what you want. Because the length is 0 (a falsy value), it will falsely be inaccurate. This could also have issues if another object has a length property.
if (obj.length === undefined) will usually work, but it's frowned upon because undefined can be redefined. Someone could break your code by writing undefined = obj.length. This can also create false negatives; obj could happen to have a property called "length" and it would falsely call it an array.
if (typeof obj.length === "undefined") works fine, but could detect the same false negatives as the above.
if (obj.length == null) will work okay, but has the same bugs as above. In a double-equals (==), it matches null and undefined.
I would do `
obj instanceof Array
to check if obj is an array
http://jsfiddle.net/Tcjk4/
For what it's worth, here's how jQuery checks whether something is an array:
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
This uses ES5's Array.isArray if available, or a custom check in older browsers. jQuery makes this function accessible as $.isArray.
jQuery.type is basically an enhanced typeof that works around some limitations of the JavaScript language and browser bugs. Whereas typeof returns 'object' for anything object-like ({}, [], even null), $.type returns the internal JavaScript [[Class]] property of the object.
In fact, this method of determining type is actually safer than instanceof:
Both instanceof and constructor look very innocent and seem like great
ways to check if an object is an array.
The problems arise when it comes to scripting in multi-frame DOM
environments. In a nutshell, Array objects created within one iframe
do not share [[Prototype]]s with arrays created within another
iframe. Their constructors are different objects and so both
instanceof and constructor checks fail:
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // [1,2,3]
// Boom!
arr instanceof Array; // false
// Boom!
arr.constructor === Array; // false
More comment than answer.
While a test like object instanceof Array will work in most cases (it may fail where frames or inter–window communication are involved), it's a good idea to consider what you really need to test for and design the test accordingly. Testing explicitly whether an object is an array or not is almost always unnecessary.
In this case, it seems that you just want to use the length property for iterating over the object's numeric properties.
If that's the case, all you need to do is read the value of the length property and use it. Whether the property is missing, or hasn't been assigned a value, or has a value of undefined or 0, you don't want to do the loop. Fortunately, you can do all of those tests in one go (and also skip processing if the value is Null or '', which seems sensible too):
if (obj.length) {
// iterate over numeric properties of obj
}
That will make the method generic, so it can be applied to any Object that has a suitable length property and some numeric properties (e.g. a jQuery object or an HTMLCollection object).
If you need some other feature of an array (say push or slice), you can also test for those.
If you are using the test as a logic fork (e.g. if it's an array do one thing, if it's a plain object do something else) then you should consider whether that's a sensible thing to do.
var sizeArrayOrObject = function(obj) {
var size = 0, key;
for (key in obj) {
if (typeof obj.key === 'undefined') size++;
}
return size;
};
sizeArrayOrObject([]); // 0
sizeArrayOrObject([5,6]); // 2
sizeArrayOrObject({}); // 0
sizeArrayOrObject({id:8}); // 1
to use underscore.js http://underscorejs.org/#isObject
_.isArray(object)
Returns true if object is an Array.
(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true
_.isObject(value)
Returns true if value is an Object. Note that JavaScript arrays and functions are objects, while (normal) strings and numbers are not.
_.isObject({});
=> true
_.isObject(1);
=> false
I want to add a method to every object.
When I just set Object.prototype.somefunction = ..., it will come up when somebody enumerates the object using the usual pattern:
for (i in o){
if (o.hasOwnProperty(i)){
// do something with object
}
}
I tried to set it higher up the prototype chain, but that is not possible (at least not possible in Chrome):
TypeError: Cannot set property 'blah' of undefined
Can I set some flag or something on the method so that it won't get enumerated, just like the native methods won't? (Or at least make hasOwnProperty() return false.)
Update: Sorry, I didn't look at it properly. I am using the ExtJS Framework and the object I was looking at had been processed by Ext.apply() which does the following:
for(var p in c){
o[p] = c[p];
}
That's where the "own property" flag gets lost.
So I guess I have no chance (in ECMAScript < 5) to inject a method into all objects that behaves like a native one?
I'm not sure I understand correctly. hasOwnProperty is needed exactly for this case, and enumerating an object via
for (i in o){
if (o.hasOwnProperty(i)){
// do something with object
}
}
should not include methods from Object.prototype. Can you please make a working example where you see this behaviour?
I also do not understand what you mean by
I tried to set it higher up the
prototype chain
as Object.prototype is the root of the chain, so you cannot get any higher.
In short, the solution is doing exactly what you claim you have done. If this does not work, probably you have made a mistake or found a bug.
I'm not sure what you mean. If a method/property is attached to the prototype, hasOwnProperty will return false. See this code:
function Con(){this.enumerableProp = true;};
Con.prototype.fun = function(){return 'that\'s funny'};
var fun = new Con;
alert(fun.hasOwnProperty('fun')); //=> false
alert(fun.hasOwnProperty('enumerableProp')); //=> true
So, what do you mean?
Make a base class and make all other classes extend it. Add the method to the base class.
ES5 has Object.getOwnPropertyNames() for this:
Object.prototype.lolwat = 42;
var obj = {
'foo': 1,
'bar': 2
};
Object.getOwnPropertyNames(obj); // ['bar', 'foo']
To see where it is supported: http://kangax.github.com/es5-compat-table/
However, for-in combined with a hasOwnProperty check should work too.
You get that error because there is nothing higher up the prototype chain.
Of note also is that adding to Object's prototype is not really recommended unless absolutely necessary for some reason
Edit: actually, my original answer was incorrect - as the others have pointed out, your object should not have that as own property if it's in Object's prototype.
In any case, if you want to create a prototype chain (or more importantly, avoid changing Object's prototype), you'll want to create your own class:
function MyBaseClass(){
}
MyBaseClass.prototype = new Object();
MyBaseClass.prototype.someMethod = function() { /* your method */ };
var o = new MyBaseClass();
o.hasOwnProperty('someMethod') //should be false
I'm working with XULRunner and came across the following pattern in a code sample:
var StrangeSample = {
backingStore : "",
get foo() { return this.backingStore + " "; },
set foo(val) { this.backingStore = val; },
func: function(someParam) { return this.foo + someParam; }
};
StrangeSample.foo = "rabbit";
alert(StrangeSample.func("bear"));
This results in "rabbit bear" being alerted.
I've never seen this get/set pattern used in Javascript before. It works, but I can't find any documentation/reference for it. Is this something peculiar to XUL, a recent language feature, or just something I missed? I'm puzzled because I was specifically looking for something like this a few months ago and couldn't find anything.
For reference, removing "get" or "set" results in a syntax error. Renaming them to anything else is a syntax error. They really do seem to be keywords.
Can anyone shed some light on this for me, or point me towards a reference?
As suggested by Martinho, here are some links explaining the getter/setters in JS 1.5:
http://ejohn.org/blog/javascript-getters-and-setters/
http://ajaxian.com/archives/getters-and-setters-in-javascript
Be aware though, they don't seem to be supported in IE, and some developers have (legitimate) concerns about the idea of variable assignment having side-effects.
get/set are not reserved keywords as Daniel points out. I had no problem creating a top-level functions called "get" and "set" and using the alongside the code-sample posted above. So I assume that the parser is smart enough to allow this. In fact, even the following seems to be legitimate (if confusing):
var Sample = {
bs : "",
get get() { return this.bs; },
set get(val) { this.bs = val; }
}
According to Mozilla, they are not in ECMAScript.
JavaScript Setters And Getters:
Usually the setter and getter methods follow the following syntax in JavaScript objects. An object is created with multiple properties. The setter method has one argument, while the getter method has no arguments. Both are functions.
For a given property that is already created within the object, the set method is typically an if/else statement that validates the input for any time that property is directly accessed and assigned later on via code, a.k.a. "set". This is often done by using an if (typeof [arg] === 'certain type of value, such as: number, string, or boolean') statement, then the code block usually assigns the this.(specific)property-name to the argument. (Occasionally with a message logging to the console.) But it doesn't need to return anything; it simply is setting the this.specific-property to evaluate to the argument. The else statement, however, almost always has a (error) message log to the console that prompts the user to enter a different value for the property's key-value that meets the if condition.
The getter method is the opposite, basically. It sets up a function, without any arguments, to "get", i.e. return a(nother) value/property when you call the specific-property that you just set. It "gets" you something different than what you would normally get in response to calling that object property.
The value of setters and getters can be easily seen for property key-values that you don't want to be able to be directly modified, unless certain conditions are met. For properties of this type, use the underscore to proceed the property name, and use a getter to allow you to be able to call the property without the underscore. Then use a setter to define the conditions by which the property's key-value can be accessed and assigned, a.k.a. "set". For example, I will include two basic setters and getters for this object's properties. Note: I use a constant variable because objects remain mutable (after creation).
const person = {
_name: 'Sean';
_age: 27;
set age(ageIn) {
if (typeof ageIn === 'number') {
this._age = ageIn;
}
else {
console.log(`${ageIn} is invalid for the age's key-value. Change ${ageIn} to/into a Number.`);
return 'Invalid Input.';
}
},
get age() {
return this._age;
},
set name(nameIn) {
if (typeof nameIn === 'string') {
this._name = nameIn;
} else {
console.log(`Change ${nameIn} to/into a(ny) String for the name's
key-value.`);
return 'Invalid Input.';
}
},
get name() {
return this._name;
}
};
Where it gets interesting is when you try to set/assign a new key-value for the _age property, because it has to meet the if conditional in order to be successfully assigned, meaning not all assignments are valid, etc.
person.age = 'twenty-eight'; /* output: twenty-eight is invalid for the
age's key-value. Change twenty-eight to/into a Number. */
console.log(person.age); // output: 27 (twenty-eight was never assigned)
person.age = 28; // output: none
console.log(person.age); // output: 28
Note how I was able to access the person._age property via the person.age property thanks to the getter method. Also, similar to how input for age was restricted to numbers, input for the name property is now restricted/set to strings only.
Hope this helps clear things up!
Additionally, some links for more:
https://johnresig.com/blog/javascript-getters-and-setters/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
https://www.infragistics.com/community/blogs/infragistics/archive/2017/09/19/easy-javascript-part-8-what-are-getters-and-setters.aspx
Let's say I've got a method that takes some arguments and stores them as instance variables. If one of them is null, some code later on is going to crash. Would you modify the method to throw an exception if null arguments are provided and add unit tests to check that or not? If I do, it's slightly more complicated since javascript has many bad values (null, undefined, NaN, etc.) and since it has dynamic typing, I can't even check if the right kind of object was passed in.
I think it really depends on what sort of API you're unit testing. If this is a component designed and built for internal use only, and you know usage will be under certain constraints, it can be overkill to unit test for bad parameters. On the other hand, if you're talking about something for distribution externally, or which is used in a wide variety of situations, some of which are hard to predict, yes, checking for bad parameters is appropriate. It all depends on usage.
I think you really have 2 different questions here.
The first is what is the best practice for parameter input validation and the second is should your unit test handle test for these situations.
I would recommend that you either throw an Argument Exception for the parameter that was not supplied correctly to your function or some other variable/message that informs the calling function/user of the situation. Normally, you do not want to throw exceptions and should try to prevent the functions from even being called when you know they will fail.
For your unit test, you should definitely include NULL value tests to make sure a graceful result occurs.
JavaScript has instanceof and typeof that can help you check what kind of objects are being passed to your functions:
'undefined' == typeof noVariable; // true
var noVariable = null;
'undefined' == typeof noVariable; // false
typeof noVariable; // 'object'
noVariable === null; // true
var myArray = [];
typeof myArray; // 'object'
myArray instanceof Object; // true
myArray instanceof Array; // true
var myObject = {};
typeof myObject; // 'object'
myObject instanceof Object; // true
myObject instanceof Array; // false
You can use these to set some default "bad" values for your instance variables:
function myFunction(foo,bar) {
foo = foo instanceof Array ? foo : []; // If 'foo' is not an array, make it an empty one
bar = bar instanceof Number ? bar : 0;
// This loop should always exit without error, although it may never do a single iteration
for (var i=0; i<foo.length; i++) {
console.log(foo[i]);
}
// Should never fail
bar++;
}
The or operator is also very useful:
function myFunction(blat) {
var blat = blat||null; // If 'blat' is 0, '', undefined, NaN, or null, force it to be null
// You can be sure that 'blat' will be at least *some* kind of object inside this block
if (null!==blat) {
}
}
Also, don't forget that with JavaScript you can pass in fewer than or more than the expected number of parameters. You can check that too, if you like.
For creating robust and secure code, checking the edge cases is definitely important task. Positive and negative testing is always good for the quality. The lack of negative tests might bite you in the long run.
So I'd say it is better play it safe - do both. It's a bit more work, but if you can afford the time, then it'll be worth it. Taking the developer hat off and putting on the cracker hat can be very interesting sometimes.