Difference in Javascript between {} and []

I am working on javascript and I am running into this:

if i do

let object = {};
object.length

      

It will complain that object.length is undefined But

let object = [];
object.length 

      

work

Does anyone know why?

thank

+3


source to share


4 answers


In JavaScript, almost everything is an object (there are exceptions, but in particular null

and undefined

), which means that almost all of the values have properties and methods.

var str = 'Some String';
str.length // 11

      

{}

is shorthand for creating an empty object. You can think of this as the basis for other types of objects. Object

provides the last link in the prototype chain that can be used by all other objects like Array

.

[]

is shorthand for creating an empty array. Although a data structure similar to an object (in fact Object

, as mentioned earlier, it is in the prototype chain), it is a special form of an object that stores sequences of values.

typeof [] // "object"

      

When you create an array is automatically added to the special property that will reflect the number of stored items: length

. This value is automatically updated by certain methods and also used by others.

var arr = [];
arr.hasOwnProperty('length'); // true
arr.length; // 0

      



There is really nothing special about array properties (although there are several reasons why they can be used) other than using them for these methods.

var arr = [];
arr.foo = 'hello';
arr // []
arr.foo // "hello"
arr.length // 0

      

This does not apply to Object

. It has no property added length

because it does not expect a sequence of values. So when you try to access length

, the return value 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 automatically added that represents the length of the data structure.

BONUS: you can use length

to trim the array:

var a = [1,2,3,4,5];
a.length; // 5
a.length = 2;
a; // [1, 2]
a.length; // 2

      

+5


source


This is because it []

is an array object and the length is 0 because there are no elements. {}

is an object and there is length

no property . Array object has a property length

, so you see the number of elements when you call[].length



+2


source


[]

means array in javascript, so it has length. {}

just declares an object.

+2


source


These are two different things. One object, the other is an array.

{}

is an object that has keys and values.
You cannot determine the length of an object, as its key-value pairs may not have to be numbers or indexed in any way.

[]

- an array that has numbered indices. It's pretty simple, length is length.

+1


source







All Articles