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
Yup, {} is an empty object and [] is an empty array.
It's declaring an empty object literal.
It is shorthand for empty array. Same as new Array(). Also {} is an empty object. Objects are like hashtables in Js so you can use it as a dictionary. Copy link CC BY-SA 2.5.
JavaScript objects are written with curly braces {} . Object properties are written as name:value pairs, separated by commas.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With