What does var = {} mean in javascript / jquery?

3

Sometimes I have seen variables that have two parentheses with nothing, that is to say this.

var obtener_teclas = {}

Especially in scripts to capture keystrokes, that is, keyboard events, does that variable mean that it will store some value? Also this is not a javascript object?

It's just that I tried to find info. but I do not know how to look for it.

P.D: And I've also seen variables without values, that is, this:

var x;
    
asked by cat_12 11.12.2018 в 10:16
source

2 answers

6

When you have something like nombreVariable = {} you are declaring that variable as an object in JavaScript.

If instead you do this: nombreVariable = [] are declaring an array.

As for your question of what var x means without any value, what you are declaring a variable simply, to which you can give value later, use in the loops for , while . .etc or use it as contador or sumatorio .

    
answered by 11.12.2018 / 10:42
source
5

With var obtener_teclas = {} you are simply defining the variable obtener_teclas as an empty object of zero length.

var obtener_teclas = {}
console.log(typeof(obtener_teclas));
console.log(obtener_teclas);
console.log(Object.keys(obtener_teclas).length);

//Otras formas de crear un objeto vacío
console.log("*****");

var obtener_teclas2 = Object.create(null);
console.log(typeof(obtener_teclas2));
console.log(obtener_teclas2);
console.log(Object.keys(obtener_teclas2).length);

console.log("*****");

var obtener_teclas3 = new Object();
console.log(typeof(obtener_teclas3));
console.log(obtener_teclas3);
console.log(Object.keys(obtener_teclas3).length);

You could initialize the object with values:

var obtener_teclas = {v: "Valor1", v2: "Valor2"};
    console.log(typeof(obtener_teclas));
    console.log(obtener_teclas);

You can also add values to the a posteriori object:

var obtener_teclas = {};
console.log(obtener_teclas);
obtener_teclas.v = "Valor1";
obtener_teclas.v2 = "Valor2";
obtener_teclas.v3 = "Valor3";
console.log(obtener_teclas);

Regarding var x; you are creating the variable x as undefined .

var x;
console.log(x);

If you want more info about declaration of variables in JS I recommend this question

And here more info on the creation of objects.

Also check out the use of "use strict" in the definition of variables

    
answered by 11.12.2018 в 10:45