Optional Parameter in JavaScript Function

Yes you heard it right, C# brought optional parameter in version 4.0 however it is part of JavaScript from beginning of the language design.

JavaScript function,

  1. Does not do any type checking on argument values
  2. Does not do any checking on number of arguments passed

There are three ways you can call a function in JavaScript

  1. With exact number of arguments
  2. With more number of arguments than specified
  3. With less number of arguments than specified

 

With less numbers of arguments

When you call a function with less numbers of arguments then left arguments are passed as undefined. To understand it more let us consider below example,

image

 

When creating function you may want to check for arguments which being not passed and assigned a default value. There are two ways you can assigned a default vale

  1. Using If statement
  2. Using || operator

Let us assume that you want to assign default value for optional parameter as 99. You can do that as following

image

 

Or better way to assign default value is using or operator. If first argument is falsy object in OR operator then it will always use second object. So when you don’t pass optional argument its values is undefined (falsy) and default value will get assigned.

image

 

Always remember to put optional arguments at end of argument list. You cannot make first argument as optional argument and pass second argument. If you want to do this then you will have to explicitly pass undefined as first parameter. So you can make first argument optional as below,

 

image

 

With more numbers of arguments

Other possibility is that you are calling a function with more number of arguments. So for example you are calling above function as following,

 

image

There is no direct way extra arguments can be read inside function. But there is a way using that extra arguments can be read. We can read extra arguments using arguments object. So you can read extra arguments as following

image

 

You can check exact number of arguments as following and throw exception

image

So this is all what I have in this blog to share with you on Optional arguments in JavaScript function. I hope you find this post useful. Thanks for reading.

Reflection in JavaScript

While working with JavaScript you may come across a scenario when you need to reflect type of a particular property. Let us say you have an object Student like following,

image

If you want to find type of students object property like name and marks you can get them as following,

image

Now go ahead and fetch type of calculateGrades.

image

You will get expected output as following,

image

If you slightly modify above code as below you will get undefined as output. We have put braces in finding type of function

image

image

While reflecting getting these two values as output may not be good idea

  1. Function
  2. Undefined

You may want to avoid these values in your code or can use other method hasOwnProperty . You can use this method to find that whether object contains that particular property or not. Following code will alert True since name is property of object Student.

image

Now let us go ahead and pass function name calculateGrades as value to hasOwnProperty. You will find true as output again.

image

Interestingly in above code you see that when we pass constructor as input output is false. Reason behind this is hasOwnProperty method does not look for the method in whole property chain. It will only look for the input parameter in current object. As clearly we see that Student object does not have constructor property of its own hence hasOwnProperty is giving false for this.

Better way of doing reflection in JavaScript could be as follows,

image

By using hasOwnProperty method and typeof operator you can work with reflection in JavaScript. I for your reference code discussed in this post is given below,


<script type="text/javascript" >
 function GetData() {

var Student = {
 name: "DJ",
 marks: 100,
 calculateGrades: function () {
 }
 };
 var typeofmarks = typeof (Student.marks);
 alert(typeofmarks);

alert(Student.hasOwnProperty('constructor'));
 alert(Student.hasOwnProperty('calculateGrades'));

if (Student.hasOwnProperty('name')) {
 var typeofname = typeof (Student.name);
 alert(typeofname);
 }

 }

</script>

I hope you find this post useful. Thanks for reading.

Learning Bootstrap Part 3: Working with Image and Icons

Read Part 1 here: Getting started with Bootstrap

Read Part 2 here: Working with Buttons

Working with images are very essential of web application development and Boot strap also realize this. If you want to create rounded image, circled images or Polaroid image then that is as easy as adding a class.

You can create a circled image as following

image

Circled images will look like following

image

You can create round corner images as following,

image

Rounded image will look like following

image

You can create Polaroid image as following,

image

Polaroid image will look like following ,

image

You can create different types of images as following


<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="Scripts/jquery-1.7.1.min.js"></script>
 <link href="Content/Site.css" rel="stylesheet" />
 <!-- Bootstrap references -->
 <script src="bootstrap/js/bootstrap.min.js"></script>
 <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
 <div class="container">

 <img src="Images/uk.jpg" class="img-polaroid"/>
 <img src="Images/indiaflag.jpg" class="img-circle"/>
 <img src="Images/deepika-paduk.jpg" class="img-polaroid" />

 </div>
</body>
</html>

It is very easy to work with Icons also in Bootstrap. Bootstrap supports free icons from http://glyphicons.com/ for developers. There are 140 icons avialble. You need to follow following steps to work with icons

  1. Create a <i> tag
  2. Set class of <i> tag with icon name. For erxample if you want to create calendar icon then that can be created as following

image

You can add icons to buttons as following . A Search button can be created as following . We are nesting <i> tag inside button taf to create a button with icons.

image

You can create different size of button with icons as following ,

image

Above buttons can be created as following


<div class="container">
 <a class="btn btn-large">
 <i class="icon-search"></i>Search
 </a>
 <br />
 <a class="btn btn-small">
 <i class="icon-search"></i>Search
 </a>
 <br />
 <a class="btn btn-mini">
 <i class="icon-search"></i>Search
 </a>
 </div>

You can create navigation lists with icons as following

<ul class="nav nav-list">
 <li class="active"><a href="#home"><i class="icon-home icon-white"></i>Home</a></li>
 <li><a href="#"><i class="icon-gift"></i>Gift</a></li>
 <li><a href="#"><i class="icon-picture"></i>Images</a></li>
 <li><a href="#"><i class="i"></i>Misc</a></li>
 </ul>

And you will find navigation bar created as following,

image

In this way you can add icons to any other elements. Bootstrap makes working with icons and images very easy. I hope you find this post useful. Thanks for reading.

Learning Bootstrap Part 2: Working with Buttons

Read Part 1 here: Getting started with Bootstrap

Buttons and anchor tags are very important controls. Bootstrap allows you to customize look of these two very elegantly.

Block level Button: if you want to create a button as the full width of parent container that can be easily created as following


<div class="container">
 <button class="btn btn-large btn-block" type="button">Login</button>
 <button class="btn btn-large btn-block" type="button">Register</button>
 <button class="btn btn-large btn-block" type="button">Twitter</button>
 <button class="btn btn-large btn-block" type="button">Facebook</button>
 </div>

In above we are putting buttons inside fixed container and you will see buttons would rendered as following. Buttons are taking width of parent div container.

clip_image002

There are different styles of buttons available. You can very easily create them. Let us say you want to create a Success Button. Success button can be created by setting class as btn-success

image

If you want to create Info button then that can be created setting button class as btn-info

clip_image001

Different kinds of buttons available in bootstrap is as following,

image

You can create above buttons as easily as given below


<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="Scripts/jquery-1.7.1.min.js"></script>
 <link href="Content/Site.css" rel="stylesheet" />
 <!-- Bootstrap references -->
 <script src="bootstrap/js/bootstrap.min.js"></script>
 <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
 <div class="container">

 <button class="btn btn-large btn-primary" type="button">Primary Button</button><br />
 <button class="btn btn-info"
 type="button">
 Info Button
 </button>

<br />

 <button class="btn btn-success"
 type="button">
 Success Button
 </button>

 <br />
 <button class="btn btn-large btn-warning" type="button">Warning Button</button> <br />
 <button class="btn btn-large btn-danger" type="button">Danger Button</button><br />
 <button class="btn btn-large btn-inverse" type="button">Inverse Button</button> <br />
 <button class="btn btn-large btn-link" type="button">Link</button> <br />
 </div>

</body>
</html>

Bootstrap also provides you different sizes of buttons. If you want to create a large button that can be created as following

clip_image001[6]

You can create a large success button as following

clip_image003

There are three buttons sizes available,

  1. Large button : btn-large
  2. Default button : btn
  3. Small button : btn-small
  4. Mini button : btn-mini

image

Above buttons can be crated with following mark-up


<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="Scripts/jquery-1.7.1.min.js"></script>
 <link href="Content/Site.css" rel="stylesheet" />
 <!-- Bootstrap references -->
 <script src="bootstrap/js/bootstrap.min.js"></script>
 <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
 <div class="container">
 <button class="btn btn-large ">
 Large Button
 </button> <br />
 <button class="btn">
 Default Button
 </button> <br />
 <button class="btn btn-small">
 Small Button
 </button> <br />
 <button class="btn btn-mini">
 Mini Button
 </button> <br />

 </div>

</body>
</html>

