Powered by Blogger.

JavaScript CheatSheet


Objects

    Delete: The only way to remove a property from an object is to use the delete operator; setting the property to undefined or null only removes the value associated with the property, but not the key.

    Prototype:

        Simply using Bar.prototype = Foo.prototype will result in both objects sharing the same prototype. Therefore, changes to either object’s prototype will affect the prototype of the other as well, which in most cases is not the desired effect.

        function Foo(){
             this.value =42;           
        }
        Foo.prototype = {
              method: function() {}
          };
          function Bar() {}

        // Set Bar’s prototype to a new instance of Foo
        Bar.prototype = new Foo();

        It is important to note that new Bar() does not create a new Foo instance, but reuses the one assigned to its prototype; thus, all  Bar instances will share the same value property.
    Prototype Lookup
        When accessing the properties of an object, JavaScript will traverse the prototype chain upwards until it finds a property with the requested name.If it reaches the top of the chain – namely Object.prototype – and still hasn’t found the specified property, it will return the value undefined instead.
    hasOwnProperty: To check whether an object has a property defined on itself and not somewhere on its prototype chain, it is necessary to use the hasOwnProperty method which all objects inherit from Object.prototype.
Functions
    Hoisting: All variable and function declartions are hosited by javaScript at the top. Top can be global if the variables and functions are defined in global scope or can be function level.
    Function Expression: var foo = function() {};
this
    Global Scope: When using this in global scope, it will simply refer to the global object.
    Calling a function: foo(); Here, this will again refer to the global object. In strict mode, the global case no longer exists. this will instead have the value of undefined in that case.
    Calling a Method: test.foo(); this will refer to test.
    Calling a Contructor: new foo();this will refer to a newly created Object.
    Explicit Setting of this: When using the call or apply methods of Function.prototype, the value of this inside the called function gets explicitly set to the first argument of the corresponding function call.

    // Code
    function foo(a, b, c) {}

    var bar = {};
    foo.apply(bar, [1, 2, 3]); // array will expand to the below
    foo.call(bar, 1, 2, 3); // results in a = 1, b = 2, c = 3

    IMPORTANT
    //Code
    Foo.method = function() {
    function test() {
        // this is set to the global object
    }
        test();
    }
    A common misconception is that this inside of test refers to Foo; while in fact, it does not.

    In order to gain access to Foo from within test, it is necessary to create a local variable inside of method that refers to Foo.

    Foo.method = function() {
        var that = this;
        function test() {
            // Use that instead of this here
        }
        test();
    }

Closure and References
    //Code
    for(var i = 0; i < 10; i++) {
    setTimeout(function() {
        console.log(i);
        }, 1000);
    } 
    The above will not output the numbers 0 through 9, but will simply print the number 10 ten times. The anonymous function keeps a reference to i. At the time console.log gets called, the for loop has already finished, and the value of i has been set to 10.
    Use Annoymous Wrapper
    //Code
    for(var i = 0; i < 10; i++) {
    (function(e) {
        setTimeout(function() {
            console.log(e);
            }, 1000);
        })(i);
    }

    Arguments
        Every function scope in JavaScript can access the special variable arguments. This variable holds a list of all the arguments that were passed to the function.
        Note: In case arguments has already been defined inside the function’s scope either via a var statement or being the name of a formal parameter, the arguments object will not be created.

    If the function that was called has no explicit return statement, then it implicitly returns the value of this – the new object.

Namespaces
    A common problem associated with having only one global namespace is the likelihood of running into problems where variable names clash. In JavaScript, this problem can easily be avoided with the help of anonymous wrappers.

Arrays:
    //Code
    var list = [1, 2, 3, 4, 5, …… 100000000];
    for(var i = 0, l = list.length; i < l; i++) {
        console.log(list[i]);
    }
    There is one extra catch in the above example, which is the caching of the length of the array via l = list.length.

