How to achieve static variable in javascript

2 Ways :

1) Make use of the fact that functions are objects and can have properties
(Even using “this” instead of uniqueID inside the function will do)

function uniqueID() {
    // Check to see if the counter has been initialized
    if ( typeof uniqueID.counter == 'undefined' ) {
        // It has not... perform the initialization
        uniqueID.counter = 0;
    }
    uniqueID.counter++;
    return (uniqueID.counter);
}

console.log(uniqueID());
console.log(uniqueID());


2) Using closure and function expressions

var uniqueID = (function() {
   var id = 0; // This is the private persistent value
   // The outer function returns a nested function that has access
   // to the persistent value.  It is this nested function we're storing
   // in the variable uniqueID above.
   return function() { return id++; };  // Return and increment
})(); // Invoke the outer function after defining it.

console.log(uniqueID());
console.log(uniqueID());


Javascript Questions Set3

1) What is event delegation?

Event delegation is when you bind an event listener to a parent (or ancestor) element rather than the element(s) you are particularly interested in. When the event is triggered you can check the event target to make sure it was actually the triggered on the element of interest.

Capturing and bubbling allow us to implement one of most powerful event handling patterns called event delegation. The idea is that if we have a lot of elements handled in a similar way, then instead of assigning a handler to each of them – we put a single handler on their common ancestor. In the handler we get event.target, see where the event actually happened and handle it.

Event bubbling provides the foundation for event delegation in browsers. Now you can bind an event handler to a single parent element, and that handler will get executed whenever the event occurs on any of its child nodes (and any of their children in turn). This is event delegation. Here’s an example of it in practice:

Let’s say that we have a parent UL element with several child elements:

    • Item 1

 

    • Item 2

 

    • Item 3

 

Let’s also say that something needs to happen when each child element is clicked. You could add a separate event listener to each individual LI element, but what if LI elements are frequently added and removed from the list? Adding and removing event listeners would be a nightmare, especially if addition and removal code is in different places within your app. The better solution is to add an event listener to the parent UL element. But if you add the event listener to the parent, how will you know which element was clicked?

Simple: when the event bubbles up to the UL element, you check the event object’s target property to gain a reference to the actual clicked node. Here’s a very basic JavaScript snippet which illustrates event delegation:

// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a list item
if(e.target && e.target.nodeName == "LI") {
    // List item found!  Output the ID!
    console.log("List item ", e.target.id.replace("post-"), " was clicked!");
       }
 });

2) What are the 3 ways to bind an event to an element ?
1) HTML Event Handlers
< input type=”text” id=”username” onblur=”checkUserName()”>
Not recommended any more. Better to separate JS and HTML

2) DOM Event Handlers
function checkUserName() { blah } ;
var el = document.getElementById(‘username’);
el.onblur = checkUserName;

Disadvantage is that you can only attach one function to each event Handler.

3) DOM Event Listeners
Advantage : They can deal with more than one function at a time.
var el = document.getElementById(‘username’);
el.addEventListener(‘blur’, checkUserName, false);

3) How do you convert arguments into an actual array. arguments are pseudo array in js.

var args = Array.prototype.slice.call(arguments);

4) How would you simulate Function.prototype.bind in older browser that don’t support it

Function.prototype.bind = Function.prototype.bind || function(context){
  var self = this;

  return function(){
    return self.apply(context, arguments);
  };
}

4) How to pass parameters to callback functions?

By default you cannot pass arguments to a callback function. For example:

function callback() {
  console.log('Hi human');
}

document.getElementById('someelem').addEventListener('click', callback);

But using closure concept you can do so :

function callback(a, b) {
  return function() {
    console.log('sum = ', (a+b));
  }
}

var x = 1, y = 2;
document.getElementById('someelem').addEventListener('click', callback(x, y));

5)  attribute vs. property:

https://lucybain.com/blog/2014/attribute-vs-property/

6) Explain the difference between: function Person(){}, var person = Person(), and var person = new Person()

First is a function declaration, second is a function expression, third is a function constructor

https://www.quora.com/In-Javascript-what-is-the-difference-between-function-Person-var-person-Person-var-person-new-Person

Function overloading in Javascript

Unique things about arguments in functions in Javascript:

1) You can pass any number of parameters to a function without causing an error.
2) You can also pass in no arguments but still make use of arguments inside the function (through arguments array)
3) you have access to arguments[0], arguments[1] etc in a function
4) arguments.length will give you number of parameters passed in. This is the way you can achieve function overloading. Based on number of parameters you do one thing or the other.
5) If you define multiple functions with same name, the one which is defined last will override all others.

Identifying Primitive and Reference Types in Javascript

5 Primitive Types: Number, Boolean, String, Null, Undefined

typeof “abc” => string
typeof “true” => boolean
typeof will work for mostly all of above except null.
typeof null will return “object”.
So to verify “null” just compare to null. (value == null)

6 Reference Types: Function, Object, Array, Date, Error, RegExp

typeof object will be “object”
typeof function will be “function”

for all the rest use instanceof to identity

items instanceof Array

Note that items instanceof Object will also return true since instanceof can identity inherited types.

For Array, if you are using frames and communicating values between frames then instanceof may not provide accurate results if you are checking instanceof. Its recommended to use Array.isArray(items) in that case.

Example of Associative Array in Javascript

Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence “The quick brown fox jumps over the lazy dog” repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.)

After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams.

Given a sentence , tell Roy if it is a pangram or not.

E.g: We promptly judged antique ivory buckles for the next prize

function processData(input) {
    //Enter your code here
    var inpArr = input.split("");
    var uinput = input.toUpperCase();
    var freqObj = {};
    for (var a=65; a <= 90 ; a++) {
        var s = String.fromCharCode(a);
        freqObj[s] = 0;  // associative array as an object
    }
    
    for (var i = 0; i < uinput.length ; i++) {
        
        var char = uinput[i];
        //if (char in freqObj) {
        if ((char in freqObj) && (freqObj.hasOwnProperty(char)) ) {
            freqObj[char] = 1;
        } 
        
    }
    
    var okeys = Object.keys(freqObj);
    var sum = 0;
    for (var k = 0; k < okeys.length; k++) {
        if (freqObj.hasOwnProperty(okeys[k])) {
            sum += freqObj[okeys[k]];
        }
    }
    
    if (sum == 26) {
        console.log("pangram");
    } else {
        console.log("not pangram");
    }
    
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Way to create an object in Javascript

1) // object constructor

var mango =  new Object ();
mango.color = "yellow";
mango.shape= "round";
mango.sweetness = 8;

mango.howSweetAmI = function () {
console.log("Hmm Hmm Good");
}
      

2) // object literal

      // This is an object with 4 items, again using object literal
var mango = {
color: "yellow",
shape: "round",
sweetness: 8,

howSweetAmI: function () {
console.log("Hmm Hmm Good");
}
}
   

3) // constructor pattern

function Fruit (theColor, theSweetness, theFruitName, theNativeToLand) {

    this.color = theColor;
    this.sweetness = theSweetness;
    this.fruitName = theFruitName;
    this.nativeToLand = theNativeToLand;

    this.showName = function () {
        console.log("This is a " + this.fruitName);
    }

    this.nativeTo = function () {
    this.nativeToLand.forEach(function (eachCountry)  {
       console.log("Grown in:" + eachCountry);
        });
    }


}

var mangoFruit = new Fruit ("Yellow", 8, "Mango", ["South America", "Central America", "West Africa"]);
   

4) // using prototype pattern

function Fruit () {

}

Fruit.prototype.color = "Yellow";
Fruit.prototype.sweetness = 7;
Fruit.prototype.fruitName = "Generic Fruit";
Fruit.prototype.nativeToLand = "USA";

Fruit.prototype.showName = function () {
console.log("This is a " + this.fruitName);
}

Fruit.prototype.nativeTo = function () {
            console.log("Grown in:" + this.nativeToLand);
}

var mangoFruit = new Fruit ();
   

5) // using Object.create()

var superHuman = {
    usePower: function () {
        console.log(this.superPower + "!");
    }
};

var banshee = Object.create(superHuman, {
    name: { value: "Silver Banshee" },
    superPower: { value: "sonic wail" }
});

// Outputs: "sonic wail!"
banshee.usePower();