In this way you can work with buttons and make them immersive using twitter bootstrap. In further posts we will get into more deep into bootstrap. I hope you find this post useful. Thanks for reading.

Learning Bootstrap Part 1: Getting started with Bootstrap

What is Twitter Bootstrap ? Well, I will answer this question in further posts. In this post I am focusing on getting started with Bootstrap and I will show you how easy it could be to make your web applications more immersive using bootstrap.

Let us start with downloading and installing Bootstrap. You can download that from here

clip_image002

After downloading unzip the folder and you will find following subfolders inside that. Folders name are very much self-explanative. CSS files are in CSS folder and JS files are in JS folder.

image

Next you need to add bootstrap files in project structure. In Visual Studio folder structure should look like as following

image

Now a typical HTML file looks like following,


<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="Scripts/jquery-1.7.1.min.js"></script>
 <link href="Content/Site.css" rel="stylesheet" />
</head>
<body>

 <h1>Bootstarp Sample</h1>
 <div>I am here to decide about my Ideas ! Okay ?</div>

</body>
</html>

HTML will render without bootstrap as following,

image

You can add bootstrap CSS and JS references in the same way we add usual CSS and JS reference.

image

After adding references of bootstrap CSS and JS HTML should look like following.


<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="Scripts/jquery-1.7.1.min.js"></script>
 <link href="Content/Site.css" rel="stylesheet" />
 <!-- Bootstrap references -->
 <script src="bootstrap/js/bootstrap.min.js"></script>
 <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>

 <h1>Bootstarp Sample</h1>
 <div>I am here to decide about my Ideas ! Okay ?</div>

</body>
</html>

&nbsp;

Now we have added bootstrap CSS and HTML will render as following. You can notice the difference typography and the way H1 and DIV elements are rendering now.

image

Now let us see that how easy it is to differentiate different kind of message in bootstrap. For example if we want to show an error message that can be done by setting class of a paragraph.

image

In the same way an info message can be displayed as following,

image

We can show different kind of messages in application as easily as depicted in following HTML


<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="Scripts/jquery-1.7.1.min.js"></script>
 <link href="Content/Site.css" rel="stylesheet" />
 <!-- Bootstrap references -->
 <script src="bootstrap/js/bootstrap.min.js"></script>
 <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>

 <h1>Bootstarp Sample</h1>
 <p class="muted">This is muted text</p>
 <p class="text-warning">This is warning text</p>
 <p class="text-error">This is Error !</p>
 <p class="text-info">This is Info !</p>
 <p class="text-success">This is sucess message !</p>
</body>
</html>

And different kind of message will render as following,

image

Let us take another example of table. You can create a table a with some rows as following,

<table>
 <tr>
 <td>Dhananjay Kumar</td>
 <td>@debug_mode</td>
 </tr>
 <tr>
 <td>John Bristowe</td>
 <td>@johnbristowe</td>
 </tr>
 <tr>
 <td>Chris Eargle</td>
 <td>@kodefuguru</td>
 </tr>
 <tr>
 <td>Pinal Dave</td>
 <td>@pinaldave</td>
 </tr>
 </table>

&nbsp;

On rendering above HTML in browser you will get table as following. Certainly this table is not looking very immersive.

clip_image001

Using bootstrap we can style table as easily as setting class value. If you set class of table as table then table will stretch to all width available.

clip_image002

And you will notice the way table is rendering.

clip_image004

If you want strip table that can be done by just setting class value. A stripped table can be created in bootstrap as following,

clip_image005

As output table will render as given in below image,

clip_image007

Full source code of above stripped table is as following,


<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="Scripts/jquery-1.7.1.min.js"></script>
 <link href="Content/Site.css" rel="stylesheet" />
 <!-- Bootstrap references -->
 <script src="bootstrap/js/bootstrap.min.js"></script>
 <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>

 <h1>Bootstarp Sample</h1>
 <table class="table table-striped">
 <tr>
 <td>Dhananjay Kumar</td>
 <td>@debug_mode</td>
 </tr>
 <tr>
 <td>John Bristowe</td>
 <td>@johnbristowe</td>
 </tr>
 <tr>
 <td>Chris Eargle</td>
 <td>@kodefuguru</td>
 </tr>
 <tr>
 <td>Pinal Dave</td>
 <td>@pinaldave</td>
 </tr>
 </table>
