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.






Sunday, March 4, 2018

Difference between let const and var

There are three types of variable declaration is possible in ES6. Each have some different scope so developer should use that correct situation.


1. Variable by using var

Before Es6 came , var was used at all time. But after ES6 , developer have choose let. However, still developers are using both let and var.

Simple example, var name="test";

Remember, let and var have huge difference there.

See the below example,

(function (){
  for(var i = 0; i<10; i++) {
    console.log(i)
  }
})(); // Print 0 to 9

console.log(i); // Print 10

From the above code loop running and printing value 0, 1, 2... 9. But after that it will print 10 also. Because still variable i have scope. But if you use let here instead of var, it will error.


2. Variable by using let

Use let keyword to create variable. Its a block level scope.

Example:

let message;                 // Just declaration using let
message = 'Hello!';
let name = 'John', age = 19; //multiple variables
alert(message); // alert show message value


let- block level scope
Example below,


(function (){
  for(let i = 0; i<10; i++) {
    console.log(i)
  }
})(); // Print 0 to 9

console.log(i); // i is not defined

Hope now you have understand var and let difference.

3. Variable by using const

If you want any variable should be constant, go for this. Once assigned, we can not reassign.

Example :


const FixedValue =10;
  console.log(FixedValue);  //Print 10
  FixedValue =20;           //throws Error
  console.log(FixedValue); 

Above code, FixedValue assigned already and trying to reassign throwing an error.



Conclusion:

So based on your situation scope level choose the right one. Better one is let than var and const will be choose for constant.









Saturday, March 3, 2018

Data types in javascript

These are the following data base in java script.

    1. Number          -  Integer and floating point can mentioned here.
    2. String             -  For String, may have one or more characters.
    3. Boolean          - True or false value can be mentioned here.
    4. Null                -  For unknown values null.
    5. Undefined      -  For unassigned value
    6. Object            -  For making data structure
    7. Symbol          -  For unique identifiers.

Example:

Below example explain all data types with the help of  typeof operator, 

typeof undefined // undefined

typeof 0 // number

typeof true // boolean

typeof "foo" // string

typeof Symbol("id") // symbol

typeof null // object

typeof alert // function

Note: typeof operator will tell you what it is, whether it is function, object or string etc.,