DEV Community

Cristian Fernando
Cristian Fernando

Posted on

3 1

Paracetamol.js💊| #98: Explica este código JavaScript

Explica este código JavaScript

const nombre = Symbol("primer nombre");
const apellido = Symbol("apellido paterno");

const persona = {
  id: 1,
  [nombre]: "Cristian",
  [apellido]: "Villca",
  peso: 82,
  estatura: 180,
};

console.log(Object.keys(persona)); //?
Enter fullscreen mode Exit fullscreen mode

A. [ 'id', 'peso', 'estatura' ]
B. [ 'id', 'nombre', 'apellido', 'peso', 'estatura' ]
C. [ 'nombre', 'apellido' ]
D. Ninguno de los anteriores

Respuesta en el primer comentario.


Top comments (1)

Collapse
 
duxtech profile image
Cristian Fernando

Respuesta:
A. [ 'id', 'peso', 'estatura' ]

Las variables de tipo symbol son relativamente nuevas y tienen peculiaridades muy interesantes, una de ellas es la creación de propiedades ocultas o privadas dentro de los objetos.

Por este motivo las propiedades nombre y apellido no se muentran al ejecutar Object.keys(persona), esto puede ser de mucha útilidad para no contaminar nuestros objetos de manera arbitraria y poder tener un código mas profesional y limpio en nuestros desarrollos aprovechando las últimas caracteristicas del lenguaje.

Por si te lo preguntabas, ¿entonces como podemos acceder a las propiedades que son symbol dentro de los objetos? Podemos hacer esto:

console.log(Object.getOwnPropertySymbols(persona)); // [ Symbol(primer nombre), Symbol(apellido paterno) ]
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay