1. Function is represented as Object in Javascript
  2. Has 2 phases – Function Definition and Function Execution
  3. Two ways of defining function
    Function Declaration / Named Function – Function object would get created at scope creation phase
    Function Expression / Anonymous Function – Function object would get created at execution phase – Interepreter would throw error incase the function is called before anonymous definition.

      
      //Named Function
     displayAge(); 
     
     function displayAge(){
      console.log('My Age is 33')
     } 
     
     //Anonymous Function 
     var age = function(){ //Context/scope execution phase
       console.log('My Age is 33')
     } 
     age();
    
  4. No concept of function overloading. Function with near matching argument would be called.In the below code getSum has 2 arguments but still it gets called.
    function getSum(num1, num2) {
      console.log('Function overloading is not possible');
    }	
    getSum();
    
      Function overloading is not possible
    
  5. Function namespace context would be created with the samename as the function namespace
  6. In the below code the getLunch appears to be overloaded but there would be only one namespace in context with name getLunch
  7. So you may expect the output to be different but all the times getLunch(buffey, paid) would be called in below code
    function getLunch() {
      console.log('Free Lunch');
    }
    
    function getLunch(paidLunch) {
      console.log('paidLunch');
    }
    
    function getLunch(buffey, paid) {
      console.log('paidLunch buffey');
    }
    getLunch();
    getLunch(5);
    getLunch(5,10);
    

    Output

    paidLunch buffey
    paidLunch buffey
    paidLunch buffey
    
  8. So what would be the workaround. Check the code as below
     
      function getLunch() {
      if(arguments.length === 0)
        console.log('Free Lunch');
      
      if(arguments.length === 1)
        console.log('paidLunch');
        
      if(arguments.length === 2)
        console.log('paidLunch buffey');
      }
      
       getLunch();
       getLunch(5);
       getLunch(5,10);
    

    Output

    Free Lunch
    paidLunch
    paidLunch buffey
    
  9. Using Restparameter feature from ECMAScript6
     
    function getLunch(bill, space, ...menu) {
      console.log(bill);
      console.log(space);
      console.log(menu);
    }
    
    getLunch(150, 'Open Terrace', 'idly', 'dosa', 'vada');
    

    Output

    150
    Open Terrace
    ["idly", "dosa", "vada"]
    
Posted in JS.
  1. Node Package manager is a package manager which ships along node
  2. It is a Javascript package manager which helps to manage modules like HTTP, Event etc..
  3. Once the npm init is run package.json would be created in the project folder.It is similar to pom.xml for Maven project which saves all the settings and dependencies
  4. To check the npm version
    >>npm -v 
    >>npm --version
    
  5. To create a new project we use the below command – take default setting by telling -yes
    >>npm init -yes
    
  6. To Install a new package is as below
    >>npm install NAME_OF_PACKAGE
    
  7. To Set particular config name
    >>npm set CONFIG_KEY CONFIG_VALUE
    >>npm set init-licencse "MIT"
    
  8. To Get particular config name
    >>npm get CONFIG_KEY 
    >>npm get init-licencse
    
  9. To Install a new package
    >>npm install packagename
    >>npm install loadash
    

    Running the above command is going to create a node_modules folder in project with the dependencies for the package(loadash) installed.

  10. To Install only dependencies that are needed to run app other than utility dependencies like gulp which provides minified version of JS use below command
    >>npm install --production
    
  11. To remove dependencies
    >>npm remove gulp
    
  12. To install specific version
    >>npm install gulp@4.7.3
    
  13. To update latest version
    >>npm update gulp
    
  14. Semantic versioning formart.PatchVersion includes bug fixes and minor tweaks
    MajorVersion.MinorVersion.PatchVersion
    4.7.8
    
  15. How to find the location of node modules
    >>npm root -g
    

    This will take you to location C:\Users\Mugil\AppData\Roaming\npm\node_modules

  16. How to install server globally – live-server will reload the JS files without restart of server
    >>npm install -g live-server
    

    This will take you to location C:\Users\Mugil\AppData\Roaming\npm\node_modules

  17. When you move the project to new environment no need to move the node_modules folder similar to avoiding JAR while shifting java application.We just need to move the JS file and package.json which contains the details of dependencies. Running npm install will read the package.json file and load the dependencies in new environment

package.json

   "name": "my_package",
    "description": "",
    "version": "1.0.0",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "dependencies": {"loadash" : 14.7.8},
    "keywords": [],
    "author": "",
    "license": "ISC",
    "bugs": {
      "url": "https://github.com/ashleygwilliams/my_package/issues"
    },
    "homepage": "https://github.com/ashleygwilliams/my_package"
  }

How to run some js file in the beginning of the server
I have JS server which needs to start at the beginning of application. In such case I would be defining the JS file in scripts.
You need to call npm start after chaning package.json file
package.json

