U r s u s
U r s u s

Reputation: 6968

Difference between Element.value === "" and Element.length === 0

I'm pretty sure this is obvious to most people, but I somehow got stuck thinking about this. Please be kind ;)

I realised that Element.value returns a String whereas Element.length returns an Int, but I'm still not sure whether the two methods return the same values (see example).

Toy example

I have the following input box

<input id="myInput" type="text" value="">

and two separate functions with the following methods

---method1---
var x = document.getElementById("myInput").length;

---method2---
var y = document.getElementById("myInput").value;

y value would be 0, but what would x value be? null or 0?

In other words do

Element.value === "" and Element.length === 0 express the same thing?

Upvotes: 2

Views: 2097

Answers (3)

AL-zami
AL-zami

Reputation: 9066

var x = document.getElementById("myInput").length;

This statement will give you undefined.Because length is a property of Array , String and nodeList objects.You can't implement length property on html objects .

y will be zero if you don't input any text to the text field.Otherwise it will give you the value you wave written in the text field.If you want the length of input string try x.value.length

Upvotes: 3

codeandcloud
codeandcloud

Reputation: 55200

Element.length will be undefined as its not a property. See here

var properties = [];
var myObject = document.getElementById("myInput");
for (var name in myObject) {
  if (myObject.hasOwnProperty(name)) {
    properties.push(name);
  }
}
alert(properties.filter(function(value) {
  return value && value.length > 0 && value[0] == "l";
}).join(" \n"));
<input id="myInput" type="text" value="">

Upvotes: 2

Mouser
Mouser

Reputation: 13304

Element.value returns a string on elements that allow user input. There this attribute is provided by the system. Element.length is not a property.

Various other objects in JavaScript do feature a property length. Arrays and all arrayish objects have a length property. They return the length of the array. An arrayish example is a node list. This is a list of elements. The function getElementsByTagName returns a node list for example. You can retrieve the length of this list by using length. The string object also has a length property (String.prototype.length). It returns the length of the string. (A string is also kind of an array). See this example:

 alert("test"[0]);

This will alert t. So you can loop through the string as if it where an array.

To conclude: Element.value === "" and Element.length === 0 is not the same since they don't relate to each other. Element.value === "" and Element.value.length === 0 almost do the same thing. The first checks if the returned string is empty, while the second checks the length of that string. In both cases the length of the string is 0.

Upvotes: 2

Related Questions