Reliability Testing

I would like to know the difference (if any) between the following:

if( someDOMElement.someProperty )
{
...

if( someDOMElement.someProperty != null )
{
...

if( someDOMElement.someProperty != undefined )
{
...

Is it safer than others?

+3
source share
4 answers

Everyone will do the same, while others are not subject to errors than others. If you used !==, and not !=, then the second two would be true if the value were null(second) or undefined(third), since the operator !==does not force.

Javascript will support values ​​during comparisons to !=or ==, for example:

alert(false == 0);   // alerts "true"
alert(false === 0);  // alerts "false"

=== !== . , , ( ), " 0, "", null undefined?" if (thingy), . 0, "", null undefined "".

Sean Kinsey , , , DOM, . , , COM , if (comObject.property), true, if (comObject.property == null) true. ( COM, API- , , Javascript, .) , . Javascript ( ) DOM, .

+4

, someDOMElement, , "" , - (, ActiveXObjects, ).

,

// use this if you expect a callable property
function isHostMethod(object, property){
    var t = typeof object[property];
    return t == 'function' ||
    (!!(t == 'object' && object[property])) ||
    t == 'unknown';
}

// use this if you are only looking for a property
function isHostObject(object, property){
    return !!(typeof(object[property]) == 'object' && object[property]);
}

alert(isHostObject(someDOMElement, "someProperty")) 

http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting

+1

, .

if(someDOMElement && someDOMElement.someProperty !=undefined){
    the property exists and has been set to a value other than undefined or null-
    it may be 0, false, NaN or the empty string, as well as any truthy value
}
0

Source: https://habr.com/ru/post/1746850/


All Articles