I am working on javascript and I run into this:
if i do
let object = {};
object.length
It will complain that object.length is undefined But
let object = [];
object.length
works
Any know why?
Thanks
In JavaScript, virtually everything is an object (there are exceptions however, most notably null
and undefined
) which means that nearly all values have properties and methods.
var str = 'Some String';
str.length // 11
{}
is shorthand for creating an empty object. You can consider this as the base for other object types. Object
provides the last link in the prototype chain that can be used by all other objects, such as an Array
.
[]
is shorthand for creating an empty array. While also a data structure similar to an object (in fact Object
as mentioned previously is in its prototype chain), it is a special form of an object that stores sequences of values.
typeof [] // "object"
When an array is created it automatically has a special property added to it that will reflect the number of elements stored: length
. This value is automatically updated by certain methods while also used by others.
var arr = [];
arr.hasOwnProperty('length'); // true
arr.length; // 0
In fact there is nothing special about properties on arrays (although there are few if any good reasons to use them) aside from the engine using them for those methods.
var arr = [];
arr.foo = 'hello';
arr // []
arr.foo // "hello"
arr.length // 0
This is not true of an Object
though. It does not have a length
property added to it as it does not expect a sequence of values. This is why when you try to access length
the value returned is undefined
which is the same for any unknown property.
var obj = {};
obj.hasOwnProperty('length'); // false
obj.length; // undefined
obj.foo; // undefined
So, basically an array is a special data structure that expects a sequence of data. Because of this a property is added automatically that represents the length of the data structure.
BONUS: You can use length
to trim an array:
var a = [1,2,3,4,5];
a.length; // 5
a.length = 2;
a; // [1, 2]
a.length; // 2
This is because []
is an array object and the length is 0 because there are no elements. {}
is an object and there is no property length
. The array object does have a property called length
, thats why you see the number of elements when you call [].length
Object.keys()
[]
signifies an array in javascript, so it has length. {}
is just declaring an object.
They're different things. One is an object, another is an array.
{}
is an object, which has keys and values.
You can't necessarily determine the length of an object since its key-value pairs may not necessarily be numbers or indexed in any way.
[]
is an array, which has numbered indices. It's pretty straightforward it has a length.
length
is a property that arrays have innately. An object has no concept of a length as it's not a container, and has no length
property, so, no.
Object.keys(object).length