Primitive types in JavaScript

In every language there are variable type.In a programming language, if variables are container then data type is the type of container. type of container actually tells that what kind of stuff can be put in it. For example you don't want to put cookies in a bottle similarly you don't want to store an integer value in a variable of data type String

As its name indicates, a data type represents a type of the data which you can process using your computer program. So JavaScript also has 6 Primitive data types other than objects.

Lets Go though each of them.

  1. Undefined
    This represent the lack of existence.(Shouldn't set a variable to this).
  2. Null
    This also represent lack of existence.
  3. Boolean
    This represent a value that is true or false
  4. Number
    This is a floating point number. Normally programming languages have many types of number like int,long,double but JavaScript has only one
  5. String
    This represents a sequence of characters. single quotes ('') or double quotes ("") are used to specify strungs
  6. Symbol
    This type is used in ES6 which is the latest version of JavaScript

What is dynamic typing in JavaScript

When learning a programming language, knowing variable types that programming language supports is an important part. Taking about variable types in JavaScript there are two important thing

  • JavaScript is a dynamically typed language.
  • There are 6 primitive types in JavaScript.

What is dynamic typing

JavaScript is a language that supports dynamic typing. That means, we don't have to tell the JavaScript engine what type of data a variable holds. It figures it out while code is running.

Single variable can hold different types of values at different times of execution of code because it is all figured out during execution.

In static typing we need to specify the what type of data a variable is going to hold and we cant store other types of data in that variable
As an example, in a static typed language like java we can't store a string in a variable that is declared as a boolean.

boolean variable = "hello"; // gives error
But, in a dynamically typed language like JavaScript it can be done without errors.

var box = true;
box = "hiii";
box=3;
//no errors
This is a powerful feature of JavaScript and sometimes it can cause problems as well (If you don't have a proper understanding).

Regular Expressions (Regex) in JavaScript - Part I

Regular Expressions are used to find a specific pattern within a big glob of text. Regular expressions are also known as regex or regexp among developers.

Read this post for how regular expressions are used in JavaScript methods.

In this post series i'm trying to give you an idea about how to create an regex that matches a particular string.

Very Basic Rules 

  1. Every regular expression literal starts and ends with a forward slash ("/").  
  2. Pattern that we are trying to match goes between those slashes.
  3. After end slash "g", "i", "m" characters can be used as flags. Each letter has different purposes.

Anatomy of call back functions in JavaScript

Call back function is a pattern that heavily used in JavaScript programming. Most of beginners in JavaScript programming have no clear idea about JavaScript programming. Specially Programmers from other programming paradigms except functional programming facing difficulties in adapting this idea.

JavaScript is a functional programming language. So functions are considered as first class objects. There for we can do may things with functions that can't be done in other programming languages. 
Like,
  • Store functions in a variable.
  • Pass functions a arguments to another function. 

What is a Call back function

 A call back function is,
  • passed as an argument to another function.
  • It is invoked after some kind of event.
So basically Call back function is a function (func1) that pass to another function (func2) to be executed after finish the execution of second function (func2).

Singleton Pattern in JavaScript

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

In JavaScript this pattern restricts instantiation of an object to a single reference thus reducing its memory footprint and allowing a "delayed" initialization on an as-needed basis. This isn't too common among JavaScript projects.

Here is how a singleton pattern can be implemented with JavaScript

  1. Easiest way is using object literals
    
    var singletonObject ={
        method1:function(){
            
        },
        method2:function(){
        
        }
    }

Encapsulation : private variables in JavaScript

Encapsulation is an one of main concepts in object oriented programming. Encapsulation is the ability that an object has to forbid external access to chosen properties and methods, so that they can only be called by other methods of same object and protect from external unwanted access.

A normal code Snippet

function SecretCode(){
    secretNumber=Math.floor((Math.random() * 10) + 1);     
    
    this.getSecret=function(){
        return secretNumber;
    }
}

var secret1 = new SecretCode();
document.write("value of secret number "+secret1.secretNumber+"<br/>");

document.write("value of secret number : "+secret1.getSecret()+"<br/>");

SecretCode.prototype.getSecretCode= function(){
    return this.secretNumber;    
}

document.write("Secret number is "+secret1.getSecretCode()+"<br/>");

Simple JavaScript : Accessing properties of objects.

There are mainly two ways to access a property in JavaScript.
  • Using dot notation (.)
  • Using square bracket notation ([])
Consider an object like this.

var employee={
    name:"Antony",
    age:26
}

We can access properties of employee object in both ways.
  1. employee.name
  2. employee["name"]
But Consider a object that has non-string property names. Some times we have to use object property names with non-string types.
Ex:
var marks={
    30:"bad",
    70:"good"
}

In here we won't be able to properties with both notation. Only marks["30"] will work.

Creating objects for your design pattern in JavaScript

There are few different ways of creating objects in JavaScript and different ways of using those objects. Most of the beginners in JavaScript are confused with those different ways of handling objects.

Here is a list of few different styles mostly used by developers to create objects.
  1. Object constructor
    
    var person = new Object();
    
    person.name = "Mark",
    person.getName = function(){
      return this.name ; 
    };
    

JavaScript : Inheritance in JavaScript

JavaScript is not a class based language, So it is bit confusing for most of developers familiar with languages like Java or C#.In-order to understand how inheritance work in JavaScript you need to have a good understand about how prototype objects work in JavaScript.

Every object in JavaScript has an internal link to a object. That object is called prototype object. When we trying to access a property from a object JavaScript will first look in that object and if that property is not found next the prototype object will be searched . Refer this link for more details.

So if we want want to inherit properties from another object we can simply point prototype to that object.

How to detect scroll action using JavaScript

To fire up different actions in a web page when someone scroll on it we need to detect scroll events on the page.

Completed project can be Download from here.
In this tutorial color of a div(div with ID "maincontent") is changed when a user is scrolling the page,

Here is how it can be done.

  1. Add onscroll attribute in the element which you need to detect scroll on.
    ex:<body onscroll="bodyScroll();"></body>

  2. Declare a JavaScript variable to -1. (In this tutorial scrollTimer)

  3. Implement the bodyScroll() function
       function bodyScroll() {        
            $('#maincontent').css('background-color','lightGrey'); 
            
            if (scrollTimer != -1)
                clearTimeout(scrollTimer);

            scrollTimer = window.setTimeout("scrollFinished()", 300);
        }

  4. Implement the scrollFinished() method.
        function scrollFinished() {
           $('#maincontent').css("background","white");
        }

Note: In the project I have added extra reference to bootstrap  for easiness of making the UI.

This post shows hot do this using JQuery scroll() method.

Please add a comment if this was useful to you or you have something to add



Detecting a click on a element in DOM

As web developers some times we need to detect clicks on elements of our DOM to enhance experience with our site. Here is a one simple way we can achieve that.

In this tutorial I have demonstrated how to detect a click on a Image in side a div element.
you can find images used in this tutorial from here.

Here is the HTML for the tutorial

<!DOCTYPE html>

<html>
<head>
    <style>
        .imagegrid{
            border: 3px solid black;
            padding: 10px;
        }
        
        img{
            border: 1px solid red;
            margin: 10px;
        }
    </style>
</head>

<body>
    <h2>Image Grid</h2>
    <div class="imagegrid">
        <img src="Images/facebook.ico">
        <img src="Images/google.ico">
        <img src="Images/Linkedin-icon.png">
        <img src="Images/twitter-icon.png">
    
    </div>  
</body>    
</html>



Java Script code to detect the clicks

var myNode= document.querySelector('.imagegrid');

myNode.addEventListener("click",function(e){

  if(e.target.tagName==="IMG"){
   alert(e.target.src+" clicked");
  } 


},false); 


What happen in the script

  1. Get an element which has "imagegrid" class to myNode variable.
  2. Add an event listener to that myNode element fire up when a click happen.
  3. Alert a message if tagName of a click event (detect by event listener on myNode variable) is equal to "IMG".

In this way you can detect a click on an "img" element as well as other elements in your DOM.
In this tutorial we just alert a message with source of clicked image, but you can do what ever you want after detecting a click on an element like,

  • Taking user to another page
  • Display a larger image of the image
  • Give a hint to the user
This kind of small things give a better experience to the user of your site.


NOTE: CSS parts in the head is added to display limits of images and div with a border

How to use Array sort() method in JavaScript


If we want to sort an array using JavaScript easiest way is using sort() method in JavaScript.
By default sort() method get values as strings and sort them in alphabetical and ascending order.
This is how we use this method in JavaScript.

Using sort() method.

var names=['Jack','Eve','Ann','Jane']; 
names.sort(); 

var numbers=[22,56,3,10,6]; 
numbers.sort();

After using sort() method your result arrays will be like,

['Ann','Eve','Jack','Jane']
[10,22,3,56,6]

you will notice that integer array was not sorted correctly. That is because sort() method get values as strings and when comparing 22 is smaller than 3 because 2(first character of 22) is smaller than 3.

Using overloaded method.

To over come this problem there is overloaded method of sort() that take a compare function as a parameter.

var numbers=[22,56,3,10,6];
numbers.sort(function(a,b){return a-b}); 

After using this method your numbers array will be sorted correctly in ascending order as,
[ 3, 6, 10, 22, 56]

As compare function is used to compare integers when comparing 3 and 22,
compare function will be used as function(3,22) and return value 3-22 = -19. 3 will be identified as smaller than 22 because compare function returned a minus value.

If function(a,b){return a-b} is used as compare function integer array will be sorted in descending order.
feel free to comment below if you have any questions or something to add.