Thursday, April 23, 2015

Interesting examples of Javascript

I am learning Node.js recently and this is the first time I writing Javascript code. Here are some interesting examples I found when I am learning.

1. Hoisting
var foo = 1;
function bar(){
    if(!foo){
        var foo = 10;
    }
    
   alert(foo);
}
bar();
//answer: 10
2. Hoisting
function test(){
   foo(); // TypeError "foo is not a function"
   bar(); // "this will run!"
   var foo = function () { // function expression assigned to local variable 'foo'
      alert("this won't run!");
   }
   function bar() { // function declaration, given the name 'bar'
      alert("this will run!");
   }
}
test();
3. Closure
for (var i = 0; i < 5; i++){
   setTimeout(function () {
   console.log(i);
   }, 5);
}
//will print five 5

for (var i = 0; i < 5; i++) {
   (function (idx) {
      setTimeout(function () {
         console.log(idx);
      }, 5);
   })(i);
}
//will print 1,2,3,4,5
4. Scoping
(function(){
   var a = b = 5;
})();
console.log(b)
//output: 5, b is global
5. this
var fullname='John Doe';
var obj = {
   fullname: 'Colin Ihrig',
   prop: {
      fullname: 'Aurelio',
      getFullName: function(){
         return this.fullname;
      }
   }
};
console.log(obj.prop.getFullName());
var test = obj.prop.getFullName;
console.log(test());
console.log(test.call(obj.prop));
//output: 
//'Aurelio'
//'John Doe'
//'Aurelio'
Reference:
5-typical-javascript-interview-exercises
JavaScript-Scoping-and-Hoisting
alsotang node lessons