//Function declaration
function foo() { return 5; }

//Anonymous function expression
var foo = function() { return 5; }

//Named function expression
var foo = function foo() { return 5; }

function declarations loads before any code is executed.While function expressions loads only
when the interpreter reaches that line of code.

So if you try to call a function expression before it’s loaded, you’ll get an error

But if you call a function declaration, it’ll always work. Because no code can be called until all declarations are loaded.

Function Expression

  alert(foo()); // ERROR! foo wasn't loaded yet
  var foo = function() { return 5; } 

Function Declaration

  alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
  function foo() { return 5; } 

The difference is in First case foo() is defined at run-time, whereas in second case foo() is defined at parse-time
for a script block

Getting GMT Time for the Day

 var strDate = new Date();

 hour = strDate.getUTCHours().toString();
 minute = strDate.getUTCMinutes().toString();
 second = strDate.getUTCSeconds().toString();

 if (hour.length == 1) { hour = "0" + hour; }
 if (minute.length == 1) { minute = "0" + minute; }
 if (second.length == 1) { second = "0" + second; }

 Cal.SetHour(hour); 
 Cal.SetMinute(minute); 
 Cal.SetSecond(second);

How to set a Specific option as selected

<html>
<head>
	<script src="jquery-2.1.0.min.js" type="text/javascript"></script>
	<script>
	 $('document').ready(function(){
	   $('#btnSubmit').click(function(){
            alert($('#cboLocation').val());
            alert($('#cboLocation').find(":selected").text());
			});
		});
	</script>
</head>
<body>
<select name="cboLocation"  id="cboLocation">
  <option value="">Select Zone</option>
  <option value="South">South Chennai</option>
  <option value="North">North Chennai</option>
  <option value="East">East Chennai</option>
  <option value="West">West Chennai</option>
</select>
<input type="button" name="btnSubmit" id="btnSubmit" value="Click Me"/>
</body>
</html>

How to get Selected Item Value

 alert($('#cboLocation').val());

How to get Selected Item Text

 alert($('#cboLocation').find(":selected").text());

What is Node?

  1. Node is not a programming language rather runtime environment to run Javascript code
  2. Browsers provide runtime environment to run javascript.Node uses Chrome v8 engine internally to run js code.
  3. In Traditional server request are assigned a thread and the response would be server. So there exist one thread for each request.The threads cannot be shared and Blocking and Synchronous in nature
  4. In node there is single thread and all these request would be served by this single thread hence its is Nonblocking and Asynchronous in nature.
  5. Because of this asynchronous nature node is not suitable for Data intensive operations and for image manipulation, Since the threads would be locked for a long time
  6. Since node application runs in an environment outside broswer it provides file handling operations which are not possible by browsers.

How the Execution of js files in Node happens

  1. Node variables has 2 scopes –
    • Global Scope
    • Local Scope or Module Scope
  2. Variables like Window, Console is global scope as they are accessed globally over broswer
  3. In Node everything is a module. Each js file would be accounted for as a module. The js file execution happens within its own module scope.
  4. The below statements are same in node
      console.log('Uses console without global prefix');
      global.console.log('Uses console with global prefix');
     

    Output

    Uses console without global prefix
    Uses console with global prefix
    
  5. Let’s try to print the module variable in Node js using below code.The code below prints the details of the module such as js file name, exports done from module and so on.
      console.log(module); 
     

    Output

    Module {
      id: '.',
      exports: {},
      parent: null,
      filename: 'D:\\AngularProjects\\NodeServer\\index.js',
      loaded: false,
      children: [],
      paths:
       [ 'D:\\AngularProjects\\NodeServer\\node_modules',
         'D:\\AngularProjects\\node_modules',
         'D:\\node_modules' ] }
    
  6. Exporting Variable and Function From Module
    We exported a variable and a function from logger.js and we called the same in index.js.Now when you run console.log(module) we can see the exported functionality in exports
    logger.js

    var log = "Log Me"
    
    function getLoggedValue(message){
        console.log(message);
    }
    
    module.exports.log=log;
    module.exports.printLog=getLoggedValue;
     

    index.js

    const logger = require('./logger');
    console.log(logger.log);
    logger.printLog('Hi there');
    

    Output

    Log Me
    Hi there
    

    You can see what is imported simply by using below statement in index.js
    index.js

    const logger = require('./logger');
    console.log(logger);
    

    Output

    { log: 'Log Me', printLog: [Function: getLoggedValue] }
    
  7. In case you are having just a single function the same thing can be accessed in the imported js as below. Let export just a single function in logger.js
  8. logger.js

    var log = "Log Me"
    
    function getLoggedValue(message){
        console.log(message);
    }
    
    module.exports=getLoggedValue;
    

    index.js

    const logger = require('./logger');
    logger('Hi there');
    

    Output

    Hi there
    
  9. Node always executes modules inside immediately invokable function expression.It is called Module Wrapper Function
    (function(exports, require, module, __filename, __dirname) {
    // Module code actually lives in here
    });
    

    Before a module’s code is executed, Node.js will wrap it with a function wrapper that looks like the following:
    By doing this, Node.js achieves a few things:It keeps top-level variables (defined with var, const or let) scoped to the module rather than the global object.
    It helps to provide some global-looking variables that are actually specific to the module. The module and exports objects that the implementor can use to export values from the module.The convenience variables __filename and __dirname, containing the module’s absolute filename and directory path.

Modules in Node
Node is a combination of different modules we interact with based on our needs. Below are a few of them as listed.

  1. Path – Using path we are listing the details of the filename
  2. OS – We check for the total memory and free memory
  3. File – We list the files in the directory.Always use asynchrounous reading mode(fs.readdir) for file instead of (fs.readFileSync).
  4. Events
  5. Http

