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.

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) {
// is the clicked element!
// If it was a list item
if( && == "LI") {
    // List item found!  Output the ID!
    console.log("List item ","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 =;

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));

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) {
    } else {
        console.log("not pangram");

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

process.stdin.on("end", function () {

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!"

Difference between Object.create() and new SomeFunction()

The object used in Object.create actually forms the prototype of the new object, where as in the new Function() form the declared properties/functions do not form the prototype.

Very simply said, new X is Object.create(X.prototype) with additionally running the constructor function. (And giving the constructor the chance to return the actual object that should be the result of the expression instead of this.)

Explain FLUX

Flux is an architectural pattern that enforces unidirectional data flow.

MVC vs Flux:
MVC did not scale well for Facebook’s huge codebase. The main problem for them was the bidirectional communication, where one change can loop back and have cascading effects across the codebase (making things very complicated to debug and understand).

How does Flux solve this? By forcing an unidirectional flow of data between a system’s components.
In general the flow inside the MVC pattern is not well defined. A lot of the bigger implementations do it very differently (e.g. Cocoa MVC vs. Ruby on Rails MVC).
Flux on the other hand is all about controlling the flow inside the app?—?and making it as simple to understand as possible.

Action –> Dispatcher –> Store –> View

Facebook found that two-way data bindings led to cascading updates, where changing one object led to another object changing, which could also trigger more updates. As applications grew, these cascading updates made it very difficult to predict what would change as the result of one user interaction. When updates can only change data within a single round, the system as a whole becomes more predictable.

Javascript Prototype Pattern

1. First, there is a prototype property that every JavaScript function has (it is empty by default), and you attach properties and methods on this prototype property when you want to implement inheritance.Note that this prototype property is not enumerable: it is not accessible in a for/in loop. The prototype property is used primarily for inheritance: you add methods and properties on a function’s prototype property to make those methods and properties available to instances of that function.

2. The second concept with prototype in JavaScript is the prototype attribute. Think of the prototype attribute as a characteristic of the object; this characteristic tells us the object’s “parent”. In simple terms: An object’s prototype attribute points to the object’s “parent”—the object it inherited its properties from. The prototype attribute is normally referred to as the prototype object

Prototype is important in JavaScript because JavaScript does not have classical inheritance based on Classes (as most object oriented languages do), and therefore all inheritance in JavaScript is made possible through the prototype property. JavaScript has a prototype-based inheritance mechanism.

function Plant () { = "Mexico";
this.isOrganic = true;

// Add the showNameAndColor method to the Plant prototype property
Plant.prototype.showNameAndColor =  function () {
console.log("I am a " + + " and my color is " + this.color);

// Add the amIOrganic method to the Plant prototype property
Plant.prototype.amIOrganic = function () {
if (this.isOrganic)
console.log("I am organic, Baby!");

function Fruit (fruitName, fruitColor) { = fruitName;
this.color = fruitColor;

// Set the Fruit's prototype to Plant's constructor, thus inheriting all of Plant.prototype methods and properties.
Fruit.prototype = new Plant ();

// Creates a new object, aBanana, with the Fruit constructor
var aBanana = new Fruit ("Banana", "Yellow");

// Here, aBanana uses the name property from the aBanana object prototype, which is Fruit.prototype:
console.log(; // Banana

// Uses the showNameAndColor method from the Fruit object prototype, which is Plant.prototype. The aBanana object inherits all the properties and methods from both the Plant and Fruit functions.
console.log(aBanana.showNameAndColor()); // I am a Banana and my color is yellow.

Prototype is also important for accessing properties and methods of objects. The prototype attribute (or prototype object) of any object is the “parent” object where the inherited properties were originally defined. if you want to access a property of an object, the search for the property begins directly on the object. If the JS runtime can’t find the property there, it then looks for the property on the object’s prototype—the object it inherited its properties from.This in essence is the prototype chain

var myFriends = {name: "Pete"};

// To find the name property below, the search will begin directly on the myFriends object and will immediately find the name property because we defined the property name on the myFriend object. This could be thought of as a prototype chain with one link.

// In this example, the search for the toString () method will also begin on the myFriends’ object, but because we never created a toString method on the myFriends object, the compiler will then search for it on the myFriends prototype (the object which it inherited its properties from).

// And since all objects created with the object literal inherits from Object.prototype, the toString method will be found on Object.prototype—see important note below for all properties inherited from Object.prototype. 

myFriends.toString ();

When it comes to inheritance, JavaScript only has one construct: objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.

var o = {a: 1};

// The newly created object o has Object.prototype as its [[Prototype]]
// o has no own property named 'hasOwnProperty'
// hasOwnProperty is an own property of Object.prototype. 
// So o inherits hasOwnProperty from Object.prototype
// Object.prototype has null as its prototype.
// o ---> Object.prototype ---> null

var a = ["yo", "whadup", "?"];

// Arrays inherit from Array.prototype 
// (which has methods like indexOf, forEach, etc.)
// The prototype chain looks like:
// a ---> Array.prototype ---> Object.prototype ---> null

function f() {
  return 2;

// Functions inherit from Function.prototype 
// (which has methods like call, bind, etc.)
// f ---> Function.prototype ---> Object.prototype ---> null

Javascript Set2 of Interview questions

1) Does Javascript support read only attributes of Object?

With any javascript interpreter that implements ECMAScript 5 you can use Object.defineProperty to define readonly properties. In loose mode the interpreter will ignore a write on the property, in strict mode it will throw an exception.

var obj = {};
Object.defineProperty( obj, "", {
  value: "",
  writable: false,
  enumerable: true,
  configurable: true

Also you can try to attempt this via private attributes simulation.

2) What does the delete operator do ?
delete is used to delete object properties. It will not delete ordinary variables defined with var. it will delete global variables though since they are actually properties of the global object.

3) What are all the types of Pop up boxes available in JavaScript?

Confirm and

4) What does the void operator do
The void operator is often used merely to obtain the undefined primitive value, usually using “void(0)” (which is equivalent to “void 0”). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value). undefined isn’t a JavaScript keyword, but a property of the global object. So it can be shawdowed sometimes.

5) What does use strict in javascript do ? What kind of errors does it catch ?
If you use “use strict” javascript will flag error for certain cases.

x = 3.14; // will cause error since x is not declared
x = {p1:10, p2:20}; // using object without declaring it
var x = 3.14; delete x; // deleting a variable will cause an error
function x(p1, p2) {}; delete x; // deleting a function will cause an error
function x(p1, p1) {}; // Duplicating parameter names will cause an error

6) What is event bubbling and event capturing ?
Event bubbling and capturing are two ways of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. The event propagation mode determines in which order the elements receive the event.

With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.

With capturing, the event is first captured by the outermost element and propagated to the inner elements.

We can use the addEventListener(type, listener, useCapture) to register event handlers for in either bubbling (default) or capturing mode. To use the capturing model pass the third argument as true

7) What is hoisting in javascript ?
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Inevitably, this means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.

Of note however, is the fact that the hoisting mechanism only moves the declaration. The assignments are left in place.

8) Make this work
duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]

var newarr = duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]

function duplicate(arr) {
   return arr.concat(arr);

9) What’s the difference between feature detection, feature inference, and using the UA string?
When you check if a certain feature exists, that’s feature detection.
if(typeof(Text) === “function”){

When you make an assumption that because one feature is present (or not) another one will also be present (or not)
if(typeof applyElement != ‘undefined’) {
// now I know I’m not in IE, I’ll just assume Text is available
text = new Text(‘Oh, how quick that fox was!’);

“UA” stands for user agent, which means the browser (and a whole lot of other stuff). Just like with feature inference, if you use the UA string you’re making an assumption about how the string will be written, what changes are likely to happen in this particular version. Using UA string to infer things is also bad.

10) What does the javascript comma operator do ?
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand. (MDC)

var a = (7, 5);
a; //5
var x, y, z
x = (y=1, z=4);
x; //4
y; //1
z; //4