Enumerable in JavaScript

Object.defineProperty(obj, 'answer', {
  value: 42,
  writable: true,
  enumerable: true,
  configurable: true
});

The property enumerable specifies a specific property of an object to be available for operations.

The default properties of inbuilt objects in JavaScript are not enumerable that means they can not be listed by using for in loop.

When you try to get the properties of an object, the default properties are not being listed because of enumerable false assigned to them. These properties are not listed when you try to get the properties of that object.

var o = {};
var a = [];
o.prop = 'is enumerable';
a[0] = 'is enumerable';

o.propertyIsEnumerable('prop');   // returns true
a.propertyIsEnumerable(0);        // returns true
a.propertyIsEnumerable('length');   // returns false

One can check if the property is enumerable by using propertyIsEnumerable. The length is a default property of an array object. But it is not listed when you try to get the keys/properties in an array.

Advertisements

Array.fill method in JavaScript

We are used to create arrays with loop.

A better way to create a long array with around 10,000,000 entries is to use the fill method which is fast and reliable.

E.g.

Var a = new Array(10000000);
a.fill(“satya”);
console.log(a);

Fill can take two extra parameters as well.

a.fill(“satya”, 0, 100);
this will fill the array starting from 0th index till 100th index.

Phaser bow and arrow game, trajectory

The most popular phaser framework is very helpful to create html5 and javascript games.

I have come up with a simple trajectory code for a bow and arrow game.


var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', {
  preload: preload,
  create: create,
  update: update
});

var bow, bag, arrow, angle;
var score=0;
var x;
var y;
var oldx, oldy;
var xVel;  // calculate this based on distance
var yVel;  // 
var g = 0.25;
var arrowCreated = false;
var shot = false;

function preload() {
  game.load.image('bag', bagURI);
  game.load.image('bow', bowURI);
  game.load.image('arrow', arrowURI);

}

function create() {
  game.world.setBounds(0, 0, 800, 600);
  bow = game.add.sprite(100, 250, 'bow');
  bow.anchor.setTo(0.5);
  
  bag = game.add.sprite(650,300,'bag');
  bag.anchor.setTo(0.5);
  
  
  arrow = game.add.sprite(bow.x, bow.y, 'arrow');
  arrow.anchor.setTo(0.5);
  arrow.scale.setTo(0.5);
  arrow.angle = bow.angle;
  x = oldx = arrow.x;
  y = oldy = arrow.y;
  //game.input.onDown.add(createArrow, this);
  game.input.onUp.add(shootArrow, this);
}

function update() {
  //console.log(shot);
  if (!shot) {
    angle = Math.atan2(game.input.mousePointer.x - bow.x, -(game.input.mousePointer.y - bow.y)) * (180 / Math.PI) - 180;
    bow.angle = arrow.angle = angle;
    
  } else {
    
    //console.log("x",x,"y",y,"xVel",xVel,"yVel",yVel,"oldx",oldx,"oldy",oldy);
    
    x += xVel;
    y += yVel;
    yVel += g;

    arrow.x = x;
    arrow.y = y;
    
    
    arrowAngle = Math.atan2(x-oldx, -(y-oldy)) * (180 / Math.PI);
    arrow.angle = arrowAngle;
    /* need to write new arrow code */
    
     oldx = x;
     oldy = y;
    
    
    if(arrow.y>600) {
      resetArrow();
    }
    
    
    var intersects = Phaser.Rectangle.intersection(arrow, bag);
    if(intersects.width>0) {
      //console.log(intersects.width);
      resetArrow();
      score=score+45;
      console.log(score);
    }
    
  }
}
function resetArrow() {
  shot = false;
  arrow.x=bow.x;
  arrow.y=bow.y;

  x=oldx=arrow.x;
  y=oldy=arrow.y;
}
function createArrow() {
  arrowCreated = true;
}

function shootArrow() {
  if(!shot) {
    shot = true;
    xVel = - (game.input.mousePointer.x-bow.x)/6;
    yVel = - (game.input.mousePointer.y-bow.y)/6;
  }
}

 

How to use Namespace in JavaScript

In JavaScript there is no concept of namespace. But we can create an object and assign the same to window. Then we write all our code inside the object.

That way, the global scope is not polluted.

Normally we use the application name as our namespace object.

There are few different ways to create namespace in JavaScript.

if (Foo == null || typeof(Foo) != "object") { var Foo = new Object();}

The above syntax does not take any dependencies. It creates a global object and that object is being used to write code.

(function( skillet, $) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = "Bacon Strips";

    //Public Method
    skillet.fry = function() {
        // can return a private variable value
    };

    //Private Method
    function addItem( item ) {
        // not accessible out side the namespace object
    }
}( window.skillet = window.skillet || {}, jQuery ));

The above syntax has the full feature of a namespace.

var app = new function() {
    var privateFunction = function() {    };
    this.publicFunction = function() {    };
};

The above is with functional programming concept.

var app = app = app || {};
app.Foo = { "alert" : "test"};
app.Bar = function(arg) 
{
    alert(arg);
};
app.Bar("Hey");
with(app) {
   Bar(Foo.alert);
}

The above is empty object creation style and later you assign properties and methods.

The above syntax will give you access to the namespace object from any other file in the application without any issues in all the browsers.

In Modular pattern of development, one can use a global namespace as well as child namespaces like below.

namespace = window.namespace || {};
namespace.module1 = namespace.module1 || {};
namespace.module2 = namespace.module2 || {};

