What is the difference in the statements with [] and {} in Javascript?

Asked

Viewed 2,752 times

10

var a=[]
var b={}

What is the difference in statements with [] and {} in Javascript? And in what context is best used each?

Question in English: Soen

2 answers

10


Basically you use the {} keys when you want to declare an object. I will give an example creating an object with sub values or better saying, defining values within this 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 in the use of square brackets [], you will be 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 string with Marley title and the third key of this array indicates the value with Reggae title

You can also enter an array like this as I will show below

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

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

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

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

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

3

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

Example of 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 inside the object by calling hierarchically by the name of the variables inside it:

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

Already with the [], you will create a simple array, where each item has a value and an index, starting with 0:

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

But you can also merge the two things. Below 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 or the other 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 subvalues in a specific object, use {}.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.