Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript difference between {} and []

Tags:

javascript

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

like image 543
Telenoobies Avatar asked Jul 08 '15 17:07

Telenoobies


People also ask

What is the difference between a {} and a []?

Yup, {} is an empty object and [] is an empty array.

What is the use of {} in JavaScript?

It's declaring an empty object literal.

What does [] mean in JavaScript?

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.

What type is {} in JS?

JavaScript objects are written with curly braces {} . Object properties are written as name:value pairs, separated by commas.


1 Answers

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
like image 177
Jason Cust Avatar answered Oct 01 '22 18:10

Jason Cust