Inconsistant JavaScript Return Values - javascript

Why does getElementById() return null if the ID doesn't exist and getElementsByClassName() returns undefined if the class doesn't exist? This seems like an inconsistency in the JavaScript language since both are DOM methods. For example:
console.log( document.getElementById('bogusID') ); // null
console.log( document.getElementsByClassName('bogusClass')[0] ); // undefined
I recently had to find out the hard way, having my program crash since I wrongly assumed both methods would return "undefined" on a fail.
Is there actually a reason for the different return values?

document.getElementsByClassName('bogusClass') returns an empty array and you are trying to access the zeroth element, which doesn't exist, so you get undefined.
Javascript, unlike other programming language doesn't throw index out of range exception, because indexes are implemented as properties and accessing a property which doesn't exists returns undefined.
In terms of checking and handling for null and undefined, both are falsy value in javascript and hence your code should be the same for both cases.
if(condition){
// Both undefined and null would not pass the condition.
}

console.log( document.getElementById('bogusID') ); // null
Thats because there aren't bogusID items on your DOM so the return is null
console.log( document.getElementsByClassName('bogusClass')[0] ); // undefined
Thats because your getting the index 0 of an array that doesn't have an element at the 0 pointer. So the index 0 of the array isn't defined (undefined)

I don't know how the program is defined internally for getElementById() & getElementByClass but according to mozilla documentation getElementById() basically returns a reference(object) to the element.
ID
eg: element = document.getElementById()
Return Value
element -
is a reference to an Element object, or null if an element with the specified ID is not in the document. In dom there should be only 1 ID with a same name so there is no reuse in ID name.
Class
eg: var elements = element.getElementsByClassName(names);
getElementsByClassName() method returns a live HTMLCollection containing all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node.
In dom there should be only 1 ID with a same name so there is no reuse in ID name and also HTMLCollection uses array to collect all the elements that are refered using classname.
Undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value.
Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Related

Jquery isEmptyObject returns true even though it is not

This is the jquery code i am using
console.log(arrayPgggoData[taxonomy]);
console.log(jQuery.isEmptyObject(arrayPgggoData[taxonomy]));
And I don't know why it is returning true.
Also, what I am actually trying to see if the key inside is not an empty string.
The documentation clearly states:
The argument should always be a plain JavaScript Object as other types of object (DOM elements, primitive strings/numbers, host objects) may not give consistent results across browsers. To determine if an object is a plain JavaScript object, use $.isPlainObject()
But you are checking over an array.
To check if an array has no elements, you can simply rely on its .length property.
arrayPgggoData[taxonomy].length === 0
If you have some array values that you want to consider as "empty" values, then .filter method is your friend.
nonEmptyValues = arrayPgggoData[taxonomy].filter(function(el) { return el !== '' })
ES6 friendly syntax
const nonEmptyValues = arrayPgggoData[taxonomy].filter(el => el !== '')

Precaution needed while using variable.length in javascript for array and object?

I want to use javascript length property (variable.length) to find the length of an array or object.
Is there any special check required before using the length property for an array or object.
Different types of errors are found while using the length property in my previous experience. So I need to know the correct way to use the length property and possible errors while using length property.
You need check if the array is different to undefined or null, after that, you can get the length property. Also you can use Array.isArray() to check if is array the variable
isArray reference
You can access every property (also the "length") property on everything, except on null and undefined. In most cases .length is undefined then though.
The length attribute can be found in multiple data structures.
The length in String.prototype.length or in Array.length.
For any variable, you should check whether the variable itself exists first and then check the length if you know that it will have length attribute like for arrays.
// This will be applicable for data structures with length attribute
if (variable && variable.length) {}
// If you don't know the data structure
if (('length' in variable) && (variable.length >= some_num)) {}

Empty element and getElementsByClassName

I try to parse site and i have problem. When i parse table with empty element
type = elements[i].getElementsByClassName("listing-item__type");
I have this
VM56462:7 Uncaught TypeError: Cannot read property 'innerText' of undefined
at <anonymous>:7:25
How to fix it? Is it possible to check the element for empty?
Because getElementsByClassName return an array, you can not treat array as DOM element, you need get index and use
if (type[0] != undefined && type[0].innerText){
// add code here
}
Without seeing your HTML structure, you can check the presence of an element through:
if (type) {
// "type" is not undefined
}
Please note also that your "type" will return an array of elements (since you're using getElementsByClassName). Access the first one and check it is truthy before checking for the .innerText.

what does calling Object without using new do?

I've seen code that goes along the line of
Object( existingObject ).myMethod();
Is this different than calling existingObject.myMethod() directly? More generally, what does Object(x) do?
The Object constructor creates an object wrapper for the given value.
If the value is null or undefined, it will create and return an empty
object, otherwise, it will return an object of a type that corresponds
to the given value. If the value is an object already, it will return
the value.
In your case, since the value is an object already, it will just return the value existingObject. So, no, it is not really different from calling existingObject.myMethod directly.
Documentation

OOO javascript: object self reference returns undefined but console shows it exists

Okay, so I did search a bit before posting... no luck (or maybe I'm just stupid).
I have this array I call "myArray" and I push objects onto it to populate some variables:
myArray.push({
time : (y.moveTime - y.startTime),
pos : y.move,
last : myArray[y.recents.length-1].time
});
My issue is why does firebug complain about the "last" variable: "Uncaught TypeError: Cannot read property 'time' of undefined". If I do
last : myArray[y.recents.length-1]
everything is fine.
An observation I don't understand:
The array is empty when I have the ".time" reference, but if I remove it, the array is full.
What am I missing here? I don't get it :(
Thanks for any pointers.
The error means that the evaluated value of
myArray[y.recents.length-1]
is not an object that has a time property. This likely occurs when you perform the first push because the array does not yet have any elements.
If you want to hide the error and just assign the last property to undefined in this case, you can just add a fallback value:
last: (myArray[y.recents.length - 1] || {}).time
The value of myArray[y.recents.length-1] can be anything (some string, object, array, null etc.). you can set the value of last with it and will not make any error.
however, if you set a property to a non-object (like setting time), it will cause an error.

Categories