.
.
"scripts": {
      "start": "node server.js"
    }
.
.

Let’s create a simple application which greets with Welcome message in console on start
package.json

{
  "name": "school",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "Mugil",
  "license": "ISC"
}

index.js

console.log('Welcome to School .....');

output

Welcome to School .....

package.json
live-server allows you to run code without restarting server after changes.

.
.
"scripts": {
    "start": "node index.js",
    "server": "live-server"
  }
.
.
>>npm run server
  1. Obersvable and Observer are from RxJS similiar to Event and Event listener
  2. Observer can listen to three actions of observable that is next, error and complete
  3. Below we create a observer JSON key value pair and calling function based on the action from observable
  4. We need to subscribe to Observable in ourcase observable and pass observer as parameter
  5. We should unsubscribe to obeservable once we are done inorder to prevent memory leaks

test.html

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.0/Rx.js"></script>

    <script>
        var observer = {
            next: function (value) { console.log(value); },
            error: function (error) { console.log(error); },
            complete: function () { console.log("Completed..!") }
        };


        const observable = new Rx.Observable(obs => {
            obs.next(102);
            obs.next(103);
            setTimeout(function () {
                obs.next(109);
                obs.complete("Completed");
            }, 2000);
        });

        observable.subscribe(observer);
    </script>

Observable over Stream
Observable is similar to event which keeps happening. During its occurance it could emit values, throw error or comes to complete.

setTimeout is the functionality which comes along with the webapi whereas setInterval is javascript implementation.

setTimeout(expression, timeout); runs the code/function once after the timeout.
The clearTimeout() method stops the execution of the function specified in setTimeout().

function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);

Output

run your code here when time interval is reached

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.

function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);

Output

run your code here when time interval is reached

In javascript date validation, while checking selected date is less than or equal to today’s date, time should be taken into consideration otherwise even when the selected day is equal to today’s date the validation fails.

i.e

 
 var strStartDate          = $("selectedStartDate").val();
 var strStartDateFormatted = new Date(strStartDate);
 var today                 = new Date();
 
 today.setHours(12,0,0,0);

  if(strStartDateFormatted == today)
    console.log("Both are Same");

new Date() will return date with time where as date returned using the datepicker does not contain time so if you directly compare new Date() which comes along with time it would return false even when the date-month-year are equal.

Date.prototype.withoutTime = function () {
    var d = new Date(this);
    d.setHours(0, 0, 0, 0);
    return d;
}

var date1 = new Date(2014,1,1);
new Date().withoutTime() > date1.withoutTime(); // true

How can I add Key/Value pair to Object

var obj = {
    key1: value1,
    key2: value2
};

There are two ways to add new properties to an object

Method 1 – Using dot notation

 obj.key3 = "value3";

Method 2 – Using square bracket notation

 obj["key3"] = "value3";

The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:

var getProperty = function (propertyName) {
    return obj[propertyName];
};

getProperty("key1");
getProperty("key2");
getProperty("key3");

A real JavaScript array can be constructed using either:

The Array literal notation:

var arr = [];

The Array constructor notation:

var arr = new Array();

Simple 2 Dimensional Array

 var grades = [[89, 77, 78],[76, 82, 81],[91, 94, 89]];
 print(grades[2][2]); 

Method 1

var numeric = [
    ['input1','input2'],
    ['input3','input4']
];
numeric[0][0] == 'input1';
numeric[0][1] == 'input2';
numeric[1][0] == 'input3';
numeric[1][1] == 'input4';

Method 2

var obj = {
    'row1' : {
        'key1' : 'input1',
        'key2' : 'inpu2'
    },
    'row2' : {
        'key3' : 'input3',
        'key4' : 'input4'
    }
};
obj.row1.key1 == 'input1';
obj.row1.key2 == 'input2';
obj.row2.key1 == 'input3';
obj.row2.key2 == 'input4';

Method 3

var mixed = {
    'row1' : ['input1', 'inpu2'],
    'row2' : ['input3', 'input4']
};
obj.row1[0] == 'input1';
obj.row1[1] == 'input2';
obj.row2[0] == 'input3';
obj.row2[1] == 'input4';

Creating a Multidimensional Array on Fly

var row= 20;
var column= 10;
var f = new Array();

for (i=0;i<row;i++) {
 f[i]=new Array();
 for (j=0;j<column;j++) {
  f[i][j]=0;
 }
}

Method to create a Javascript Multidimensional Array

Array.matrix = function(numrows, numcols, initial) {
var arr = [];
for (var i = 0; i < numrows; ++i) {
var columns = [];
for (var j = 0; j < numcols; ++j) {
columns[j] = initial;
}
arr[i] = columns;
}
return arr;
}