</body>
</html>

In this post we focused on getting started with bootstrap. In further posts we will get into details of other aspects of bootstrap. I hope you find this post useful. Thanks for reading.

Flip Image on hover using CSS 3.0

In this post we will take a look on flipping images using CSS3.0. Let us assume that we have a div with two images as following,


<div id="flipimagediv">
 <img id="backImage" src="images/srt.jpg" />
 <img id="frontImage" src="images/msdhoni.jpg" />
 </div>

Now we want to flip these two images on mouse hover. We will achieve that using CSS3.0. To start with let us set container div style. In container we are setting width, height and display.


#flipimagediv {
display: inline-block;
width: auto;
height: auto;
position: relative;
}

After setting container div styles let us go ahead and set image styles. In image style we are setting usual properties like height and width. We are setting

  • transition-property
  • transition-duration
  • transition-timing-function

#flipimagediv img {
width: 400px;
height: 300px;
position: absolute;
transition-property: opacity;
transition-duration: 3s;
transition-timing-function: linear;
}

Last we need to change opacity of images on hover. We can do that  as following.


#flipimagediv #frontImage, #flipimagediv:hover #backImage {
opacity: 1;
}
#flipimagediv:hover #frontImage, #flipimagediv #backImage {
opacity: 0;
}

In this way we can flip images on hover using CSS 3.0. I hope you find this post useful. Thanks for reading.

Working with Knockout.js Part 6: Working with text binding

Working with Knockout.js Part 5: Working with visible binding

Working with Knockout.js Part 4: Observable Arrays

Working with Knockout.js Part 3: Working with Observables

Working with Knockout.js part 2: Understanding MVVM

Working with Knockout.js Part 1: Getting started with Knockoutjs

In last post we started learning about bindings. We had a look on visible binding . In this post we will learn a very important text binding.

Text binding is used to set text property of view elements from the properties or values of ViewModel. You can bind text of a span as easily as depicted in following code snippet,


<script type="text/javascript">

<em id="__mceDel">
 var studentViewModel = {
 studentName: ko.observable('DJ'),

 }

 </script>
<body>
 <span data-bind="text:studentName"></span>
 <script>
 ko.applyBindings(studentViewModel);
 </script>
</body></em>

Above we are creating a ViewModel named studentViewModel with property studentName. In HTML we are binding text property of span. So we can bind text property using following syntax,

Capture

Some time you may come across requirement to dynamically set the value of text binding. That is very much possible using functions and expressions to determine value of the text. Let us assume we have a function in ViewModel as give below,


var studentViewModel = {
 marks: ko.observable(90),
 }

And we can create computed function as following. This function will determine grade of the student.

 studentViewModel.grade = ko.computed(function () {

 if (this.marks > 96)
 return "Grade A";
 else
 return "Grade B";

 }, studentViewModel);

And we can simply bind computed property as text binding to span element on view. You can do this as following,


<body>
 <span data-bind="text:grade"></span>
 <script>
 ko.applyBindings(studentViewModel);
 </script>
</body>

The other way we can dynamically set text binding value by using conditional statement while binding. We can do bind grade without computed function as following


<span data-bind="text:marks()> 10 ? 'Grade A':'Grade B'"></span>

In this way we can work with text binding in knockoutjs. In further posts we will discuss other bindings. I hope you find this post useful. Thanks for reading.

What is Method Invocation Pattern in JavaScript

In this post we will take a look on “Method Invocation Pattern” in JavaScript. In JavaScript when function is defined as property of object then it is known as Method

image

Assume we have a JavaScript object as following. In studentObject object property findgrade is a function. So we can say findgrade is a method.


var studentObject =
{
name: "dj",
marks: 89,
findgrade: function (marks) {
if (marks > 75) {
return "Grade A ";
}
else {
return "Grade B ";
}
}
}

Invocation of method is known as “Method Invocation Pattern”. We can invoke method using dot operator on object. Method can be invoked as following,


var grade = studentObject.findgrade(99);
alert(grade);

A Method can access its parent object using operator this. Let us go ahead and modify studentobject as following. Now you can see that we are accessing other properties of object in method using this operator.


var studentObject =
{
name: "dj",
marks: 89,
grade : null,
findgrade: function (marks) {
if (marks > 75) {
this.grade = "A";
}
else {
this.grade = "B";
}
}
}

