No announcement yet.

Top Javascript Secrets

  • Filter
  • Time
  • Show
Clear All
new posts

  • Top Javascript Secrets

    Top Javascript Secrets:

    No. 1: Closures

    No. 2: Higher-order functions
    No. 3: Invoking functions
    No. 4: What’s this?
    No. 5: Protecting the global scope
    No. 6: Inheritance
    No. 7: Void operator
    No. 8: Class constructor
    No. 9: IIFE
    Comma operator

    No. 1: Closures:

    A closure in JavaScript gives function access to its parent’s scope:

    function a(x,y) {
       function b() {
          return x+y;

    No. 2: Higher-order functions

    functions are first-class members. They can be passed around like any other value. Methods on the function prototype, such as call and bind, are both higher-order functions. Techniques such as currying and memoization can both be expressed as higher-order functions.

    No. 3: Invoking functions

    After understanding the most common way to invoke a function (using the parentheses operator), it’s time to learn how to use call and apply. The benefit of using call/apply over the parentheses operator is that you can specify the context in which the function will execute (the value of this).

    function bind(func, context){
    return function(){
    func.apply(context, Array.prototype.slice.apply(arguments));

    No. 4: What’s this?

    When not using call/apply or bind, the this value will always refer to the global object, except in the following instances:
    1. The function in question was called with the new operator, in which case this points to a new object being constructed.
    2. The function in question is a member of an object, in which case this points to the object.
    Rule 2 should be disregarded whenever the function involved is being called asynchronously, such as in a click handler or setTimeout.

    No. 5: Protecting the global scope:

    Minimizing the use of the global scope is a defensive technique that helps eliminate interference and save you hours of debugging time. Chances are you can’t eliminate storing variables globally, but you can minimize your footprint by using techniques like namespacing:

    // **Namespacing**
    // The global footprint is a single object containing //
    all other references needed.
    var MyApp = {}; = 42;
    MyApp.utils = {
    validate: function(){
    //do work

Related Topics