Tuesday, December 7, 2021

Debouncing and Throttling in JavaScript

Hi, Debouncing and Throttling concepts are little bit hard and confusing for anyone who is trying to understand first time. Some time I get confused with the logics that which one called debounce and which logic called throttling.

So here I am trying to write few things so that we can remeber it always. Followings are few real life examples of debouncing:

  • When we press a electronic button, like TV remote button, there are chances that it gets pressed multiple time in micro/mili seconds, but there is debouncing logic there so that multiple times button pressinga are ignored for those micro/mili seconds, so input gets considered only for once, other signals get bounced
  • One more real life example I would like mention. If you have ever used or seen hand dryer in some place, it uses debounce. Let me explain, when you place your hand in it then it starts running, now if you get your hand out for few seconds, it still runs and if you place your hand in that again then it continues running. So what is happening here, hand dryer has a sensor which check if your hand is in the dryer or not in few seconds(suppose 3 seconds). When you take out your hand from dryer it wait for 3 seconds to switch it off. If you place your hand again say after 2 seconds then action to switch off is canceled. So whenever you take out hand hand action for close is registered and it will get closed if not detect hand for 3 seconds. Suppose if we have done the programming for this in JS then it would be like this:

    Placing image for reference

    First basic version will be like below where no debouncing is used:

          // method to switch off dryer
          switchOff(){ 
         	// ....some code
          }
          // method to switch on dryer
          switchOn(){
          	// ....some code
          }
          
          addEventListener("handOn", switchOn);
          
          addEventListener("handOff", switchOff);
          
        

    In this scenario it will be very jerky in switching on and off when user's will use dryer as we move our hands during drying. Now let's see how we can improve this?

          var timerId;
          // method to switch off dryer
          switchOff(){ 
         	// .... some code
          }
          // method to switch on dryer
          switchOn(){
          	// .... some code
          }
          
          addEventListener("handOn", function(){
          	clearTimeout(timerId);
            switchOn();
           );
          
          addEventListener("handOff", function(){
            clearTimeout(timerId);
          	timerId = setTimeout(function(){
    	        switchOff(); 
            }, 3000);
          });
        

    In the above code we are clearing the previuos action if it occurs before 3 seconds, that is called debouncing

  • One more example I would like to mention here, suppose there is one child and he is demanding cake from his mom. Now mom do not want to give the cake whenever he demand, but mom said if you keep quiet for 30 mins then you will get the cake. So if child is quiet for 30 mins atleast then mom give him a cake, but he makes noise in between then counter is again reset. So this is also a debounce condition for giving the cake if child make noise

Throttling

One example of throttling by which you can understand it:

Imagine yourself as a 7-year-old toddler who loves to eat chocolate cake! Today your mom has made one, but it's not for you, it's for the guests! You, being spunky, keep on asking her for the cake. Finally, she gives you the cake. But, you keep on asking her for more. Annoyed, she agrees to give you more cake with a condition that you can have the cake only after an hour. Still, you keep on asking her for the cake, but now she ignores you. Finally, after an interval of one hour, you get more cake. If you ask for more, you will get it only after an hour, no matter how many times you ask her.
This is what throttling is!


Saturday, March 9, 2019

What Happens When You Write www.google.com and Hit Enter

There are lots of processes involved if we go in every detail, but I am covering few points which will give insights of processes involved from a URL enter till the page displayed in the browser

  1. Browser checks for cache if requested url matches in cache then go to step #4
  2. If not available in the cache then browser ask OS for server IP address
  3. OS makes a DNS lookup and replies the IP address to the browser
    1. Since the operating system doesn’t know where “www.google.com” is, it queries a DNS resolver.
    2. For most users, their DNS resolver is provided by their Internet Service Provider (ISP)
    3. The resolver starts by querying one of the root DNS servers for the IP of “www.google.com.” The root is represented in the hidden trailing “.” at the end of the domain name. Typing this extra “.” is not necessary as your browser automatically adds it.
    4. There are 13 root server clusters named A-M with servers in over 380 locations. They are managed by 12 different organizations that report to the Internet Assigned Numbers Authority (IANA), such as Verisign, who controls the A and J clusters. All of the servers are copies of one master server run by IANA.
    5. These root servers hold the locations of all of the top level domains (TLDs) such as .com, .de, .io, and newer generic TLDs such as .camera.
    6. The root doesn’t have the IP info for “www.google.com,” but it knows that .com might know, so it returns the location of the .com servers. The root responds with a list of the 13 locations of the .com gTLD servers, listed as NS or “name server” records.
    7. Next the resolver queries one of the .com name servers for the location of google.com. Like the Root Servers, each of the TLDs has 4-13 clustered name servers existing in many locations. There are two types of TLDs: country codes (ccTLDs) run by government organizations, and generic (gTLDs). Every gTLD has a different commercial entity responsible for running these servers. In this case, we will be using the gTLD servers controlled by Verisign, who run the .com, .net, .edu, and .gov among gTLDs.
    8. Each TLD server holds a list of all of the authoritative name servers for each domain in the TLD. For example, each of the 13 .com gTLD servers has a list with all of the name servers for every single .com domain. The .com gTLD server does not have the IP addresses for google.com, but it knows the location of google.com’s name servers. The .com gTLD server responds with a list of all of google.com’s NS records. In this case, Google has four name servers, “ns1.google.com” to “ns4.google.com.”
    9. Finally, the DNS resolver queries one of Google’s name server for the IP of “www.google.com.”
    10. This time the queried Name Server knows the IPs and responds with an A or AAAA address record (depending on the query type) for IPv4 and IPv6, respectively.
    11. At this point the resolver has finished the recursion process and is able to respond to the end user’s operating system with an IP address.
  4. Browser opens a TCP connection to the server (this step is much more complex with HTTPS)
    1. Client sends SYN packet.
    2. Web server sends SYN-ACK packet.
    3. Client answers with ACK packet, concluding the three-way TCP connection establishment.
  5. Browser sends the HTTP request through TCP connection
    1. Web server processes the request, finds the resource, and sends the response to the Client. Client receives the first byte of the first packet from the web server, which contains the HTTP Response headers and content.
  6. Client loads the content of the response
  7. Web server sends second TCP segment with the PSH flag set.
  8. Client sends ACK. (Client sends ACK every two segments it receives. from the host)
  9. Web server sends third TCP segment with HTTP_Continue.
  10. Browser receives HTTP response and may close the TCP connection, or reuse it for another request
    1. Client sends a FIN packet to close the TCP connection.
  11. Browser checks if the response is a redirect or a conditional response (3xx result status codes), authorization request (401), error (4xx and 5xx), etc.; these are handled differently from normal responses (2xx)
  12. If cacheable, response is stored in a cache, following key in response header tells the browser to cache or not any request’s response
    1. Preventing caching (Cache-Control: no-cache, no-store, must-revalidate)
    2. Caching static assets (Cache-Control: public, max-age=31536000)
  13. Browser decodes response (e.g. if it's gzipped)
  14. The browser determines what to do with the response (e.g. is it an HTML page, is it an image, is it a sound clip, is it a js file, CSS file ?) using content-type in the respnse header
  15. The browser renders response or offers a download dialog for unrecognized types
    1. In case of html file, browser parse the html to create the DOM (Document Object Model)
    2. If during parsing browser gets js file with script tag then browser pause the dom parsing and start downloading the js file and execute the js code
      1. In case js file script tag has async attribute then downloading happens parallely but at the time of js code execution DOM parser stops
      2. In case js file script tag has defer attribute then downloading happens parallelly and js code executed after DOM completion
    3. If during html document parsing browser gets CSS file then DOM parsing is not blocked and CSS files downloaded parallely
      1. CSS file blocks rendering, once css is downloaded CSSOM (CSS object model) is created
      2. The DOM and CSSOM trees are combined to form the render tree
      3. Render tree contains only the nodes required to render the page
      4. Layout computes the exact position and size of each object
      5. The last step is paint, which takes in the final render tree and renders the pixels to the screen
      6. And now you see the www.google.com page in the browser

Monday, November 13, 2017

Promise in JavaScript, Understanding With Example

Hi, I am trying to explain here the Promise in JavaScript little bit with the help of example. Suppose we want to perform 3 tasks (task1, task2, task3), and we want to perform some other action when all three task are completed and we don't know how much time any task will take then surely we need to apply some logic in our code then we can achieve this but using Promises this is very easy to do.

Let's see this example:

Creating tasks using promises

 function task1(){
        return new Promise(function(resolve, reject){
         setTimeout(function(){
          resolve("Hello Task1 is done");  // we can use reject also on the basis of some condition.
         },5000)
        });
}
function task2(){
        return new Promise(function(resolve, reject){
         setTimeout(function(){
          resolve("Hello Task2 is done");
         },3000)
        });
}

function task3(){
        return new Promise(function(resolve, reject){
         setTimeout(function(){
          resolve("Hello Task3 is done");
         },7000)
        });
}

In above example I have taken setTimeout with some time but in real scenarios it can be some aync ajax request. Now suppose we need to perform some action on completing all three tasks.

Promise.all([task1(), task2(), task3()]).then(function(value){ 
    // do your action here
    console.log(value);
 });

// output for above code will come after 7 seconds as this is the maximum time that task3 will take:
["Hello Task1 is done", "Hello Task2 is done", "Hello Task3 is done"]

For more detail of Promise in JavaScript you can refer this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Friday, September 22, 2017

Convert Multiline Text Into Single Line for HTML page

If you want to create your multiline message in single line for html which will be shown on the browser with multiline then just paste/write here your multiline message as it is and then click on "Convert" button:



Use Ctrl + C to copy the message OR right click and copy

Thursday, September 15, 2016

Why call and apply two methods available in JavaScript

I hope everyone know about what is call and apply. Just for reminder,

The call() method calls a function with a given this value and arguments provided individually

 myFunction.call(thisArg[, arg1[, arg2[, ...]]])

The apply() method calls a function with a given this value and arguments provided as an array

 myFunction.apply(thisArg, [argsArray])

So both call and apply do similar job as to change the scope of function in which it gets executed (change this of function). So why exactly JavaScript has these 2 methods, one to pass array as an argument and another as the comma separated args. As per my experience in JavaScript I found few places where actually we can use apply but not call. May be you got some other examples also then please share. I would like to take one example here. Suppose we need to find out the min in a given array of integer (unsorted), what will be your approach? First approach we can think to search and find min or sort the array and find min. But if the question is, you have 5 numbers and find out the min of these 5 numbers, now can you think to use Math library (Math.min) in this case and find out min

 // we can pass individual numbers comma separated in Math.min and find out min easily
 Math.min(4,1,8,3,7) // 1

Now think about using array here.......??? can we pass array in this Math.min ? ..... Yes we can !

 var ar = [4,1,8,3,7];
 Math.min.apply(undefined, ar) // 1

Now suppose if only call is available in javascript we can not achieve this using call

In ES6 there is one more way to achieve this. Spread/rest parameter

 var ar = [4,1,8,3,7];
 Math.min(...ar) // 1
Know more about spread/rest parameter

Saturday, August 27, 2016

Align Element in Center

Align element in centre position of the screen using only CSS

Horizontal alignment is very easy on the screen. But some times alignment in vertical is very difficult

Horizontal alignment

To align an element horizontally best approach is using margin

 margin: 0 auto;

Vertical alignment

To align an element vertically we can use this approach

  transform: translateY(-50%);
  position: relative;
  top: 50vh; 

There is one another approach to center it using CSS3 flex property

 // on the parent element we just need to apply flex properties
  height: some height;
  display: flex;
  justify-content: center;
  align-items: center;
You can check on codepen: Codepen

If you have any other approach please share.

Wednesday, August 24, 2016

Block level scoping in JavaScript

Block level scoping in JavaScript

If you are familiar with JavaScript. If you are working as FE developer then must be aware that JavaScript has functional level scoping not block level scoping as in C family languages.

Now, from ES6 JavaScript introduces let keyword. "var" keyword is still there which will function in same manner as it is currently. Using let keyword you can declare one variable inside one block and its scope will be in that block only as block level scoping in C family languages.

For example
// using var only
function myFun(){
 var a=1;
 if(a>0){
  var b=2;
 }
 console.log(b);
}

myFun(); // 2

// using let keyword
function myFun2(){
 var a=1;
 if(a>0){
  let b=2;
 }
 console.log(b);
}

myFun2(); // Uncaught ReferenceError: b is not defined

In above example second function myFun2 gives error as let has block level scoping only and it is declared inside if block so it is not available out side if block.


Saturday, August 6, 2016

Clone/Copy JavaScript Object

Creating an Object copy from an object was not easy earlier in JavaScript (before ECMAScript 2015). Now as ECMA 2015 is available we can use Object.assign to create copy of an object.

Create clone/copy of an object before ECMAScript 2015

 var obj1 = {a:1,b:2}, obj2;
 // one simple way is to stringify and then use
 obj2 = JSON.parse(JSON.stringify(obj1));
 console.log(obj2); // {a:1,b:2} 

Clone/Copy after ECMAScript 2015

Now ECMAScript 2015 provided assign method in Object so that we can create clone/copy of an object. For method is available chrome 45 onwards.

 var obj1 = {a:1,b:2}, obj2;
 obj2 = Object.assign({}, obj1);
 console.log(obj2); // {a:1,b:2}
 
 // another way to use same method (assign)
 var obj3={x:1, y:2}, obj4 = {};
 Object.assign(obj4,obj3);
 console.log(obj4);

Friday, July 15, 2016

Create Message in Hindi by typing in Hinglish

If you want to write something in Hindi but want to type in hinglish then this is the correct place just write in English (Hinglish) and when you press space english will change to Hindi. Enjoy writing.
Create your messages in hindi and spread the love
Use Ctrl + C to copy the message OR right click and copy

You can share your message with your friends or family

Wednesday, June 29, 2016

Concentration Circle

Hello Friends in this busy schedule we do not have time for doing yoga and exercise, we should do some exercise daily to keep our body and mind both healthy. Below is one concentration circle it is the exercise for sharpen the mind.

If you just focus on black center of circle with full concentration then surrounded radiant color part will disappear. Try this 2 minutes mind exercise to sharpen your mind.

Sunday, June 26, 2016

Input Validation with Styling anywhere in your site

Hello Friend, When we have input fields in our websites then many custom styling we apply or required for form validation. For example if user entered something, if user changed the value of input, is input empty. Many more depend on user actions.

Here I created one small utility which you can add in your site code and all the inputs of your project can be validated using this, without adding any extra code. Below is the code which you need to add in JavaScript.

function inputValidator(inputSelector) {
  var current_val = $(inputSelector).val();
  function onChange() {
    $(this).removeClass("dirty").addClass("pristine");
    this.updated_val = $(this).val();
    if (this.updated_val != current_val) {
      $(this).removeClass("pristine").addClass("dirty");
    }
  }
  function onFocus(){
    $(this).removeClass("untouched").addClass("touched");
  }
  $(inputSelector).on("input change", onChange);
  $(inputSelector).on("focus", onFocus);
  return true;
}

$(document).ready(function() {
  $.each($("input"), function(key, value) {
    new inputValidator(value);
  });
});

When you add above code in your javascript, then all input will have one class "untouched" by default. Class of input will change on user action, and you can apply style on input based on classes.

  • By default class is untouched
  • When you touch the input, class will change to "touched"
  • When you enter something in the input, class will change to "touched dirty"
  • When you revert you changes in the input, class will be "touched pristine"

For example, if our inputs are as shown below:

Text:

Email:

Password:

Number:

Date:

CSS code that I have written for inputs:

.name{
  display: inline-block;
  width:80px;
}
input.untouched{
  background-color: #DDF4FC;
}
input.touched{
  background-color: #6AFAFA;
}
input.touched.pristine{
  background-color: #43FF44;
}
input.touched.dirty{
  background-color: #FF4422;
}

Now if user interact with inputs, colors changes as mentioned in css style

Here is the codepen link : http://codepen.io/JitendraPal/pen/MebLoX

Thursday, May 19, 2016

Spread operator or Rest parameter or Ellipsis in JavaScript (ES6)

Spread/Rest/Ellipsis operator in JavaScript is very useful in many context. First important use of this operator is to pass indefinite number of argument in function

Operator syntax: ...name

Three dot and then a variable name

 function sum(a,b,...n){
  return a+b+n[0]+n[1];
 }
 sum(1,2,3,4); // output: 10 

This is also called rest parameter. inside function it can be used directly as array.

As we already know that arguments is already available in function to get many parameters as shown below: but actually that is not array

function fun(){
 return arguments[0] + arguments[1];
}

fun(1,2); // 3


function fun2(...n){
 console.log(arguments);
 console.log(n);
}

fun2(1,2,3); // it will print arguments object and array n.

There are other advantages of spread operator. Suppose we have 2 arrays and need to merge both

var a = [1,2,3], b = [4,5,6];
a.push(...b);
console.log(a); // [1,2,3,4,5,6]

Sunday, April 24, 2016

AngularJS advanced trick and techniques

These days AngularJS is highly recommended framework for front-end developer. Angular is really awesome framework to work with. Below are few techniques those I feel really cool features and may be these are simple and easy for you but as a fresher in angular I think these features are really good.

1. How to add multiple classes in ng-class?

Everyone knows how to add class using ng-class, its very easy. We can use ng-class to have more than one class as well

 
// single class
// multiple class
some content

Similarly we can add many classes separated by comma (,)

2. Can we have multiple conditions in ng-hide and ng-show?

Yes, we can have multiple conditions in ng-hide and ng-show.

// ng-show with multiple conditions
Some content

3. How to share methods or data between controllers?

Yes we can share data and methods between controllers using Factory or Service. Angular has service as constructor method which instantiate once on startup and we can use this service/factory in any controller within the module by injecting on controller method.

Restrict input to allow only required value (jQuery plugin for input type validation)

HTML5 provides many validation on input, but still few we need to implement by our self. For example, if we need one input for price then we should allow users to enter only float values. I created one small plugin using jQuery, it is very easy to use.

To create one input with only price value then just include attribute "only-price"


To create one input with only number (contact) value then just include attribute "only-number"


Here is the codepen: http://codepen.io/JitendraPal/pen/JXBqXj

Saturday, April 2, 2016

Git Hub configuration All About

Hello Friend, Most of the time when I am working with git hub. I forgot few commands. To help myself I am writing this post, and its my pleasure if this post helps other as well.

Below are commands those are self explanatory:

  1. To clone your branch in local

    $ git clone [your git repository url]
  2. Clone specific branch in local

    $ git clone [your git repository url] -b [branch name]
  3. OR
    $ git clone -b [branch name] [your git repository url]
  4. After cloning your branch go to that branch to check branch status or perform any git operations, below command will show you current branch

    $ git branch
  5. Checkout specific branch from git

    $ git checkout [branch1]
  6. Merge branch2 into branch1

    $ git merge [branch2]
  7. Stash your changes before pull

    $ git stash
  8. Pull latest changes from current branch

    $ git pull
  9. Get stashed changes back into local

    $ git stash apply
  10. Add all your changes

    $ git add -A
  11. Add specific files

    $ git add [/file path] [/another file path] [..etc]
  12. Commit your changes with message

    $ git commit -m "[your message]"
  13. Push your committed changes in the branch

    $ git push origin [branch name]
  14. Pull latest changes

    $ git pull --rebase
  15. Create new branch and checkout in this branch

    $ git checkout -b [your new branch name]
  16. Push the branch on git hub

    $ git push origin [your new branch name]

Friday, February 12, 2016

How to use factory or service in AngularJS

As a beginner in AngularJS it is very important to understand Service/Factory. AngularJS provides many services itself and we can use those services whenever we required, just by injecting in controller/module.

when we need to share some functions or some data we can create our own service/factory and have all the methods/data in that. To use these service's method or data we just need to inject that service and use.

For example if we want to share one data object in 2 different controller, say controller1 and controller2. We Create one service dataService

 var app = angular.module("app",[]);
 app.factory('dataService',['$http', function($http){
  var dataService = {};
  dataService.method1 = function(){
    console.log("method1 executing");
  };
  dataService.method2 = function(){
    console.log("method2 executing");
  };
  return dataService;
 }]);
 

Now we can use this service in any controller by injecting

app.controller('controller1',['dataService','$scope' function(dataService,$scope){
 dataService.method1();  // it will print 'method1 executing'
 dataService.method2();  // it will print 'method2 executing'
}]);
app.controller('controller2',['dataService','$scope' function(dataService,$scope){
 dataService.method1();  // it will print 'method1 executing'
 dataService.method2();  // it will print 'method2 executing'
}]);

In same way we can create service also instead of factory, the only difference between factory and service is that, service is constructor function while in factory we need to return the object. For same objective we can create service as follows:

 app.service('dataService',['$http', function($http){
  this.method1 = function(){
    console.log("method1 executing");
  };
  this.method2 = function(){
    console.log("method2 executing");
  };
 }]);

Sunday, January 31, 2016

How to add AngularJS in rails application, error: rails:undefined method `register_engine' for nil:NilClass (NoMethodError)

Adding AngularJS in rails application is very easy. Just add angular-rails-templates in gem file as shown below:
  gem 'bower-rails'
  gem 'angular-rails-templates'

But some times it gives error and does not run as expected. This issue is might be because of sprocket version. We have to mention sprocket version in gem file

  gem 'sprockets', '2.12.3'

After adding sprocket in the gem file, update bundle

  $ bundle update
  $ rails g bower_rails:initialize json

Now open bower.json file and add angular in the library dependencies

{
  "lib": {
    "name": "bower-rails generated lib assets",
    "dependencies": {
      "angular": "latest",
      "angular-route": "latest"
    }
  },
  "vendor": {
    "name": "bower-rails generated vendor assets",
    "dependencies": {
    }
  }
}

One more important thing REMOVE turbolinks from gem file and from application.js file, and add angular in application.js file

//= require angular
//= require angular-route
//= require angular-rails-templates

For the reference below is my gem file

source 'https://rubygems.org'

gem 'sprockets', '2.12.3'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.4'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

gem 'angular-rails-templates'

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'

  gem 'bower-rails'

end


group :development do
  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'

  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
end

Thursday, October 1, 2015

how to align elements in a row with equal space around

Hello friend,
For any front-end developer aligning elements in a row with equal space is very common problem. This problem can be solved very easily if site is non responsive. But it will little difficult if your site is responsive. One method to solve this problem is use some calculation with margin/padding to properly align elements with spaces in between. Or one solution can be write huge media query for spaces in all different window widths. For example to create menu bar and keep it align horizontally for all small devices as well.

CSS3 provides one very good feature to solve such problems easily, that is- display: flex

Consider below code to display divs with text class as headers link
 
Item1
Item2
Item3
Item4
Item5

Apply this CSS code to display headers properly in all window widths

#container{
    display:flex;
    justify-content: space-around;
}
.delimeter{
    border-left:1px solid red;
}
Result of this code will be as:
You can check this link to see the example: https://jsfiddle.net/JitendraPal/6fdLpLxd/

To work properly in all browsers use prefixed appropriately as shown below:

          display: flex;
          display: -moz-flex;
          display: -ms-flex;
          display: -webkit-flex;
          justify-content: space-around;
          -ms-justify-content: space-around;
          -webkit-justify-content: space-around;
          -moz-justify-content: space-around;

Sunday, August 30, 2015

JavaScript amazing facts

JavaScript is the most used language of this time on the planet earth.

  1. Everything is object in JavaScript, even function is also a first class object.
    • You can pass function object as an argument to a function
    • Function object can be returned from a function
    • Function may assigned to a variable
    • Function May be stored in an object or array
  2. JavaScript programs use Unicode character set (UTF-16) which is super-set of ASCII and Latin-1 and supports virtually every written language currently used on the planet
  3. NULL is an object in JavaScript
  4. NaN is a number, if we say typeof NaN, then it would be number
  5. typeof Infinity is a number
  6. Function can execute themselves. We call them self executing function. This is very important concept/feature which is used at many places
  7. using typeof we can not get if any variable is of type array. So how we can determine if a variable is of type array?
    var ar = [1,2,3];
    ar instanceof Array // this will return true because ar is of type array
    
    There is one more way to get the type of any variable:
    var ar = [1,2,3];
    Object.prototype.toString.call(ar); // "[object Array]"
    

Thursday, July 9, 2015

One good way to declare Global Variables in JavaScript

In JavaScript, declaring one variable as global is very easy, some one can say that if you just write a=3; "a" will be global, and if you write var a=3; then a is local (It is not at all true..!).

Let me explain first scope in JavaScript, JavaScript is functional level scoping language (not block level as C family languages) and any variable declared inside a function is not available to outer function (parent function).

Any variable directly declared or initialized outside (not inside any function) will be global variable

        var myVar = 3; // global variable 
        function myFun(){
            var funVar = 33; // this variable is not global, scope of this variable is within "myFun" function
        }
    
Below image explain it better on console, window is the root object in a browser, so if we declare any variable outside then it comes directly under window object:

In above snapshot window.funVar is undefined because this variable is not available globally because it is inside function "myFun".

Main aim of this post is to find out best way to keep all the global variables if required in an application. One question will come in mind that, why we should avoid global variables in an application??

Normally in an application there are many JS files and if any 2 or more files have same variable name and those are global then application will be messed up and it will really hard to find the issue sometime. So we should always avoid using global variables.

Before ECMA Script 5 strict mode, there were no way to check that inside function we have declared global variable by mistake. But now using "use strict" we can find out such issues.

We can create a class to have all the global variables inside that, and using getter nd setter method we can easily get and set the variables.

// how to use Global variables in JS
    var GlobalVariables = function () {
        // keep all the variables in this GlobalVars object
        var GlobalVars = {
            var1: 123,
            var2: 456,
            var3: "values"
        }
        this.get = function (name) {
            return GlobalVars[name];
        };
        this.set = function (name, value) {
            GlobalVars[name] = value;
        };
    };

    // craeate an object to fetch all the varibales and you can set also using get and set methods
    var global = new GlobalVariables();
Usage of above global object is as shown in console below: