Unlock Objects In JavaScript

aryan sharmaaryan sharma
7 min read

You might have seen such key-value pairs in code or somewhere,

let user = {               // an object
  name: "Aryan",            // by key "name" store value "Aryan"
  age: "18"        // by key "age" store value 18
};

But what are these lines of code inside curly scriptures { } Let's get to know more about Objects and learn the best out of it.💫

Welcome everyone, this is Aryan Sharma and this is another blog of the Javascript blog series.

Letsss goooo....🚀

The concept of objects in a programming language like JavaScript maps nicely to its real-world equivalents. In the real world, you are literally surrounded by objects. Your computer is an object. A book on a shelf is an object. A potato is (arguably) an object. Your alarm clock is an object. The autographed Cee Lo Green poster you got on Ebay is also an object! I could go on forever, but (for everyone's sake :P) I'm going to stop here.
Now learn objects according to technical language,

Objects

There are 8 types of datatypes, out of which 7 are primitive, which means their values contain only a single thing whether be a string, integer or whatever.

In contrast, objects are used to store keyed collections of various data and more complex entities.

In JavaScript, objects penetrate almost every aspect of the language. So we must understand them first before going in-depth anywhere else.

Figure braces {…} can be used to build an object with an optional list of properties. A "key: value" combination, where the key is a string and the value can be any string, represents a property.

Okay, I am gonna talk about a different thing now, but by moving further in the blog, you will get it.

At technical conferences, usually we get Pizza,
Okay if you have forgotten your lovely food, then let me remind you.

Here we have pizza showing several Ingredients,

Just like the cheese, sauce, pepperoni, mushrooms, and bacon in our version of a pizza, the basic types in JavaScript are string, number, boolean, bigint, Symbol, null, undefined, and Object.

An empty object (“empty pizza”) can be created using one of two syntaxes:

let pizza = new Object(); // "object constructor" syntax
let pizza = {};  // "object literal" syntax

The figure brackets {...} are typically utilized. An object literal is that declaration.

Literals and properties

A property has a key (also known as “name” or “identifier”) before the colon ":" and a value to the right of it.

In the user object, there are two properties:

  1. The first property has the name "name" and the value "Aryan".

  2. The second one has the name "age" and the value 18.

     let user = {     // an object
       name: "Aryan",  // by key "name" store value "Aryan"
       age: 18        // by key "age" store value 18
     };
    

    A property has a key (also known as “name” or “identifier”) before the colon ":" and a value to the right of it.

    In the user object, there are two properties:

    1. The first property has the name "name" and the value "Aryan".

    2. The second one has the name "age" and the value 18.

The resulting user object can be imagined as a cabinet with two signed files labeled “name” and “age”.

We can add, remove and read files from it at any time.

Property values are accessible using the dot notation:

    // get property values of the object:
    alert( user.name ); // Aryan
    alert( user.age ); // 18

To remove a property, we can use the delete operator:

delete user.age;

Multiword property names can be added bi\ut must be quoted:

let user = {
  name: "Aryan",
  age: 18,
  "active": true 
};

The last property in the list may end with a comma:

let user = {
  name: "Aryan",
  age: 18,
}

That comma is referred to as "trailing" or "hanging." simplifies the addition, removal, and rearranging of properties by making all lines similar.

Square brackets

For accessing multiword variables in your code, . dot notation doesn't work.

user.name.age
// this will give a syntax error

Javascript understand only user.name and give error moving ahead.

There’s an alternative [] "square bracket notation” that works with any string:

let user = {};

// set
user[age] = 18;

// get
alert(user["age"]); // 18

// delete
delete user["age"];

Square brackets also provide a way to obtain the property name as the result of any expression – as opposed to a literal string – like from a variable as follows:

let key = "likes birds";

// same as user["likes birds"] = true;
user[key] = true;

Here, the variable key may be calculated at run-time or depend on the user input. And then we use it to access the property. That gives us a great deal of flexibility.

For instance:

let user = {
  name: "Aryan",
  age: 18
};

let key = prompt("What do you want to know about the user?", "name");

// access by variable
alert( user[key] ); // John (if enter "name")

The dot notation cannot be used in a similar way:

let user = {
  name: "Aryan",
  age: 18
};

let key = "name";
alert( user.key ) // undefined

Shorten the code

We are going to talk about writing less code!

Let's see how we can do it...

The Code :

function makeUser(name, age) {
  return {
    name: name,
    course: course
  };
}
let user = makeUser("Aryan", Btech);
alert(user.name);

Properties and variables have the same names in the example above.
Because creating a property from a variable is such a common use case, there is a unique property value shorthand for it.

We can simply write name in place of name:name, as in this example:

function makeUser(name, age) {
  return {
    name, 
    course
  };
}

These shorthands are allowed in JavaScript.

Property names rules

As we know, there ars some predefined keywords that we cannot use to give variable names in our code like "let", "for", "while", etc.

But there isn't a restriction of this kind for an object property:

let obj = {
  let: 1,
  for: 2,
  while: 3
};

alert( obj.let + obj.for + obj.while );  
// Output 6

There are no limitations on property names. They can be any strings or symbols.

Strings are automatically created from other types.

For example, when used as a property key, the number 0 becomes the string "0":

There’s a minor gotcha with a special property named __proto__. We can’t set it to a non-object value:

let obj = {};
obj.__proto__ = 7; 
alert(obj.__proto__); // [object Object] - the value is an object, didn't work as intended

As we see from the code, the assignment to a primitive 7 is ignored.

We’ll cover the special nature of __proto__ in subsequent chapters, and suggest the ways to fix such behavior.

in operator

There is something special about Objects in JavaScript.
Like it do not give error if failed to access any property or property doesn't exist.

It just returns undefined if property not exists.

let user = {
    "name": "Aryan Sharma",
    "age": 18
};

alert( user.address); // undefined as address property is not in user object
alert( user.address === undefined) //true

There we have a special operator "in" for that purpose.

Syntax :

"key" in object
let user = { name: "Aryan", age: 18 };

alert( "age" in user ); // true, user.age exists
alert( "address" in user ); // false, user.address doesn't exist

Property must be in "quotes"

Why does the in operator exist? Isn’t it enough to compare against undefined?

Well, Let's understand with the help of an example--

let obj = {
  check: undefined
};

alert( obj.check ); // it's undefined, but the prop exist na

alert( "check" in obj ); // true, the property does exist!

The property obj.check is technically present in the code above. Thus, the in operator functions properly.

for..in loop

To loop every key in an object, we use for..in loop. And it is not for(,,) that we have cstudied earlier in the course.

for (key in object) {
  // executes for each key
}

Let's output all the keys from info object

let info = {
  name: "Aryan",   // key-value pair
  age: 18,
  favColor: red
};

for (let key in user) {
  alert( key );  // name, age, favColor
}

Keep in mind that we can declare the looping variable inside the loop using any "for" construct, like let key in this case.

Also, we could use another variable name here instead of key. for (let prop in obj)

Here we are at end of this blog!
Hope you loved this💖

Don't forget to follow this blog & Connect with me

Twitter And LinkedIn

25
Subscribe to my newsletter

Read articles from aryan sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

aryan sharma
aryan sharma

Hey, Awesome ones! Aryan this side👋 Full-Stack Developer, Life-Long Learner, Optimistic Using this blog to help code newbies. Learn with me! :)