Skip navigation

Category Archives: Javascript

JavaScript keeps giving shock to me even after using, learning since so long years! I just came to know that hasOwnProperty method is not guarded by the JavaScript language. Users can override it. Below code demonstrates how to override, consequences and work around.

var foo = {
    // overriding foo's default hasOwnProperty method
    hasOwnProperty: function() {
        return false;
    bar: 'rajakvk'

foo.hasOwnProperty('bar'); // false always

// using hasOwnProperty of of object and setting this to foo
({}), 'bar'); // true

// or use hasOwnProperty from the 
// Object prototype for this purpose, 'bar'); // true

It is common in forms, to get user inputs for numerical calculations later like house rent allowance for salary calculation. In such scenarios, the value returned is string which if we add result in concatenation. To avoid this mistake adding toInt method to string object directly will be handy.

 * adding toInt method to String object
 * author rajakvk <rajakvk at gmail dot com>
if(!String.toInt) {
   * Returns integer value if a string value is passed.
   * @name toInt
   * @methodOf String
   * @param {*} none 
   * @returns {Number}
  String.prototype.toInt = function() {
     return parseInt(this, 10);
// Usage
// $('#hra').val().toInt();
// typeof $('#hra').val();  // string
// typeof $('#hra').val().toInt();  // number

Note: This method converts string to Integer discarding decimal places.

typeof method in JavaScript returns wrong value if you pass an array as parameter. To fix this, we can add isArray method to JavaScript’s native Array object. In future, if browser includes one such method, the below code will not break as it will use browser’s native code in that case.

This will be handy fix for typeof known bug for Arrays.

 * @author rajakvk <rajakvk(at)>
if (!Array.isArray) {
     * Returns true if an object is an array, false if it is not.
     * @name isArray
     * @methodOf Array
     * @param {*} value 
     * @returns {Boolean}
    Array.isArray  = function (value) {
        return === '[object Array]';