Saturday, March 10, 2018

Cloning Object in javascript

Last post , we have seen How object reference is working.But in some cases(very rare) if you want to copy exact object, means cloning, what you should do? How do you do that.

Its really a dull or tedious process.

Let see by code example,

let user = {
  name: "Kamal",
  age: 30
};

let clone = {}; // Going to clone into this empty object

// copy all properties from original into target
for (let key in user) {
  clone[key] = user[key];
}

console.log(clone);

Explanation: 

user is our original object and you have created one empty object called clone. After that , we have used for loop to iterate all the property of user object and assign the same to clone object. This loop will execute for all the properties of user. 

Checking with console log, all were copied to clone(target) object. Now you can modify your cloned object and check console. It will not affect user object. Since now cloned object is independent.

However, we have another simple way for cloning. Let see that too,

Object.assign:

Above we have used loop to iterate all the properties. So its look like some wide process. But using Object.assign() will make the process simpler.

Syntax is
Object.assign(destination[, src1, src2, src3...])

destination - Targeted object for clone
src1, src2,src3 etc., - Source object where you have to copy.

let user = { name: "Surya" };

let business = { businessType: "Cinema" };
let type = { isActor: true };

// copies all properties from business and type into user
Object.assign(user, business, type); console.log(user);

Output:
{name: "Surya", businessType: "Cinema", isActor: true}

Now everything is copied into our targeted user object.







Thursday, March 8, 2018

Objects copying by Reference

Generally, copying the object means, its not copy the exact object. Just Its copying the object reference. So exact object is different and reference is different.

We can discuss clone in next post.

Example:


let person = { name: 'Kannan', age: 21 };

let employee = person; // applied employee reference

employee.name = 'Rajni';

console.log(person.name); // Rajni

Initially person.name is Kannan but after modification by reference like employee= person, its reference will be considered and changes will reflected. please check the console log.

How do you compare ?

Once you have reference you would get a chance to check object reference. We can do it by == and === operator. However , I always use ===.



let a = {};
let b = a; // applied copy reference

alert( a == b ); // true, pointing same reference of object
alert( a === b ); // true, this also true






Wednesday, March 7, 2018

Objects with Square Brackets

Consider the below object,

let test = {
  name: "Raj",
  age: 19,
}

Here , you are going to add another one property like state and district property. If you try directly based on the last post, it will throw an error. So what the error, check below.

// syntax error will occur
test.state district = TamilNadu Chennai


To solve that, you should use square brackets.

// setting value
test["state District"] = "TamilNadu Chennai";

// getting value
console.log(test["state District"]); // 

// deleting value
delete test["state District"];

From the above, We have not used dot operator and used [] .


Another important, here you can use any reserved words like "for", "switch", "let" etc., See the below to confirm how its working.

let obj = {
  for: 3,
  switch: 2,
  return: 5
}

console.log(obj.for + obj.switch + obj.return );  // Output 10






Javascript Objects Tutorial

Objects

In Javascript object is the main topic to involve and writing more efficient code. So it should be understand clearly before moving into other chapters. Let start....

A object should be created with { .........} with some list of optional properties. Means, Its based Key value pair concepts. A key should be a string and a value can be anything.

Empty Objects :

We can create an empty object by two ways. 

1. By Constructor

2. By empty literal { } (Empty braces).


let user = new Object();
let user = {};  

A simple Object Example:

let test = {     // test is object here
  name: "Raj",  // Key Value pair concept
  age: 19        
};

Here, test is your object which have name and age properties. Raj and 19 is its values.

Add, Read and Remove operation

Adding, Reading and Removing operation is possible at anywhere. So let see one by one.

1. Add Operation

Consider our test object and I need to add one property like "qulaification:Bsc". So the following way we can add,

Syntax:

ObjectName.yourNew Propery = Value;

Example:
test.qulaification="Bsc";

Now just print like console.log(test); It will show below output.

let test = {    
  name: "Raj",  
  age: 19,
  qualification:"Bsc" //newly added value updated here     
};

2. Read Operation

By accessing the property of object with dot operator do the read operation.

Syntax:

ObjectName.propertyName;

Example:

let test = {    
  name: "Raj",  
  age: 19,
  qualification:"Bsc" //newly added value updated here     
};

alert(test.age); // print 19

3. Remove Operation