Now we can set grade property with invocation of findgrade method.


studentObject.findgrade(99);
var grd = studentObject.grade;
alert(grd);

Binding of method to object happens when we execute the method. In this way we can work with Methods and Method Invocation Pattern in JavaScript. I hope you find this post useful. Thanks for reading.

How to find index of an item in JavaScript Object Array?

Recently while working I came across a scenario. I had to find index of a particular item on given condition from a JavaScript object array. In this post we will see how to find index of object from JavaScript array of object.

Let us assume we have a JavaScript array as following,


var studentsArray =
[
{
"rollnumber": 1,
"name": "dj",
"subject": "physics"
},
{
"rollnumber": 2,
"name": "tanmay",
"subject": "biology"
},
{
"rollnumber": 3,
"name": "amit",
"subject": "chemistry"
},
];

Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.

We can do that by iterating through the array and comparing value at the given key.


function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {

for (var i = 0; i < arraytosearch.length; i++) {

if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}

You can use the function to find index of a particular element as below,


var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);

In this way you can find index of an element in JavaScript array of object. I hope you find this quick post useful. Thanks for reading.

Working with Knockout.js Part 5: Working with visible Binding

Working with Knockout.js Part 4: Observable Arrays

Working with Knockout.js Part 3: Working with Observables

Working with Knockout.js part 2: Understanding MVVM

Getting started with Knockout.js

So far we have learnt about different aspects of ViewModel creation in Knockout.js. We learnt and discussed about MVVM, Observable, and Observable Array etc. In this post we will dig into various bindings’ capability of Knockout.js.

In simpler terms we can define Knockoutjs binding as a mechanism to establish relationship between view and ViewModel. View takes user action and pass the instruction to ViewModel. One of the most popular example of this could be clicking on a button or selection of an item on the View by user. After each action of user, view got the task to instruct ViewModel about the same. This is done through the BINDING. On the other hand we can define binding as manipulating DOM elements and their appearance on the basis of ViewModel properties. This can be also done through the BINDING again. Binding establish the relationship between View and ViewModel.

image

Knockoutjs binding can be categorised in different categories. We can say that there could binding could be to manage flow of data and DOM elements. There could be binding to manage display and style of DOM elements. There could be binding for user actions like click and touch. There could be binding to handle flow of data from Model to View.

In this post we will focus on working with visible binding. As name suggests visible binding decides whether a DOM element will be visible or not on the basis of ViewModel property value.

Assume you have div .You can apply visible binding to div as following

image

And a simple ViewModel can be as follows,

image

Some points about visible binding is worth discussing here, If value of ViewModel property will resolved to following values then bind DOM element view property will be set to block.

  • Null
  • undefined
  • number zero
  • Boolean false

For DOM elements if ViewModel property value is yielding to false then visible binding will always have more priority than CSS attributes.

image

Now to understand view binding in better way let us create two buttons. On click of one button div will be visible and on click of another button div visibility would be false. If you notice in ViewModel creation we have created property of ViewModel as observable property. Hence whenever value of this property will change, it will notify the View.

Let us assume we have HTML with one div and two buttons as following,

<body>
 <div data-bind="visible:displayViewDiv">
 <h2>This div will be visible and hidden thrugh visible binding </h2>
 </div>

<div>
 <button id="btnshowdiv" >Click to show Div</button>
 <button id="btnhidediv" >Click to hide Div</button>
 </div>
 <script>
 ko.applyBindings(divdispalyViewModel);
 </script>
</body>

We will create ViewModel with observable property .This property is bind with visible property of DOM element div. So ViewModel is created as follows,


var divdispalyViewModel = {

displayViewDiv: ko.observable(true)
 };

Now on click event of buttons we will set value of ViewModel property. Since property is an observable property hence it will notify view on value changed and view will get refresh automatically.


$(document).ready(function () {

 $('#btnshowdiv').click(function () {

divdispalyViewModel.displayViewDiv(true);
 });
 $('#btnhidediv').click(function () {

divdispalyViewModel.displayViewDiv(false);
 });

});

You will notice that Div is visible and hidden on clicking of buttons. We are handing div visibility using visible binding of Knockoutjs.

In this post we started with the discussion of binding. In further posts we will learn about other bindings as well. I hope you find this post useful. Thanks for reading.