later you assign private and public methods as well as properties to the modules.

 

Singleton Design Pattern in JavaScript

var Singleton = (function () {
var instance;

function createInstance() {
   var object = {"name":"I am the instance"};
   return object;
}

return {
   getInstance: function () {
      if (!instance) {
         instance = createInstance();
      }
      return instance;
   }
};
})();


var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();

alert("Same instance? " + (instance1 === instance2));

In singleton design pattern, we create a single instance of any object. Duplicate instances are being restricted. This is useful to handle objects like timer.

Singleton class is a self executable function assigned to a variable.

It has an instance variable, a create instance method and a getInstance method inside it.

It returns the instance from inside getInstance method. If the instance is already available it returns the same otherwise it calls the createInstance method.

createInstance method returns an object.

To create an instance from the object, user variable name.getInstance() method.

How to add a new function to an existing javascript object

Javascript allows us to extend any exiting objects by using prototype.

String extend

String.prototype.reverse = function() {
return this.split(“”).reverse().join(“”);
}

var s = “satya”;
console.log(s.reverse());

 

Array extend

Array.prototype.first = function() {
return this[0];
}
console.log([1,2,3,4,5].first());

 

Object extend

Object.prototype.keys = function() {
var keys = [];
for(var key in this) {
keys.push(key);
}
return keys;
}

var obj = {“name” : “Satya”, “age” : “34”};

console.log(obj.keys());

Secrets of JavaScript

  1. Function parameters can be replaced by arguments object.Arguments object is not an array, but you can convert it to array if needed.It has length property though.var arr = Array.prototype.slice.call(arguments);
  2. If you need keys to access inside arguments, use a JSON object as function argument.
  3. You can store a function in a variable and can invoke when you need it.
  4. An object can have private and public methods like below
    function Obj(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    
        // A private method only visible from within this constructor
        function calcFullName() {
           return firstName + " " + lastName;    
        }
    
        // A public method available to everyone
        this.returnString = function () {
            alert(calcFullName());
        }
    }
    
    //Usage:
    var obj = new Obj("Bob", "Loblaw");
    obj.sayHello();
    
    // This fails since the method is not visible from this scope
    alert(obj.calcFullName());
    
    
  5. Function expressions can have properties
    var fn = function() { };
    fn.name=”myFunc”;
  6. Self invoking functions are useful
    (function(){})();
    (function(){}());   Both are same
  7. Checking is a variable is an Array
    Array.isArray(var);
  8. Javascript object property names can be stored into a variable
    obj = {a:”satya”};
    var prop = “a”;
    console.log(obj.prop , obj[prop]);
  9. Functions are objects in javascripts. So you can assign a property to a function
    var fn = function(){};
    fn.prop=”satya”;
    fn.sayName=function(){ return fn.prop; };
    console.log(fn.sayName());
  10. Remove a property from an object
    delete obj.propName;
  11. Closures
    var getCode = (function(){
      var secureCode = "0]Eal(eh&2";    // A code we do not want outsiders to be able to modify...
      
      return function () {
        return secureCode;
      };
    })();
    
    getCode();    // Returns the secureCode
  12. When to use closures inside loops
    var arr=[];
    for(var a=0; a<5; a++){
    arr[a]=function() {
    console.log(a);
    }
    }
    arr[3]()       //  returns    5Solution is a closure inside the loop

    var arr = [];
    
    for (var i = 0; i < 5; i++) {
        arr[i] = (function(index) {
            return function() {
                console.log("My value: " + index);
            };
        }(i));
    }
    arr[3]();   // this will return 3
  13. What is a function statement and a function expression?
    function name() {};  this is a function statement
    var name=function(){}; this is a function expression
    var name=function n() {}; this is a named function expression // n can be used only inside the functionvar fact = function factorial(n) {
    if (n <= 1)
    return 1;
    return n * factorial(n – 1);  // this is a recursive function call
    };
    fact(3);
  14. Print a function as a string
    function foo(){return 1;};
    String(foo);
  15. Arrow functions example
    var a = function(b) { return b*b };
    Can be written as
    var a = b=> b*b;
    a(5)     //  output will be 25
  16. Array filters and its usesa. Return a result array with even numbersvar a=[1,2,3,4,5,6,7,8,9,10];
    var result = a.filter(function(val, index, array) {
    return val %2 == 0;
    },this);
    console.log(result);b. Return unique elements

    var a=[1,2,3,3,5,3,7,4,8,8];
    var result = a.filter(function(val, index, array) {
    return array.indexOf(val) == index;
    },this);
    console.log(result);

  17. Named Functions and Variables are hoisted automatically.
    Function expressions are not being hoisted.
    Only declaration of a variable is hoisted and not the value.
  18. Instead of try catch, use winodw.onerror event if try catch can be removedwindow.onerror = function(msg, url, line) {
    alert(“Message: “+msg+”\nURL: “+url+”\nLine: “+line);
    }
  19. JavaScript event delegation

    <table onclick=”editCell(event)”>
    <tr>
    <td>sample 1</td>
    <td>sample 2</td>
    <td>sample 3</td>
    <td>sample 4</td>
    </tr>
    </table>

    function editCell(e) {
    var target = e.target;
    alert(target.textContent);
    }

    tr > td {
    border:1px solid red;
    cell-spacing: 0;
    cell-padding: 0;
    padding:10px;
    }