Sample Test Values

var nums = Array.matrix(5,5,0);
print(nums[1][1]); // displays 0
var names = Array.matrix(3,3,"");
names[1][2] = "Joe";
print(names[1][2]); // display "Joe"

1.Form reset javascript does not work for hidden field

 function resetForm()
 {
   document.getElementById("SetUpForm").reset();
 }
 

The reset() functionality in javascript is intended for clearing user input, and since hidden inputs are not directly accessible by the user, it doesn’t make sense to allow the user to reset the hidden input’s value.

2.Dropdown should be reset by Javascript if selected is used.
The Same way this does not work in dropdown where the value is set to selected.The values of the dropdown should be manually reset by adding below code to above

 function resetForm()
 {
   document.getElementById("SetUpForm").reset();

   $("#cboAge").val('');
   $("#cboCity").val('');
 }
 
  1. In the below page the Checkbox checked values should be maintained as comma separated values.
  2. If select all checkbox at the top is clicked all the checkbox in that column should be marked as clicked.
  3. In the same way if all individual checkbox are selected the select All checkbox should be Marked as Clicked.

function changeInvestmentIds(pThis) 
{   	
    	if($(pThis).is(":checked"))
    	{	
      	      //Hidden variable which stores the CSV values of Checkbox
  	      if($('#csvSelectedInvestmentIds').val() != '')    	  
  	    	 arrInvstIds = $('#csvSelectedInvestmentIds').val().split(',');	
    		
	       arrInvstIds.push($(pThis).val());
	      
	      $('#csvSelectedInvestmentIds').val(arrInvstIds.join(","));
    	}
        else
        //Incase the checkbox is unchecked the values shld be removed from hidden variable 
    	{	
    		arrInvstIds = $('#csvSelectedInvestmentIds').val().split(',');
    		
    		for(var i = arrInvstIds.length; i--;) {
  	          if(arrInvstIds[i] === $(pThis).val()) {
  	        	  arrInvstIds.splice(i, 1);
  	          }
  	      }	
    		
    	  $('#csvSelectedInvestmentIds').val(arrInvstIds.join(","));
      	}    	
    	
        //This is called here incase all checkbox are checked the 
        //select all should also be checked
    	chkIsAllChecked();


    	setParentWindowVal();
}

//Incase selectAll checkbox is ticked all the checkbox should be marked as checked.
function toggleSelectAll(source) 
{		
	  csvInvestmentIds = '';	
	  var arrInvIds = [];
		  
	  if($(source).prop('checked'))	  
	   $('.chkInvestmentClass').prop('checked', true);	  
	  else	  
	   $('.chkInvestmentClass').prop('checked', false);		   
	  
            
	  if($(source).prop('checked'))
	  {
                  //The values of all the checkbox are  added to array and
                  //moved to csv hidden variable 
		  $(".chkInvestmentClass").each(function() {		  
			  arrInvIds.push($(this).val());
		  });
		  
		  $('#csvSelectedInvestmentIds').val(arrInvIds.join(","));
	  }else		  
	    $('#csvSelectedInvestmentIds').val('');
	  
	  setParentWindowVal();	  
}


//This function is to check if all check boxes when checked
//individually the select all check box should be checked
function chkIsAllChecked()
{
 if($('.chkInvestmentClass:checked').length == $('.chkInvestmentClass').length)		  
  $('#chkSelectAll')[0].checked=true;
 else
  $('#chkSelectAll')[0].checked=false;
}

HTML Code

  1. changeInvestmentIds(pThis) function is called in each checkbox when click event is carried out.
  2. toggleSelectAll(source) is called when selectAll checkbox is Clicked
  3. chkIsAllChecked() is called internally in changeInvestmentIds(pThis)
<table>
<thead>
<tr>
<th>
Locations
</th>
<th>
<input type="checkbox" name="chkSelectAll" value="SelectAll" styleId="selectAllChkBx" onclick="toggleSelectAll(this);"/>
</th>
<tr>
</thead>
<tbody>
 <tr>
 <td>Chennai</td>
 <td> 
  <input type="checkbox" name="chkInvestmentIds" value='Chennai' />' class="chkInvestmentClass" 
				onclick="changeInvestmentIds(this)">
</td>
</tr>
 <tr>
 <td>Bangalore</td>
 <td> 
  <input type="checkbox" name="chkInvestmentIds" value='Bangalore' />' class="chkInvestmentClass" 
				onclick="changeInvestmentIds(this)">
</td>
</tr>
 <tr>
 <td>Mumbai</td>
 <td> 
  <input type="checkbox" name="chkInvestmentIds" value='Mumbai' />' class="chkInvestmentClass" 
				onclick="changeInvestmentIds(this)">
</td>
</tr>
</tbody>
</table>