Hoisting in javascript

Hoisting is JavaScript’s default behavior of moving declarations to the top.

function hoistTest(){
   x = 5;            // Assign "5" to x - now x is a global variable
   console.log( x ); // returns "5"
   var x;            // Declare x - now x is a local variable
}
hoistTest();
console.log( x ); // returns undefined

In the above example we assigned value for “x” without declaring it and declared it at last of function. But once javascript runs the declaration moved to top and “x” becomes the local variable. Hence outside the function it becomes undefined. This is how the “x” declaration in hoisted.

If not declared, “x” stays as global variable.

function hoistTest(){
   x = 5;            // Assign 5 to x - now x is a global variable
   console.log( x ); // returns "5"
}
hoistTest();
console.log( x ); // returns "5"
Advertisements

HTML 5

HTML History Version Year Tim Berners-Lee invented www 1989 Tim Berners-Lee invented HTML 1991 Dave Raggett drafted HTML+ 1993 HTML Working Group defined HTML 2.0 1995 W3C Recommended HTML 3.2 1997…

Source: HTML 5

JavaScript Design Patterns

Creational Patterns   Abstract Factory Creates an instance of several families of classes   Builder Separates object construction from its representation   Factory Method Creates an instance of sev…

Source: JavaScript Design Patterns

JavaScript Cascade function

In a cascade, we can call many methods on the same object in sequence in a single statement. The trick is that the method itself should only return this. That way, each time you chain these methods…

Source: JavaScript Cascade function

Find Pangram in JS

Pangram is a sentence containing every letter of the alphabet. A simple try in js to find Pangram. DEMO

var i, alphabets = "abcdefghijklmnopqrstuvwxyz";

function isPangramFun() {
    var isPangram = true;
    var input = document.getElementById("inputTxt").value;
    for (i = 0; i < 26; i++) {
        if (input.toLowerCase().indexOf(alphabets[i]) == -1) {
            isPangram = false;
            break;
        }
    }
    alert(isPangram ? "Pangram" : "Not Pangram");
}

Number Animation using jQuery

Number is an important value that we could see in many places, Just a try to make that number look awesome. DEMO

$(function(){
  $('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 2000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
   });
});

Draw a line from x,y with a given angle and length

Draw a line from x,y with a given angle and length. DEMO Fiddle

function drawLine(x1,y1,r,theta){
    ctx.clearRect(0, 0, c.width, c.height);    
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x1 + r * Math.cos(Math.PI * theta / 180.0), y1 + r * Math.sin(Math.PI * theta / 180.0));   
    ctx.closePath();
    ctx.stroke();
  }