What's the difference in declarations with [] and {} in JavaScript?

10
var a=[]
var b={}

What's the difference in declarations with [] and {} in JavaScript? And in which context is it best to use each?

Question in English: SOen

    
asked by anonymous 20.11.2017 / 23:20

2 answers

8

The keys {} are basically used when declaring an object. I will give an example by creating an object with sub values or rather by defining values inside the object

var carro = {
marca: "Ford",
modelo: "Ka",
   getDetalhes: function () {
      return this.marca + ' - ' + this.modelo;
   }
} 

We can also wrap in keys objects created within a function

function Carro(){
   var Marca = "Sem marca";
   var Modelo = "Sem modelo";
}

Already using brackets [], you are creating / indicating an array. As I will show below

var a = [];
    a[0] = "Bob";
    a[1] = "Marley";
    a[2] = "Reggae";

That is, I indicated that the variable is an array, where the first value of this array is a string with Bob title, the second key of the array is a Marley title string and the third key of this array indicates the value with title Reggae

You can also specify an array in this way as I'll show below

var a =  ["Bob", "Marley", "Reggae"];

Remembering that you can also create an array in JavaScript with (), as I will indicate below

var a = new Array( "Bob", "Marley", "Reggae");

Or even this way it would be equivalent to the other two

var a = Array("Bob", "Marley", "Reggae");
    
20.11.2017 / 23:40
3

The difference is that {} can be used to create an object with sub-values and [] to create an array object.

Example object with {} :

var cliente = {
    usuario1: {
        nome: "João",
        idade: "23",
        estado: "SP"
    },
    usuario2: {
        nome: "Maria",
        idade: "30",
        estado: "RJ"
    }
}

Then you can access the information you want within the object by calling hierarchically the name of the variables inside it:

console.log(cliente.usuario1.nome); // retorna o "nome" do "usuario1", "João"

Now with [] , you will create a simple array, where each item has a value and an index, which begins with 0 :

var array = ['joao','maria'];
console.log(array[0]); // retorna o valor do índice 0, "joao"

But you can also merge the two. Below is an array with separate information in each index:

var array = [{nome:'joao', cidade: 'RJ'}, {nome:'maria', cidade: 'SP'}];
console.log(array[1].cidade); // retorna "SP"

The advantage of using one thing or another will depend a lot on your application. If you just want to store simple values, separated by indexes, use array [] . If you want to store values that contain sub-values in a specific object, use {} .

    
21.11.2017 / 01:05