index.js

console.log('-------Path module-------');
const path = require('path');
var pathObj = path.parse(__filename);
console.log(pathObj);

console.log('------OS module--------');
const os = require('os');
var totalMem = os.totalmem();
var freeMem = os.freemem();
console.log(`Total Memory -  ${totalMem}`);
console.log(`Free Memory -  ${freeMem}`);

console.log('------FS Module--------');
const fs = require('fs');
fs.readdir('./', (err, files)=>{
    if(err)
     console.log('Error', err);
    else 
     console.log('Files', files);
});

Output

-------Path module-------
{ root: 'D:\\',
  dir: 'D:\\AngularProjects\\NodeServer',
  base: 'index.js',
  ext: '.js',
  name: 'index' }

------OS module--------
Total Memory -  8465264640
Free Memory -  1929568256

------FS Module--------
Files [ 'index.js', 'logger.js', 'package-lock.json', 'test.html' ]

Event Module
Event is a singnal which tells something has happened.Below is a simple code for event listener

  1. We acquire handle of event class using require in EventEmitter
  2. Create object using new for EventEmitter
  3. Add the event to listener and define a function which needs to be called when the event gets fired
  4. Adding the event could be done using addListener and also by using on method
  5. Emit the event using emit methid

index.js

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.addListener('Message Listener', ()=>console.log('Listener Called'));
emitter.emit('Message Listener');

Output

Listener Called

Lets try to pass arguments to event listener. Arguments should always be passed as JSON Objects as as one parameter inorder to avoid confusion though passing as a individual argument is going to work fine.
index.js

const EventEmitter = require('events');
const emitter = new EventEmitter();

emitter.addListener('Message Listener', (argObj)=>{
                                                    console.log(argObj.argument1);
                                                    console.log(argObj.argument2);
                                                  });
emitter.emit('Message Listener', {'argument1':'arg1 val', 'argument2':'arg2 val'});

Output

arg1 val
arg2 val

Now let’s build a custom class which does the logging

  1. We have a logger.js which is a utility class with log method in it
  2. We call the log method from eventList class by importing the Logger Class
  3. In the logger we extend event emitter and use this reference to call the eventEmitter

logger.js

const EventEmitter = require('events');

class Logger extends EventEmitter
{
    log(strLogMessage)
    {
        this.emit('MessageListener', strLogMessage);        
    }
}

module.exports = Logger;

eventList.js

const Logger = require('./logger');

const objLogger = new Logger(); 

objLogger.addListener('MessageListener', (arg) =>{console.log(arg)});
objLogger.log('Calling the Log Method');

Output

Calling the Log Method

HTTP Module
server.js

const http = require('http');

const server = http.createServer();

const server = http.createServer((req, res)=>{
    if(req.url === '/')
    {
        res.write('Hello World...');
        res.end();
    }

    if(req.url === '/api/customers')
    {
        res.write(JSON.stringify(['Customer1', 'Customer2', 'Customer3']));
        res.end();
    }
});

server.listen(3000);
console.log('Listening on Port 3000.....');

Input and Output

IP : http://localhost:3000/
OP : Hello World...

IP : http://localhost:3000/api/customers
OP : ["Customer1","Customer2","Customer3"]

Common elements in two arrays javascript

arrNum1 = new Array(1,2,3);
arrNum2 = new Array(2,3,4,5);
arrNum3 = new Array();

arrNum3 =  intersect_safe(arrNum1, arrNum2);

for(i=0;i<arrNum3.length;i++)
 alert(arrNum3[i]);

function intersect_safe(a, b)
{
  var ai=0, bi=0;
  var result = new Array();

   while(ai<a.length && bi < b.length )
  {
     if(a[ai] != b[bi])
     { 
       bi++; 
     }
     else
     {
       result.push(a[ai]);
       ai++;
       bi++;
     }
  }

  return result;
}
var arr = new Array();
arr[0] = 100;
arr[1] = 0;
arr[2] = 50;

Array.prototype.max = function() {
  return Math.max.apply(null, this)
}

Array.prototype.min = function() {
  return Math.min.apply(null, this)
}

var min = Math.min.apply(null, arr),
    max = Math.max.apply(null, arr);

To find the Maximum value in Array Use Below

 var max_of_array = Math.max.apply(Math, array);
        url = "/property/realestate_statistics/";	
	
	lngCityId = $('#cboCityName').val();
	
        $.post(
	  url,
	  {
	   "act" 		: "GetCommonLocation",
	   "CityId" 		: lngCityId
	  },
	  function(responseText){		
	   $('#cboLocation').html(responseText);		
	   $('#cboPropertyType').html('');
  	   $('#cboPropertyType').append( new Option('Property Type',''));      			
	   $('#cboPropertyType').val('Property Type');
	  }, 
	  "html"
	);

I have a response text coming after changing city and this will be populated in second drop down
cboLocation. Now the third drop down should be repopulated based on property type at city by taking common location selected in to consideration. for that you should reset property type apart from resetting cboLocation.

To do so

        $('#cboPropertyType').html('');
  	$('#cboPropertyType').append( new Option('Property Type',''));      			
	$('#cboPropertyType').val('Property Type');
  1. $(‘#cboPropertyType’).html(”) – To empty the Content of Drop down
  2. $(‘#cboPropertyType’).append( new Option(‘Property Type’,”)) – It should Contain only Property Type in Option so i am Appending that
  3. $(‘#cboPropertyType’).val(‘Property Type’) – It should point to only one option that exixts