Types
    Equality Operator
        JavaScript features weak typing. This means that the equality operator coerces types in order to compare them.
        “”           ==   “0”           // false
        0            ==   “”            // true
        0            ==   “0”           // true
        false        ==   “false”       // false
        false        ==   “0”           // true
        false        ==   undefined     // false
        false        ==   null          // false
        null         ==   undefined     // true
        ” \t\r\n”    ==   0             // true
    Strict Equality Operator
        The strict equality operator consists of three equal signs: ===. It works like the normal equality operator, except that strict equality operator does not perform type coercion between its operands.
        “”           ===   “0”           // false
        0            ===   “”            // false
        0            ===   “0”           // false
        false        ===   “false”       // false
        false        ===   “0”           // false
        false        ===   undefined     // false
        false        ===   null          // false
        null         ===   undefined     // false
        ” \t\r\n”    ===   0             // false
    typeof:
        Try not using typeof operator because it cant different between array, objects, custom objects
        //Code
        function is(type, obj) {
            var clas = Object.prototype.toString.call(obj).slice(8, -1);
            return obj !== undefined && obj !== null && clas === type;
        }

        is(‘String’, ‘test’); // true
        is(‘String’, new String(‘test’)); // true
    instanceof:
        The instanceof operator compares the constructors of its two operands. It is only useful when comparing custom made objects. Used on built-in types, it is nearly as useless as the typeof operator.
        //Code
        function Foo() {}
        function Bar() {}
        Bar.prototype = new Foo();

        new Bar() instanceof Bar; // true
        new Bar() instanceof Foo; // true

        // This just sets Bar.prototype to the function object Foo,
        // but not to an actual instance of Foo
        Bar.prototype = Foo;
        new Bar() instanceof Foo; // false

    undefined and null
        undefined is a type with exactly one value: undefined.
        Here are some examples of when the value undefined is returned:

            Accessing the (unmodified) global variable undefined.
            Accessing a declared but not yet initialized variable.
            Implicit returns of functions due to missing return statements.
            return statements that do not explicitly return anything.
            Lookups of non-existent properties.
            Function parameters that do not have any explicit value passed.
            Anything that has been set to the value of undefined.
            Any expression in the form of void(expression)
        Null: While undefined in the context of the JavaScript language is mostly used in the sense of a traditional null, the actual null (both a literal and a type) is more or less just another data type. It is used in some JavaScript internals (like declaring the end of the prototype chain by setting Foo.prototype = null), but in almost all cases, it can be replaced by undefined.

    setTimeout and setInterval
        setTimeout only runs the function once, setInterval – as the name suggests – will execute the function every X milliseconds, but its use is discouraged. In setTimeout the function that was passed as the first parameter will get called by the global object, which means that this inside the called function refers to the global object.

Sample Code

function foo(x){ // this is constructor function
   this.val =x;   //public variable
  var val1 = 42; //Private variable
  method = function(z){  //private method
    return z;
  };
  this.method1 = function(z){ //public methiod will be seen by the child function ‘man’ also
    this.val = z;
    return z;
  }
}
//Added a public function to foo
foo.prototype = {
  dummy : function(){  console.log(‘d’);
                     return method(‘x’);}
};
//Added a public function to foo
foo.prototype.dum = function(){
  return ‘fd’;
}

var f = new foo(29);



console.log(f.val);
// console.log(f.method(‘s’)); // Can not be called as method is private
//This will return all public methods and properties
for(var i  in f){
  console.log(i);
}

function man () {
  this.women = ‘hello’;
  this.val =22;
};

man.prototype.ho = function(){};
//man.foo1 = f;
console.log(‘ggggg’);
//man.prototype.m = f;
man.prototype = new foo();

for(var i  in new man()){
  console.log(i);
}
var m1 = new man();
console.log(m1.val);
console.log(‘ff’ + ‘ ‘ + m1.method1(100));
console.log(m1.val); //Check the o/p its sets the value of val which is with scope of man and not foo– Important
//m1.foo1 = f
//console.log(m1.dum());
//console.log(man.women);

console.log(‘fffff’);
//console.log(m1.foo1.dummy());



console.log(‘OBJECTS’);
var obj ={
  val1: 50,
  method3: function(d){
    return ‘dd’ + d;
  }
}
//here prototype is not a keyword but a property of obj
//Object.prototype.bar =1;
obj.prototype = new foo();
for(var i in obj){
  if(obj.hasOwnProperty(i))
    console.log(i);
}
console.log(obj.prototype.val);
y=100;
function foo1(){
  var x = 101;
  return x + this.obj.val1;
}

console.log(foo1());

O/P

29
“val”
“method1”
“dummy”
“dum”
“ggggg”
“women”
“val”
“method1”
“dummy”
“dum”
22
“ff 100”
100
“fffff”
“OBJECTS”
“val1”
“method3”
“prototype”
undefined
151

No comments