JavaScript Reference Type

 

JavaScript Reference Type

JavaScript reference type.

  1. Object
  2. Array
  3. Functions.

Object

So, what is an object?

An object in JavaScript or other programming language is an object in real life?

Think about person. A person has name, Age, address and so on, these are the properties of the person we are in the same concept on the JavaScript.

When we dealing with multiple related variables, we can put these variables inside of an object.


For example:

let name = ‘Emil’;

let age = 30;

Above two variables are highly related and representation of same person.

Instead of declaring two variables, we can declare a person as object.

Instead of referring these two variables, we can just reference person object.

It makes our code cleaner

so how to declared person’s object

let name = ‘Emil;

let age = 30;

Instead of above code we can declare as object {} curly brackets called object literal


let person = {



name: ‘Emil’,

age: 30;

};

Comma (,) to add another key value

Properties of the object

Two key values Name and Age

Now log person in console Console.log(person);

Answer =

{name: “Emil”, age.: 30}

age: 30

name: “Emil”

There are two ways to work with these properties.

Let’s say we want to change the name of this person.


1.First way .dot notation


Person.name =’John’;

Console.log (person)

We can also use dot notation to read the property

Console.log (person.name);

In console you get John.

Another way to access the property we can use [] Bracket notation



2.Second Way [] Bracket notation

person[‘name’] =’Mary’;

console.log (person.name);

Now save the change you can see Mary on the console.

Which approach is better? Dot notation or Bracket notation

Bracket notation have more features. Bracket notations have it’s one uses .

For example: sometimes you do not know the name or target property until the runtime.

In your user interface, the user might be selecting the name of the target property, in that case the term of writing code, we do not know what property we’re going to access. That is going to be selected at one point of time by user.

So, we might have another variable.

Somewhere else like selection.


Bracket notation []


let selection = ‘name’;



Person [‘selection’] = ’Mary’;

Console.log(person.name);

Determining the target property, the user is selecting.

We can access the property using the bracket notation in dynamic way.

So, we pass the selections here and we get the same result.

Post a Comment

Share your thoughts here

Previous Post Next Post