Skip navigation

Tag Archives: Javascript


Pass by value and pass by reference is age old concept. It is working similar way in JavaScript too. If you like to see some code so that you can understand better. Keep reading.

Brief theory before jump into code. JavaScript primitive types (string, number, boolean, null and undefined) are passed by value. Whereas non-primitive types (objects, arrays, functions, etc.) are passed by reference.

// Primitive types: Immutable by default
let x = 5
let y = x
y = 10
console.log(x) // output 5
console.log(y) // output 10

// Non-primitive types: Mutable
let animal = {
    name: 'Rat'
}
let anotherAnimal = animal
anotherAnimal.name = 'Horse'
console.log(animal) // {name: "Horse"}
console.log(anotherAnimal) // {name: "Horse"}
console.log(animal === anotherAnimal) // true

This knowledge might be useful while learning react.js, redux architecture.

Advertisements

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.


Problem:
JavaScript can be loaded dynamically on the fly to improve the performance of the page. Basically it is used as lazy loading without blocking other important content of the page.

Here is the code snippet

//
//
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", "myscript.js")
if (typeof fileref!="undefined") document.getElementsByTagName("head")[0].appendChild(fileref)
//
//

One issue with this approach is that you can’t see myscript.js in chrome’s sources tab if you want to debug.

Solution:
Place a comment at the end of the script like below
//@ sourceURL=myscript.js

Reference:
https://developers.google.com/chrome-developer-tools/docs/javascript-debugging#source-maps

Hope this helps.