By using delete operator we can achieve this. It return true after delete get successful.  Let see the below example.

Syntax:

delete(keyword) objectName.propertyName;

Example:

let test = {    
  name: "Raj",  
  age: 19,
  qualification:"Bsc"
};

delete test.age; // Remove age property completely and return true


In next part of this chapter, we are going to see in some cases DOT operator wont work. So how do we achieve that in that scenario. Let see in next post.





Tuesday, March 6, 2018

Java script function tutorial

Function without parameter :

Below is the simple example for function without any parameter.


function welcomeMessage() {
  alert( 'Hello World!' );
}

welcomeMessage();

1. function is the keyword here

2. welcomeMessage is the function name.

3. welcomeMessage() is just calling the function.


So when you call control executes welcomeMessage() , it will call welcomeMessage function and executes the alert function inside that.

The below is little different because of variable declaration. See below,

let userName = 'Welcome';

function welcomeMessage() {
  let userName = "World"; // local variable

  let message = 'Hello, ' + userName;
  alert(message);
}

welcomeMessage();
alert( userName );

First It will show alert message like Hello World! Then after It will show Welcome. Because of variable declaration places and due to let keyword its happening.

Function with parameters :

We can also pass parameters to the function. See below example,


function welcomeMessage(msg1,msg2) {
  alert(msg1);
alert(msg2);
}

welcomeMessage("sample","Test");

Above we are passing two parameters and both were executed inside the function.

Function with returning a value :

The below we can see a function which is returning a value. Example below.


function sum(a, b) {
  return a + b;
}

let result = sum(1, 2);
alert( result ); // Output: 3

Here let result = sum(1,2) is the calling place and after executing the function , its returning value to result.

Conclusion :

These are the simple examples about function. Here the post we have used everywhere let keyword. We already saw let is a block level scope. 







Alert Prompt and Confirm dialog boxes

Alert :

Its a simple pop up dialog box, which will just show the information to developer. The below is the simple example for alert box.

alert("Test");


If you run the above code, you can expect below output,

alert
Alert Example

Prompt :

It will show a pop up window with Ok and Cancel.  The user can enter input here. Below is the syntax.

prompt(title[, default]);

let test = prompt('Which city yopu were born?', Mumbai);

If you run the above code, you can see below image.

prompt-Image
Prompt Example


Confirm :

It shows a pop up window with two buttons Ok and Cancel. Syntax is below,

confirm("Your question here ");

Generally all will use this for asking questions to the user with Ok and Cancel option.

Ok will return True value and Cancel will return False value. See the below example,


let isQulaified = confirm("Are you qualified?");

The above code return the below output.


So pressing Ok return True and Cancel return a false value.









Monday, March 5, 2018

Increment and Decrement Operator

Increment ( ++ ) and Decrement (--) operators could play a important role in our coding life especially when you would do code re fragment.

Most of the interview rounds the interviewer will ask this question and most probably targeting a freshers. Her the post I will explain what these two operators are these, and we can see some coding example.

Let start....

Increment ++ operator:

It will increase a variable by 1 always. However some logic is there when you put ++ as prefix and as post fix to the variable.

1. Post fix ++  

let counter = 2;
counter++;      //Nothing but counter = counter + 1
console.log(counter); // Output : 3

So adding a post fix , increment the variable by 1 and assign to the variable. In this case ,
counter = counter + 1.


2. ++ Prefix operator:

This is totally different from the above example even I am using the ++. See the below code and remember the applied logic. 

let b = 1;
console.log(b++);    // 1
console.log(b);      // 2

Things To Remember:

1. console.log(b++), from this line before increment b value will be printed.
2. console.log(b); from this line after increment b value taken.  Because b=b+1 was taken now.
Same concept is applicable to -- operator.

Decrement -- operator:

1. Post Fix -- operator

let c = 1;
console.log(c--);    // 1
console.log(c);  // 0

2. -- Pre Fix operator

let d = 1;
console.log(--d);    // 0
console.log(d);      // 0



The below example is little tricky and you can get now more satisfaction of understanding pre and post operators.

let count = 1;
console.log( 2 * ++count ); // 4 , because of Prefix value increment here itself


let test = 1;
console.log( 2 * test++ ); // 2, because of post fix the old value only be used here

I hope you are satisfied with the the above example.