Skip to main content

OOAP -Javascript

JAVASCRIPT


Question : How to find the index of an element from the JavaScript Array?
Answer : Arrayname.indexOf(value);

Question : How to remove an element form the JavaScript Array?
Answer : Arrayname.splice(indexOfElement,1);

Question : How can you convert a String to an Object?
Answer : provided the String is valid JSON String we can convert it using JSON.parse(VALID JSON TEXT)
e.g.
var validText = '{"name" : "vikash" , "success":true, "Address" : {"Building" : "Building_X", "Flat" : "12"}}';
var obj = JSON.parse(validText);

Now we can access the data in this way obj.name or obj.success or obj.Address.Building or obj.Address.Flat

What is Event Bubbling and Capturing?
Answer : On the Introduction to events page I asked a question that at first sight seems incomprehensible: “If an element and one of its ancestors have an event handler for the same event, which one should fire first?” Not surprisingly, this depends on the browser.

The basic problem is very simple. Suppose you have a element inside an element
-----------------------------------
| element1                              |
|   -------------------------          |
|   |element2                            |
|   -------------------------          |
|                                              |
-----------------------------------
and both have an onClick event handler. If the user clicks on element2 he causes a click event in both element1 and element2. But which event fires first? Which event handler should be executed first? What, in other words, is the event order?
Two models

Not surprisingly, back in the bad old days Netscape and Microsoft came to different conclusions.

Netscape said that the event on element1 takes place first. This is called event capturing.
Microsoft maintained that the event on element2 takes precedence. This is called event bubbling.
The two event orders are radically opposed. Explorer only supports event bubbling. Mozilla, Opera 7 and Konqueror support both. Older Opera's and iCab support neither.

Event capturing

When you use event capturing
                     | |
 ---------------| |-----------------
| element1     | |              
|      -----------| |-----------  
|   |element2  \ /        
|   -------------------------  
|        Event CAPTURING        
-----------------------------------
the event handler of element1 fires first, the event handler of element2 fires last.

Event bubbling

When you use event bubbling

                     / \
 ---------------| |-----------------
| element1     | |              
|   -----------   | |-----------
|   |element2  | |              
|   -------------------------  
|        Event BUBBLING
-----------------------------------
the event handler of element2 fires first, the event handler of element1 fires last.

W3C model

W3C has very sensibly decided to take a middle position in this struggle. Any event taking place in the W3C event model is first captured until it reaches the target element and then bubbles up again.

                         | |  / \
  -----------------| |--| |-----------------
|  element1       | |  | |                    
|     ------------- | |--| |-----------    
|    |element2    \ /  | |                    
|   --------------------------------      
|        W3C event model              
------------------------------------------

You, the web developer, can choose whether to register an event handler in the capturing or in the bubbling phase. This is done through the addEventListener() method explained on the Advanced models page. If its last argument is true the event handler is set for the capturing phase, if it is false the event handler is set for the bubbling phase.

Question : How to activate event capturing?

Answer : Let's say we have following divs
<div id="1">
       1
       <div id="2">
              2
              <div id="3">3</div>
       </div>
</div>

Now to activate the event capturing we need to execute following method on all the divs
var highlightThis = function(){
       alert($(this)[0].id);
}
$(function() {
       var divs = document.getElementsByTagName('div')
       for(var i=0; i< divs.length; i++) {
         //argument type of the addEventListener is
         // 1st argument - type of the even needed to be registered for the event                  //capturing
         //method needed to be called upon the the event
         //even capturing is true or false, false means default behavior i.e. even                //bubbling, and true means event capturing mode is active.
         divs[i].addEventListener("click", highlightThis, true)
       }
});


Question : Is JavaScript case sensitive?
Answer : Yes! JavaScript is a case sensitive because a function str is not equal to Str.

Question : What is the Type of JavaScript?
Answer : There are different of Type as given below.
  1. String, 
  2. Number,
  3. Boolean,
  4. Function,
  5. Object,
  6. Null,
  7. Undefined etc
Question : What types of Boolean operators in JavaScript?
Answer : There are three types of Boolean operators as given below.
AND (&&) operator,
OR (||) operator and
NOT (!) Operator

Question : What is the difference between “==” and “===”?
Answer : The double equal “==” is an auto-type conversion. It’s used to check the value and type of its variable.
The three equal “===” is not auto-type conversion. It’s used to check only value of its variable.
The real example as given below:
// Its returns true because it's an auto-type conversion and it check value and type both.
if(1 == ”1”) 
// Its returns false because it's not auto-type conversion and it check only value not type.
if(1 === ”1”) 
// Its returns true.
if(1=== parseInt(”1”)) 

Question : What is an Object?
Answer : The object is a collection of properties and the each property associated with the name-value pairs. The object can contain any data types (numbers, arrays, object etc.)

The example as given below :
var myObject= {empId : “001”, empCode :”X0091”};

In the above example, here are two properties one is empId and other is empCode and its values are “001” and “X0091”.

The properties name can be string or number. If a property name is number i.e.
var numObject= {1 : “001”, 2 :”X0091”};
//This line throw an error.
Console.log(numObject.1); 

// will access to this line not get any error.
Console.log(numObject[“1”]); 

As per my thought, the number property name should be avoided.

Types of creating an object
Object literals
Object constructor

Object Literals: This is the most common way to create the object with object literal and the example as given below.
The empty object initialized using object literal i.e.
var emptyObj= {};
This is an object with 4 items using object literal i.e.
var emptyObj ={
  empId:”Red”,
  empCode: “X0091”,
 empDetail : function(){
    alert(“Hi”);
};
};
Object Constructor: The second way to create object using object constructor and the constructor is a function used to initialize new object.The example as given below
var obj = new Object();
Obj.empId=”001”;
Obj.empCode=”X0091”;
Obj.empAddressDetai = function(){
       Console.log(“Hi, I Anil”);
};

Question : What is scope variable in JavaScript?
Answer : The scope is set of objects, variables and function and the JavaScript can have global scope variable and local scope variable.

The global scope is a window object and its used out of function and within the functions.
The local scope is a function object and its used within the functions.

The example for global scope variable
    var gblVar = "Anil Singh";
    function getDetail() {
        console.log(gblVar);
    }
and other example for global
    function demoTest() {
        x = 15;
    };
    console.log(x); //out put is 15

The example for local scope variable
    function getDetail() {
        var gblVar = "Anil Singh";
        console.log(gblVar);
    }

and other example for local
    function demoText() {
        var x = 15;
    };
   console.log(x); //undefined

Question : What is associative arrays in JavaScript or What is array? 
Answer : Array is a collection of index items and it is a number indexes.
Some of programming language support array as named indexes and the JavaScript not support the array as name indexes and its provide only number indexes but provide this feature using the associative array.

The array with name indexes are called associative array and the associative array is provide a ways to store the information.

The number index array example as given below
    var users = new Object();
    users["Name1"] = "Anil 1";
    users["Name2"] = "Anil 2";
    users["Age"] = 33;
    alert(Object.keys(users).length); //output is 3.
    var length = Object.keys(users).length;  // 3
 
The name index array example as given below
    var users = [];
    users["Name1"] = "Anil 1";
    users["Name2"] = "Anil 2";
    users["Age"] = 33;
    var length = users.length;         // users.length will return 0
    var detail = users[0];             // users[0] will return undefined

Where to use the associate array?
Answer : Can be use for the example like a database table have some columns and its type. i.e. the empName as text type, empAge as number type and enpDOB as date type.
If we need to find the type of a column that time we can create the associate array. i.e.
var empDetailType = new Array();
empDetailType["empName"] = "ANil";
empDetailType["empAge"] = 30;
empDetailType["empDOB"] = "10/03/1984";

console.log("Find the emp age type :" + empDetailType["empAge"]);

Question : How to achieve inheritance in JavaScript?
Answer : In the JavaScript, we can implement the inheritance using the some alternative ways and we cannot define a class keyword but we create a constructor function and using new keyword achieve it.
The some alternative ways as given  below.
Pseudo classical inheritance
Prototype inheritance
Pseudo classical inheritance is the most popular way. In this way, create a constructor function using the new operator and add the members function with the help for constructor function prototype.

The prototype based programming is a technique of object oriented programming. In this mechanism we can reuse the exiting objects as prototypes. The prototype inheritance also know as prototypal,
classless or instance based inheritances.
The Inheritance example for prototype based as given below

  // Create a helper function.
   if (typeof Object.create !== 'function') {
        Object.create = function (obj) {
            function fun() { };
            fun.prototype = obj;
            return new fun();
        };
    }

    //This is a parent class.
    var parent = {
        sayHi: function () {
            alert('Hi, I am parent!');
        },
        sayHiToWalk: function () {
            alert('Hi, I am parent! and going to walk!');
        }
    };

    //This is child class and the parent class is inherited in the child class.
    var child = Object.create(parent);
    child.sayHi = function () {
        alert('Hi, I am a child!');
    };

    <button type="submit" onclick="child.sayHi()"> click to oops</button>

The output is : Hi, I am a child!


Question : What is typeof operator?
Answer : The typeof operator is used to find the type of variables.
The example as given below.
typeof "Anil Singh"      // Returns string
typeof 3.33                    // Returns number
typeof true                    // Returns Boolean
typeof { name: 'Anil', age: 30 } // Returns object
typeof [10, 20, 30, 40]             // Returns object

Question : example where changes of the value changes the type of the variable.
Answer :
var color1 = 1;           
var color2 = '1';
             
console.log('color1 '+(typeof     color1) ); //color1 number
console.log('color2 '+typeof color2); //color2 string
             
var color1 = '1';
var color2 = 1;
             
console.log('color1 '+(typeof     color1) ); //color1 string
console.log('color2 '+typeof color2); //color2 string

Question : What is the output of the below code?
console.log(typeof null);
Answer : The output is object, as it refers to the object.

Question : What is the diff between primitive type and refrence type in javascript?
Answer : Reference types do not store the object directly into the variable to which it is assigned, so the object variable in this example doesn’t actually contain the object instance. Instead, it holds a pointer (or reference) to the location in memory where the object exists. This is the primary difference between objects and primitive values, as the primitive is stored directly in the variable.
When you assign an object to a variable, you’re actually assigning a pointer. That means if you assign one variable to another, each variable gets a copy of the pointer, and both still reference the same object in memory. 
For example:
var object1 = new Object();
var object2 = object1;
This code first creates an object (with new) and stores a reference in object1. Next, object2 is assigned the value of object1. There is still only the one instance of the object that was created on the first line, but both variables now point to that object,

Question : Do you have the code to demonstrate the same.
Answer
var obj1 = new Object();
var obj2 = obj1;
obj1.customProperty = 'My Name';
console.log(obj2.customProperty) //Output : My Name

This example demonstrates one particularly unique aspect of JavaScript: You can modify objects whenever you want, even if you didn’t define them in the first place.

Question : Do we have something like nullpointer exception, similar to Java in JavaScript?
Answer : Yes we have when we try to add the properties to the object of value null;
var item = null;
item.name = "vikash";
console.log(item)
console.log(item.name)
error : Uncaught TypeError: Cannot set property 'name' of null

Question : Can we add the property to the primitive type object?
Answer : No, we can not do that, look at the below example where we are trying to add the additional property to the String primitive type.

var item = "hello"; //string primitive type
item.name = "vikash"; // added the value to the property, it will not work as output is //undefined
console.log(item) //hello
console.log(item.name) //output : undefined
What is the way for dereferencing Objects?
Answer : JavaScript is a garbage-collected language, so you don’t really need to worry about memory allocations when you use reference types. However, it’s best to dereference objects that you no longer need so that the garbage collector can free up that memory. The best way to do this is to set the object variable to null.

What are the built in types in JavaScript?
Answer
Array : An ordered list of numerically indexed values
Date : A date and time
Error : A runtime error (there are also several more specific error subtypes)
Function : A function
Object : A generic object
RegExp : A regular expression

var items = new Array();
var now = new Date();
var error = new Error("Something bad happened.");
var func = new Function("console.log('Hi');");
var object = new Object();
var re = new RegExp("\\d+");

How can we create an object without new operator?
Answer : We can create the object using JSON kind of notation like as follows.
var book = {
     "name of book": "The Principles of Object-Oriented JavaScript",
     "year of release": 2014,
     Author : 'Vikash'
};
console.log(book['name of book']); //Output : The Principles of Object-Oriented JavaScript
console.log(book['year of release']) //Output : 2014
console.log(book.Author); //Output : Vikash           

One thing that can be observed is we can have key/name of the property can also be separated by space, only this is it should be enclosed by double quotes, next is we canot access like objectname.propertyName, we have to do something like ObjectName['propertyName'].

What is the difference between typeof and instanceof operator?
Answer : typeof is unary and instanceof is binary operator
typeof returns the type of variable, instanceof returns true or false by comparing the variable with the data type.
var items = [];
function f(){
                    
}
var obj = {};
console.log(items instanceof Array); //true
console.log(f instanceof Function); //true
console.log(obj instanceof Object); //true
console.log(typeof items ); //Object
console.log(typeof f  ); //function
console.log(typeof obj ); //object

Question : Is there other way then instanceof operator, we can get to know if the given object is array?
Answer : we have Array.isArray(array varaible name) method can specify if the given object is array or not?

Question : Can you explain the below output?
var name = "Nicholas";
var count = 10;
var found = false;
console.log(name instanceof String); // false
console.log(count instanceof Number); // false
console.log(found instanceof Boolean); // false
console.log(typeof name); // string
console.log(typeof count); // number
console.log(typeof found); // boolean

Answer : The primitive wrapper types are reference types that are automatically created behind the scenes whenever strings, numbers, or Booleans are read. So to the primitive variable to behave like an object the javascript engine creates the temp object like var temp = new string(originalVar); and also add the dereference statement like temp=null. So we can read it but we cannot use it further for any operation as the temp object will be garbage collected.

What is the difference between function declarations and expressions?
Answer : Example of the declaration is
var result = addFunc(1,2);
console.log(result);
function addFunc(a,b){
       return a+b;
}
example of expression is
var addFunc = function(a,b){
       return a+b;
}
var result = addFunc(1,2);
console.log(result);

Although these two forms are quite similar, they differ in a very important way. Function declarations are hoisted to the top of the context (either the function in which the declaration occurs or the global scope) when the code is executed. That means you can actually define a function after it is used in code without generating an error.
For example:
var result = addFunc(1,2);
console.log(result);

function addFunc(a,b){
       return a+b;
}
This code might look like it will cause an error, but it works just fine.That’s because the JavaScript engine hoists the function declaration to the top and actually executes the code as if declared like
function addFunc(a,b){
       return a+b;
}
var result = addFunc(1,2);
console.log(result);


Function hoisting happens only for function declarations because the function name is known ahead of time. Function expressions, on the other hand, cannot be hoisted because the functions can be referenced only through a variable. So this code causes an error:
var result = addFunc(1,2);
console.log(result);

var addFunc = function(a,b){
       return a+b;
}
As long as you always define functions before using them, you can use either function declarations or function expressions.

Question :  Can we assign function variable to another variable?
Answer : Yes that is absolutely fine.
var anotherAddFunc = addFunc;
console.log(anotherAddFunc(5,6));
function addFunc(a,b){
       return a+b;
}                   
//or
var add = function(num1, num2) {
       return num1 + num2;
};           
var addVarAnotherFunc = add;
console.log(addVarAnotherFunc(1,2));

Question : explain the arguments object in terms of variable arguments parameter in the function.
Answer : the arguments is nothing but the array of the parameters passed while calling the function, it's as good as java main(args[]) only differance is we don't have to explicitly mention this variable of type, it is automatically added by the javascript engine and very much accessble inside the called function. Example below.
function sum(){
       var sum = 0;
       var i = 0;
       var len = arguments.length;
       while(i < len ){
              sum+=arguments[i];
              i++;
       }
       console.log(sum);
}            
sum(1,2,3,4); //Output  : 10

The sum() function accepts any number of parameters and adds them together by iterating over the values in arguments with a while loop. This is exactly the same as if you had to add together an array of numbers. The function even works when no parameters are passed in, because result is initialized with a value of 0.

Question : Do we have the function overloading in the javascript?
Answer : As we know javaScript functions can accept any number of parameters, and the types of parameters a function takes aren’t specified at all. That means JavaScript functions don’t actually have signatures. A lack of function signatures also means a lack of function overloading.In JavaScript, however, when you define multiple functions with the same name, the one that appears last in your code wins. The earlier function declarations are completely removed, and the last is the one that is used.
The fact that functions don’t have signatures in JavaScript doesn’t mean you can’t mimic function overloading. You can retrieve the number of parameters that were passed in by using the arguments object, and you can use that information to determine what to do.

Question : What is call() ?
Answer : The first function method for manipulating this is call(), which executes the function with a particular this value and with specific parameters. The first parameter of call() is the value to which this should be equal when the function is executed. All subsequent parameters are the parameters that should be passed into the function. For example, suppose you update sayNameForAll() to take a parameter:
function sayNameForAll(label) {
              console.log(label + ":" + this.name);
}
var person1 = {
       name : "Nicholas"
};
var person2 = {
       name : "Greg"
};
var name = "Michael";
sayNameForAll.call(this, "global"); // outputs "global:Michael"
sayNameForAll.call(person1, "person1"); // outputs "person1:Nicholas"
sayNameForAll.call(person2, "person2"); // outputs "person2:Greg"

Question : What is apply()?
Answer : The apply() method works exactly the same as call() except that it accepts only two parameters: the value for this and an array or array-like object of parameters to pass to the function (that means you can use an arguments object as the second parameter). So, instead of individually naming each parameter using call(), you can easily pass arrays to apply() as the second argument. Otherwise, call() and apply() behave identically. This example shows the apply() method in action:
function sayNameForAll(label) {
              console.log(label + ":" + this.name);
}
var person1 = {
       name : "Nicholas"
};
var person2 = {
       name : "Greg"
};
var name = "Michael";
sayNameForAll.apply(this, ["global"]); // outputs "global:Michael"
sayNameForAll.apply(person1, ["person1"]); // outputs "person1:Nicholas"
sayNameForAll.apply(person2, ["person2"]); // outputs "person2:Greg"

Question : When to use call and when to use apply?
Answer : The method you use typically depends on the type of data you have. If you already have an array of data, use apply(); if you just have individual variables, use call().

Question : What is bind()?
Answer : The first argument to bind() is the this value for the new function. All other arguments represent named parameters that should be permanently set in the new function. You can still pass in any parameters that aren’t permanently set later.
The following code shows two examples that use bind(). You create the person1Call() function by binding the this value to person1, while person2Call() binds this to person2 and binds the first parameter as "person2".
function sayNameForAll(label) {
              console.log(label + ":" + this.name);
       }
       var person1 = {
              name : "Nicholas"
       };
       var person2 = {
              name : "Greg"
       };
       var name = "Michael";
       var person1Call = sayNameForAll.bind(person1, ["person1"]);
       var person2Call = sayNameForAll.bind(person2, ["person2"]);
       person1Call();// outputs "person1:Nicholas"
       person2Call();// outputs "person2:Greg"
       person1.sayName = person2Call;
       person1.sayName();// outputs "person2:Greg"

Question : Let us assume that we have an object like var person = {name: 'vikash', age : 0}. Then what is wrong with the comparison like if(person.age)?
Answer : Basically we are trying to see if the property exist in the object or not, so our intention by writing like if(person.age) is to check if the person object contains any property with the name like age. But the problem with this pattern is how JavaScript’s type coercion affects the outcome. The if condition evaluates to true if the value is truthy (an object, a nonempty string, a nonzero number, or true) and evaluates to false if the value is falsy (null, undefined, 0, false, NaN, or an empty string). Because an object property can contain one of these falsy values, the example code can yield false negatives. For instance, if person1.age is 0, then the if condition will not be met even though the property exists.
The in operator looks for a property with a given name in a specific object and returns true if it finds it. In effect, the in operator checks to see if the given key exists in the hash table. For example, here’s what happens when in is used to check for some properties in the person1 object:
console.log("name" in person1); // true
console.log("age" in person1); // true
console.log("title" in person1); // false
Keep in mind that methods are just properties that reference functions, so you can check for the existence of a method in the same way. The following adds a new function, sayName(), to person1 and uses in to confirm the function’s presence.

Question : Give the example of the accessor method in javascript?
Answer : Accessor properties don’t contain a value but instead define a function to call when the property is read (called a getter), and a function to call when the property is written to (called a setter). Accessor properties only require either a getter or a setter, though they can have both.
There is a special syntax to define an accessor property using an object literal:
var person ={
_name : 'vikash',
       get name(){
       console.log('Name : '+this._name);
       return this._name;
},
set name(value){                        
       this._name = value;
       console.log('Name : '+this._name);
}
};
console.log(person.name)
console.log(person._name)
This example defines an accessor property called name. There is a data property called _name that contains the actual value for the property u. (The leading underscore is a common convention to indicate that the property is considered to be private, though in reality it is still public.) The syntax used to define the getter v and setter w for name looks a lot like a function but without the function keyword. The special keywords get and set are used before the accessor property name, followed by parentheses and a function body. Getters are expected to return a value, while setters receive the value being assigned to the property as an argument.
Note: If you try to create a property with both data and accessor attributes, you will get an error.

Question : Is it mandatory to define both getter and setter?
Answer : You don’t need to define both a getter and a setter; you can choose one or both. If you define only a getter, then the property becomes read-only, and attempts to write to it will fail silently in nonstrict mode and throw an error in strict mode. If you define only a setter, then the property becomes write-only, and attempts to read the value will fail silently in both strict and nonstrict modes.

Question : How can we iterate the object, like HashMap in the java in the javascript.
Answer :
var person = {
        name : 'Vikash',
        age: 29,
        address : 'Bangalore',
        pin:560103
}
//First way
for(key in person){
        console.log('key : '+key + ', value : '+person[key])
}
//Second way.
var prop = Object.keys(person);
var i = 0;
while(i < prop.length){
        console.log('key : '+prop[i] + ', value : '+person[prop[i]]);
        i++;
}

Question : what is configurable:true?
Answer : this is the property which can be set using Object.defineProperty(objectVarName,propertyName,{configurable:true}) , which states that weather we can delete the property or not, if we define this as {configurable : false } then we canot call delete objectVarName.propertyName to delete the property from the object.
var person = {
       name : 'Vikash',
       age: 29,
       address : 'Bangalore',
       pin:560103
}
Object.defineProperty(person,'name',{
       configurable : false
});

delete person.name;
console.log(person.name); //Output Vikash

Object.defineProperty(person,'age',{
       configurable : true
});
delete person.age;
console.log(person.age); //Output undefined

Question : Can we call the defineProperty for the same property twice?
Answer : No we can not, we will get the following error, Uncaught TypeError: Cannot redefine property: name.
var person = {
       name : 'Vikash',
       age: 29,
       address : 'Bangalore',
       pin:560103
}
Object.defineProperty(person,'name',{
       configurable : false
});

delete person.name;
console.log(person.name); //Output Vikash

Object.defineProperty(person,'name',{
       configurable : true
});
error : Uncaught TypeError: Cannot redefine property: name.

Question : What is enumerable?
Answer : if we set this property as false, than the given property will not be picked up when we are iterating using the for(key in person) or Object.keys(person), so none of them will return the given property as the part of the keyset.
var person = {
       name : 'Vikash',
       age: 29,
       address : 'Bangalore',
       pin:560103
}
Object.defineProperty(person,'name',{
       enumerable : false
});
      
for(key in person){
       console.log(key +':'+ person[key])
}
/*
Output :
age:29
address:Bangalore
pin:560103
name is missing from the output as we have made it enumerable as false.
*/
var keys = Object.keys(person);
for(var i=0 ; i < keys.length ; i++){
       console.log(keys[i] +':'+ person[keys[i]])
}
/*
Output :
age:29
address:Bangalore
pin:560103
name is missing from the output as we have made it enumerable as false.
*/
But we can still able to access the {enumerable : false} data directly like person.name is still allowed and we will get the data for the same.

Question : getter and setter accessor property are part of the keys?
Answer : Yes, we can demonstrate that by below example
       var person = {
                     name : 'Vikash',
                     get _name(){
                           return this.name;
                     },
                     set _name(value){
                           this.name = value;
                     },
                     age: 29,
                     address : 'Bangalore',
                     pin:560103
       }
       Object.defineProperty(person,'name',{
              enumerable : false
       });
       
       for(key in person){
              console.log(key +':'+ person[key])
       }
       /*
       _name:Vikash
       age:29
       address:Bangalore
       pin:560103
       name is missing from the output as we have made it enumerable as false.
       instead we are getting the same data from the accessor method
       */
       var keys = Object.keys(person);
       for(var i=0 ; i < keys.length ; i++){
              console.log(keys[i] +':'+ person[keys[i]])
       }
       /*
       Output :
       _name:Vikash
       age:29
       address:Bangalore
       pin:560103
       name is missing from the output as we have made it enumerable as false.
       instead we are getting the same data from the accessor method
       */
As we can see that we are able get the data using the _name() which is getter accessor property.

What is writable and value property?
Answer :Data properties possess two additional attributes that accessors do not. The first is [[Value]], which holds the property value. This attribute is filled in automatically when you create a property on an object. All property values are stored in [[Value]], even if the value is a function. The second attribute is [[Writable]], which is a Boolean value indicating whether the property can be written to. By default, all properties are writable unless you specify otherwise. With these two additional attributes, you can fully define a data property using Object.defineProperty() even if the property doesn’t already exist.
"use strict"
var person = {
              name : 'Vikash',
              get _name(){
                     return this.name;
              },
              set _name(value){
                     this.name = value;
              },
              age: 29,
              address : 'Bangalore',
              pin:560103
}
Object.defineProperty(person,'name',{
       value : 'vijay',
       writable : false
});
console.log(person.name); //output : vijay
Object.defineProperty(person,'country',{
       value: 'India',
       configurable : true,
       writable : true,
       enumerable : true
             
});
console.log(person.country); //India

When you are defining a new property with Object.defineProperty(), it’s important to specify all of the attributes because Boolean attributes, like configurable, enumerable and writable will be automatically default to false otherwise.

Question : Is there any other way to create the accessor method for the below code?
var person = {
       name : 'Vikash',
       get _name(){
              return this.name;
       },
       set _name(value){
              this.name = value;
       },
       age: 29,
       address : 'Bangalore',
       pin:560103
}
Answer : Yes, using the defineProperty we can define the accessor method like get and set 
"use strict"
       var person = {
                     _name : 'Vikash',
                     age: 29,
                     address : 'Bangalore',
                     pin:560103
       }
       Object.defineProperty(person,'name',{
              set : function (value){
                     this._name = value
              },
              get : function (){
                     return this._name;
              },
              configurable : true,
              enumerable : true
       });
       console.log(person.name); //output : Vikash

Only thing to be cautious is we should not mention the writable and value for the accessor property as we will get the error as Uncaught TypeError: Invalid property.  A property cannot both have accessors and be writable or have a value, #<Object>
Question : What are the different ways of  restricting the modification of the Object in the javascript?
Answer :Objects, just like properties, have internal attributes that govern their behavior. One of these attributes is [[Extensible]], which is a Boolean value indicating if the object itself can be modified. All objects you create are extensible by default, meaning new properties can be added to the object at any time.
Preventing Extensions
One way to create a nonextensible object is with Object.preventExtensions(). This method accepts a single argument, which is the object you want to make nonextensible. Once you use this method on an object, you’ll never be able to add any new properties to it again. You can check the value of [[Extensible]] by using Object.isExtensible().
Attempting to add a property to a nonextensible object will throw an error in strict mode. In nonstrict mode, the operation fails silently. You should always use strict mode with nonextensible objects so that you are aware when a nonextensible object is being used incorrectly.
"use strict"
       var person = {
                     _name : 'Vikash',
                     age: 29,
                     address : 'Bangalore',
                     pin:560103
       }
       Object.preventExtensions(person);
       person._name = 'vijay'; //this is fine
       delete person.age; //Allowed we can delete the property
       console.log('age' in person); //false
       person.name = 'vikash';
       //Uncaught TypeError: Can't add property name, object is not extensible

Sealing Objects
The second way to create a nonextensible object is to seal the object. A sealed object is nonextensible, and all of its properties are nonconfigurable. That means not only can you not add new properties to the object,but you also can’t remove properties or change their type (from data to accessor or vice versa). If an object is sealed, you can only read from and write to its properties.
You can use the Object.seal() method on an object to seal it. When that happens, the [[Extensible]] attribute is set to false, and all properties have their [[Configurable]] attribute set to false. You can check to see whether an object is sealed using Object.isSealed().
Be sure to use strict mode with sealed objects so you’ll get an error when someone tries to use the object incorrectly.
"use strict"
       var person = {
                     _name : 'Vikash',
                     age: 29,
                     address : 'Bangalore',
                     pin:560103
       }
       Object.seal(person);
       person._name = 'vijay'; //this is fine
       delete person.age; //Not allowed we can't delete the property
       console.log('age' in person); //false
       person.name = 'vikash';
       //Uncaught TypeError: Can't add property name, object is not extensible

Freezing Objects
The last way to create a nonextensible object is to freeze it. If an object is frozen, you can’t add or remove properties, you can’t change properties’ types, and you can’t write to any data properties. In essence, a frozen object is a sealed object where data properties are also read-only. Frozen objects can’t become unfrozen, so they remain in the state they were in when they became frozen. You can freeze an object by using Object.freeze() and determine if an object is frozen by using Object.isFrozen().
"use strict"
       var person = {
                     _name : 'Vikash',
                     age: 29,
                     address : 'Bangalore',
                     pin:560103
       }
       Object.freeze(person);
       person._name = 'vijay';
       //Uncaught TypeError: Cannot assign to read only property 
       //'_name' of #<Object>
       delete person.age;
       //Not allowed we can't delete the property
       console.log('age' in person); //false
       person.name = 'vikash';
       //Uncaught TypeError: Can't add property name, object is not extensible

Question : How the prototype scales up compared to constructor? 
Answer : Constructors allow you to configure object instances with the same properties, but constructors alone don’t eliminate code redundancy. In the example code thus far, each instance has had its own sayName() method even though sayName() doesn’t change. That means if you have 100 instances of an object, then there are 100 copies of a function that do the exact same thing, just with different data.
It would be much more efficient if all of the instances shared one method, and then that method could use this.name to retrieve the appropriate data. This is where prototypes come in. Almost every function (with the exception of some built-in functions) has a prototype property that is used during the creation of new instances. That prototype is shared among all of the object instances, and those instances can access properties of the prototype.

Question : Can you delete the prototype property?
Answer : No we can not, as the prototype property doesn't belong to the single instance object but to whole class, so kind of shared stuff and also you cannot assign a value to a prototype property from an instance.

Question : Give the example of prototype?
Answer :
"use strict"
//creating the class
var PersonClass = function(person) {
       this.person = person;
}
//adding the function to the prototype
PersonClass.prototype.displayFunc = function(){
       var keys = Object.keys(this.person);
       var i =0 ;
       while(i < keys.length){
              console.log(keys[i]+':'+this.person[keys[i]]);
              i++;
       }
}
      
//Passing inline object, as an argument
var p1 = new PersonClass({
       name : 'Vikash',
       age: 35,
       address : 'Bangalore',
       pin:560103
});
p1.displayFunc();
var person = {
       name : 'Pammi',
       age: 31,
       address : 'Bokaro',
       pin:827009
}
//Passing already created object
var p3 = new PersonClass(person);
p3.displayFunc();

Question : Can we modify the prototype after applying the sealed and frozen on the objects?
Answer : The ability to modify the prototype at any time has some interesting repercussions for sealed and frozen objects. When you use Object.seal() or Object.freeze() on an object, you are acting solely on the object instance and the own properties. You can’t add new own properties or change existing own properties on frozen objects, but you can certainly still add properties on the prototype and continue extending those objects, as demonstrated in the following listing.

Question : How can we delete or remove the properties/function from the prototype object.
Answer : we can use either delete statement or we can assign the method/properties = undefined.
      "use strict"
       var inheritedOb = {
              name: 'vikash'      
       };
      
       Object.prototype.toString1 = function(){
              return 'name : '+this.name;
       }
       Object.prototype.toString2 = function(){
              return 'name : '+this.name;
       }     
      
       console.log(inheritedOb.toString1());
       console.log(inheritedOb.toString2());
       //way 1
       delete Object.prototype.toString1;
       //way 2
       Object.prototype.toString2= undefined;
       console.log(inheritedOb.toString1());
       //error : Uncaught TypeError: inheritedOb.toString1 is not a function
       console.log(inheritedOb.toString2());
       //error : Uncaught TypeError: inheritedOb.toString2 is not a function

Question : can we add prototype function and property to the instance object?
Answer : No, we can only add to the Actual Class for which we have defined the constructor.

Question : What are the default methods inherited by all object in javascript from Object class?
Answer : Several of the methods used in the past couple of example are actually defined on Object.prototype and are therefore inherited by all other objects.

Those methods are:
hasOwnProperty() : Determines whether an own property with the given name exists

propertyIsEnumerable() :  Determines whether an own property is enumerable

isPrototypeOf() : Determines whether the object is the prototype of another

valueOf() : Returns the value representation of the object, The valueOf() method gets called whenever an operator is used on an object. It is similar to java where when we compare to wrapper class object like Integer, Long, Double then first it get converted to primitive type and then compared like > < or >= <= or ==. You can always define your own valueOf() method if your objects are intended to be used with operators. If you do define a valueOf() method, keep in mind that you’re not changing how the operator works, only what value is used with the operator’s default behavior.

toString() : Returns a string representation of the object, the toString() method is called as a fallback whenever valueOf() returns a reference value instead of a primitive value. It is also implicitly called on primitive values whenever JavaScript is expecting a string. For example, when a string is used as one operand for the plus operator, the other operand is automatically converted to a string. If the other operand is a primitive value, it is converted into a string representation (for example, true becomes "true"), but if it is a reference value, then valueOf() is called. If valueOf() returns a reference value, toString() is called and the returned value is used.

Example :
"use strict"
var inheritedOb = {
       name: 'vikash'      
};
console.log(inheritedOb.hasOwnProperty('name'));//true
console.log(inheritedOb.propertyIsEnumerable('name'));//true
console.log(inheritedOb.valueOf());//Object {name: "vikash"}
console.log(inheritedOb.toString());//[Object object]

Question : How the Object Inheritance work in the javascript?
Answer : By default it is available using the Object.prototype, but we can use the Object.create(), to achieve the inheritance. Below is the code example for the same.

      "use strict"
       var person1 = {
                     name : 'vikash',
                     sayHi : function (){
                           console.log('Hi '+this.name);
                     }
       }
       //Pure Inheritance
       var person2 = Object.create(person1,{
              age : {
                     value : 29,
                     enumerable : true,
                     configurable : true,
                     writable : true
              },
              sayAge :{
                           value : function (){
                                  console.log('Age :  '+this.age);
                           },
                           enumerable : true,
                           configurable : true,
                           writable : false
              }
       });
       //Overriding the sayHi function and also name property
       var person3 = Object.create(person1,{
                     name : {
                     value : 'Vijay',
                     enumerable : true,
                     configurable : true,
                     writable : true
              },
              sayHi :{
                           value : function (){
                                  console.log('Ola '+this.name);
                           },
                           enumerable : true,
                           configurable : true,
                           writable : false
              }
       })
       //inheriting the sayHi and sayAge function and also name, age property
       //from person 1 and person 2 multi level inheritance
       //person 1 -> person 2 -> person 4
       var person4 = Object.create(person2,{})
      
       person2.sayHi()
       person2.sayAge()
       person3.sayHi()
       person4.sayHi()
       person4.sayAge()
       console.log(person4.name);
       console.log(person4.age);


Question: What is public, private and static variables in JavaScript?
Answer: I am going to explain like strongly type object oriented language (OOPs) like(C#,C++ and java etc.).
Fist I am creating a constructor class and trying to achieve to decl are the public, private and static variables and detail as given below.
function myEmpConsepts() { // This myEmpConsepts is a constructor  function.
    var empId = "00201"; //This is a private variable.
    this.empName = "Anil Singh"; //This is a public variable.
    this.getEmpSalary = function () {  //This is a public method
        console.log("The getEmpSalary method is a public method")
    }
}
//This is a instace method and its call at the only one time when the call is instanciate.
myEmpConsepts.prototype.empPublicDetail = function () {
    console.log("I am calling public variable in the instance method :" + this.empName);
}
//This is a static vaiable and its shared by all instace.
myEmpConsepts.empStaticVaiable = "Department";
var instanciateToClass = new myEmpConsepts();

Question : How to create the namespace in JavaScript?
Answer : Please see the below example for how to create the namespace in JavaScript.

//Create the namespace.
var nameSpace = nameSpace || {};

nameSpace.myEmpConsepts = function () {
    var empId = "00201"; //This is a private variable.
    this.empName = "Anil Singh"; //This is a public variable.
    //This is public function
    this.getEmp = function () {
        return "Anil Singh"
    }

    //This is private function
    var getEmp = function () {
          return "Anil Singh"
    }

    return {
        getEmp: getEmp,// work as public
        getEmp: getEmp // work as public
    }
}();

Question : How to add/remove properties to object in run-time in JavaScript?
Answer : I am going to explain by example for add and remove properties from JavaScript objects as give below.
This example for delete property.
//This is the JSON object.
var objectJSON = {
    id: 1,
    name: "Anil Singh",
    dept: "IT"
};
//This is the process to delete
delete objectJSON.dept;

//Delete property by the array collection
MyArrayColection.prototype.remove = function (index) {
    this.splice(index, 3);
}
This example for add property

//This is used to add the property.
objectJSON.age = 30;
console.log(objectJSON.age); //The result is 30;

//This is the JSON object.
var objectJSON = {
    id: 1,
    name: "Anil Singh",
    dept: "IT",
    age :30

};

Question : How to extending built-in objects in JavaScript?
Answer : JavaScript support built-in objects which use to develop the flexibility of JavaScript. The built in object are date, string, math, array and object. It's very similar to other languages and its available in the window content and wok independently when browsers are loaded.
Example as give below
var date = new Date(); //This is date built-in object.
var math = Math.abs(10); // this is math built-in object.
var string = "my string" // this is string built-in object.

Question : Why never use new Array in JavaScript?
Answer : We have some  fundamental issues with new Array() the example in detail for array constructor function as given below.

When array have more the one integer.
var newArray = new Array(10, 20, 30, 40, 50);
console.log(newArray[0]); //returns 10.
console.log(newArray.length); //returns 5.
When array have only one integer
var newArray = new Array(10);
console.log(newArray[0]); //returns undefined
console.log(newArray.length); //returns 10 because its has an error "array index out of bound";
//This is the fundamental deference to need to avoid the new array();

Question : What is eval() and floor() functions in JavaScript?
Answer : The eval() function used in execute an argument as expression or we can say that evaluate a string as expression and it used to parse the JSON.
The example over eval() function as given below.
var x = 14;
eval('x + 10'); //The output is 24.
Another over eval() function example
eval('var myEval = 10');
console.log(myEval); // The output is 10.
The floor() function is a static method of Math and we can write as Math.floor() and used to round the number of downwards. i.e.
Math.floor(1.6);//The output is 1.

Question : What is join() and isNaN() functions in JavaScript?
Answer : The is join() function used to join the separator in the array.
Syntax:  myArray.join(mySeparator);
The example as given below.
var alfabets = ["A", "B", "C", "D"];
//Join without seperator
var result1 = alfabets.join();//The output is A B C D.
//Join with seperator.
var result2 = alfabets.join(','); //The output is A, B, C, D.
The isNaN() function is used to check the value is not-a-number.
The example as given below
var var1 = isNaN(-1.23);//The output is false.
var var2 = isNaN(3);//The output is false.
var var3 = isNaN(0);//The output is false.
var var3 = isNaN("10/03/1984"); //The output is true.

Question : What is closure in JavaScript?
Answer : While you create the JavaScript function within another function and the inner function  freely access all the variable of outer function. i.e.
function ourterFun(i) {
    var var1 = 3;
    function innerFun(j) {
        console.log(i + j + (++var1)); // It will return the 16.
    }
    innerFun(10);
}
ourterFun(2); // Pass an argument 2

The output will get 16 because innerFun() function can access to the argument "i" & variable "var1" but both are define in the outerFun() function that is closure.

That means simply accessing variable outside of your scope create a closure.

// OR Other WAYS

function ourterFun(i) {
    var var1 = 3;

    return function (j) {
        console.log(i + j + (++var1)); // It will return the 16.
    }
}

var innerFun = ourterFun(2); // innerFun() function is now a closure.
innerFun(10);


Question : What is JavaScript Hoisted?
Answer : In the JavaScript, the variables can be used before declared, this kinds of mechanism is called Hoisted. It's a default behavior of JavaScript.

You can easily understanding  in the below example in detail.

//The variable declaration look like.
var emp;

//The variable initialization look like.
emp = "Anil Singh";


var emp; //The declaration of emp is hoisted but the value of emp is  undefined.
emp = 10; //The Assignment still occurs where we intended (The value of emp is 10)

function getEmp() {
    var emp; //The declaration of a different variable name emp is hoisted but the value of emp is  undefined.

    console.log(emp); //The output is undefined
    emp = 20; //The assignment values is 20.
    console.log(emp); //The output is 20.
}

getEmp();
console.log(emp); //The variable named emp in the outer scope still contains 10.

Question : What is function overloading in JavaScript?
Answer : There is no real function overloading in JavaScript and it allows to pass any number of parameters of any type.
You have to check inside the function how many arguments have been passed and what is the type arguments using typeof.
The example for function overloading not supporting in JavaScript as give below.

function sum(a, b) {
    alert(a + b);
}
function sum(c) {
    alert(c);
}

sum(3);//The output is 3.
sum(2, 4);//The output is 2.

In the JavaScript, when we write more than one functions with same name that time JavaScript consider the last define function and override the previous functions. You can see the above example output for the same.

We can achieve using the several different techniques as give below
You can check the declared argument name value is undefined.
We can check the total arguments with arguments.length.
Checking the type of passing arguments.
Using number of arguments
Using optional arguments like x=x || 'default'
Using different name in the first place
We can use the arguments array to access any given argument by using arguments[i]

Question : What is prototype in JavaScript?
Answer : The prototype is a fundamental concept of JavaScript and its must to known JavaScript developers.

All the JavaScript objects has an object and its property called prototype and its used to add and the custom functions and property.

The example without prototype as given below.

var employee = function () {
    //This is a constructor  function.
}

//Crate the instance of above constructor  function and assign in a variable
var empInstance = new employee();
empInstance.deportment = "IT";

console.log(empInstance.deportment);//The output of above is IT.
The example with prototype as given below.
var employee = function () { //This is a constructor  function.}

employee.prototype.deportment = "IT";//Now, for every instance employee will have a deportment.

//Crate the instance of above constructor function and assign in a variable
var empInstance = new employee();
empInstance.deportment = "HR";

console.log(empInstance.deportment);//The output of above is IT not HR.

Question : What is The "use strict" Directive?
Answer
: The "use strict" directive is new in JavaScript 1.8.5 (ECMAScript version 5).
It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.
The purpose of "use strict" is to indicate that the code should be executed in "strict mode".
With strict mode, you can not, for example, use undeclared variables.

//Example ---- 1
"use strict";
x = 3.14;       // This will cause an error

//Example ---- 2
"use strict";
myFunction();

function myFunction() {
    y = 3.14;   // This will also cause an error
}

Links
http://talkerscode.com/javascript/introduction.php
https://javascript.zeef.com/awan.mahboob

jQuery

Question how to start the jQuery?
Answer : we have to write the code in script section like as follows:
$(document).ready(function() {
//Your code
$('div.poem-stanza').addClass('highlight');
});

Question : Is there short form of above syntax?
Answer : We have to write the code in script section like as follows which equivalent.
$(function() {
//Your code
$('div.poem-stanza').addClass('highlight');
});

Question : What is the difference between $(document).ready() and $(window).load()?
Answer : document.ready (jQuery) : document.ready will execute right after the HTML document is loaded property, and the DOM is ready. document.ready (a jQuery event) will fire when all the elements are in place, and they can be referenced in the JS code, but the content is not necessarily loaded.
window.load (Built-in JavaScript) : The window.load however will wait for the page to be fully loaded, this includes inner frames, images etc. * window.load is a built-in JavaScript method, it is known to have some quirks in old browsers (IE6, IE8, old FF and Opera versions) but will generally work in all of them.window.load can be used in the body's onload event like this (but I would strongly suggest you avoid mixing code like this in the HTML, as it is a source for confusion later on):

Question : What are the options when we can resolve conflicting scenario with the jQuery, when we want to use other library along with the jQuery which uses the $ symbol as well.
Answer : Following is the way to use $ with the jQuery and also keeping the $ free for the other library.
function highlight(){
       //jQuery related code
       $('tr:nth-child(even)').addClass('highlight');
}
//resolving conflict first so that other library
jQuery.noConflict();
jQuery(document).ready(function($) {
       highlight();
});

Question : what is .addClass()?
Answer : it will be used to add the class on the selected element.

Question : what is .removeClass()?
Answer : it will be use to remove the class from the selected element.

Question : Elaborate some frequently used selectors used in the jQuery.
Answer : 
Selector type
CSS
jQuery
What it does
Tag name
p { }
$('p')
This selects all paragraphs in the document.
ID
#some-id { }
$('#some-id')
This selects the single element in the document that has an ID of some-id.
Class
.some-class { }
$('.someclass')
This selects all elements in the document that have a class of some-class.

Question : How to add a class to an anchor element having attribute for the email?
Answer : $('a[href^="mailto:"]').addClass('mailto') , here ^ means starting with the mailto:
This comes under the beginning Substring Attribute Value Selector and usually pattern is like element1[attr^="substring"].

Question : How can you add an alternate color/style/class to even numbered row of a table?
Answer : From jQuery we can achieve like as follows.
function addHighlightClass() {
              //Long form but reliable, even if we have multiple table result was not varying
              $('tr:nth-child(even)').addClass('alt');
              //Short form but not that reliable when more than 1 table present in the page.
              $('tr:even').addClass('alt');
}

and if we want directly from the css then we can write a css style selecting the nth child of the table row like as follows
tr:nth-child(even) {
       background: #ccc;
}

Question : How can we use the contains as pseudo selector?
Answer :
function addHighlightClass() {
       $('td:contains(Tragedy)').addClass('highlight');
}

It will find all the td cells and add the class highlight to all of them.

Question : From above example, is it possible if we can highlight the next td or next sibling which is next to the cell having Content "Tragedy"?
Answer : It's very much possible using the next(), which used to select the next element based on the selection criteria, look at the below code snippet,
function addHighlightClass() {
       $('td:contains(Tragedy)').next().addClass('highlight');
}

Question : From above example, is it possible if we can highlight all  the sibling next to the cell having Content as "Tragedy"?
Answer : It's very much possible using the nextAll(), which used to select the next element based on the selection criteria, look at the below code snippet,
function addHighlightClass() {
       $('td:contains(Tragedy)').nextAll().addClass('highlight');
}

Question : From above example, is it possible if we can highlight all  the sibling next to the cell having Content as "Tragedy" and also the cell containing Tragedy?
Answer : It's very much possible using the addBack(), which used to select the previous element based on the last selection criteria, so here it will find the starting point from where nextAll started and then using that information it will look back and apply the style class look at the below code snippet,
function addHighlightClass() {
       $('td:contains(Tragedy)').nextAll().addBack().addClass('highlight');
}

Do we have any short cut for the same? Yes we do have, look at the below code snippet, the job is
$(document).ready(function() {
       $('td:contains(Henry)').parent().child().addClass('highlight');
});
it will try to find the parent of the td, which is nothing but the tr, and the children of the tr is all the td, only catch here is the behavior is same if the cell containing the henry is first cell in the row, else behavior will differ slightly the cell is second cell then from the 2nd cell till last cell, the styling will be applied, but in 2nd case styling will be applied to all the cells in the row.

Question : Is there way we can avoid what was happening using the parent() and child(), as entire row is applied with the highlight class?
Answer: Yes after selecting the parent we can filter out few child which we need, look at the below code.
$(document).ready(function() {
       $('td:contains(Henry)') // Find every cell containing "Henry"
       .parent() // Select its parent
       .find('td:eq(1)') // Find the 2nd descendant cell
       .addClass('highlight') // Add the "highlight" class
       .end() // Return to the parent of the cell containing "Henry"
       .find('td:eq(2)') // Find the 3rd descendant cell
       .addClass('highlight'); // Add the "highlight" class
});

Question : How to enable click event on the button with the id switcher-default?
Answer: we need to call the following code.
function addClickEvent() {
       $('#switcher-default').on('click', function(){
              $('span').removeClass('large');
       });
}
$(function() {
       addClickEvent();
});

Question : Give example where in the addEvent we can refer to the same object on which event is applied.
Answer : we can use $(this)for this kind of requirement, following is the code snippet to demonstrate the same. Here we are trying to add the class selected on the click/focus of the button, and we will remove the class as soon as focus goes on something else, like we click on some other button.
$('#switcher-default').on('focus', function(){
       $(this).addClass('selected');
});
$('#switcher-default').on('blur', function(){
       $(this).removeClass('selected');
});

What is the Difference between $(this) and this in jQuery?
Answer : "this" refers to a to a DOM element and $(this) refers to a jQuery object.
In other word if you use this you have to use javascrip code, But if you use $(this) you have to use jQuery code.

As we know that innerText is javascrip method where as text() is jQuery method, so we can use innerText with this but we can not use text() with this

Question :  How to find all the buttons in the div having the id=switcher?
Answer :  Here taking from the above, we are trying to add the class selected on the click event on the button and also wanted to remove that class when some other button is clicked, so line on each event is trying to clean/remove the class selected from each button by calling #switcher which gets the div or span or whatever with the id = switcher, and then find all the button in it, so togethor it is #switcher button and applying remove class.
$('#switcher-default').on('click', function(){
       //Removing the selected class from each button 
       $('#switcher button').removeClass('selected');
      
       //applying the class selected on the currently clicked button
       $(this).addClass('selected');
});
$('#switcher-narrow').on('click', function(){
       $('#switcher button').removeClass('selected');
       $(this).addClass('selected');
});
$('#switcher-large').on('click', function(){
       $('#switcher button').removeClass('selected');
       $(this).addClass('selected');
});


What is hover()?
Answer : the declaration of the hover() is .hover( handlerIn, handlerOut )  and the use it to bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
handlerIn : the first argument is of Type Function( Event eventObject ) and this will be a function to execute when the mouse pointer enters the element.

handlerOut : the second argument is of Type : Function( Event eventObject ) and this will be aa function to execute when the mouse pointer leaves the element.

The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

Look at the following code example for the same:
var handlerIn = function() {
       $(this).addClass('hover');
}
var handlerOut = function() {
       $(this).removeClass('hover');
}
function highlight() {
       $('#switcher h3').hover(handlerIn, handlerOut);
}
$(function() {
       highlight();
});

There is another version of the .hover() which .hover(handlerInOut).

Question : How can we stop the event propagation, i.e. how can we stop the bubbling of the events?
Answer : we have to call event.stopPropagation(), look at the following code as an example?

Let's say we have following divs
<div id="1">
       1
       <div id="2">
              2
              <div id="3">3</div>
       </div>
</div>

Hence to add the click event on all the divs inside the page, we have added following.
var highlightThis = function(event){
       alert(this.id);
}
$(function() {
       $('div').click(highlightThis);
});

But this is causing the bubble effect i.e. if we call on 3 then alert event of the 3,2,1 are called i.e. until it reaches to the parent. Now to avoid this we need to add the event.stopPropagation(); in the same code.
var highlightThis = function(event){
       alert(this.id);
       event.stopPropagation();
}
$(function() {
       $('div').click(highlightThis);
});

Question : Show the code which can demonstrate the benefit of bubbling?
Answer : Lets say we have following html
<div id="root">
<div id="1">1</div>
<div id="2">
             <div id="2.1">
                 <div id="2.11">
                      2.11
                 </div>
             </div>
        </div>
<div id="3">3</div>
<div id="4">4</div>

We want to develop a funcionality where on click of the div, it will tell which div is clicked. i.e. it will alert the div id, one way is to add the onclick even manually in html, second way way will be loop through each div inside the div having the id root, and add the on click event, or we can use the bubbling of even and we will just appy the click event on the parent node i.e. the div having the id=root, and hence if we click on the one of the child id, then it will be captured using the bubbling by the parent div.

var highlightThis = function(event){
       alert(event.target.id);
}
$(function() {
       $('#root').click(highlightThis);
});

So as you can we have applied the click event only to the div having the id as  #root, and the event.target is able to figure out that what is real element which has started this, as you can see is even if we click on 2.11, which is under 2.1 and that is also under 2 and finally 2 is immediate child of root, so still it is able to know which element has started this, so able to show 2.11 in alert.

Question : Does event bubbling is also known is event delegation?
Answer : Yes, Event bubbling is one aspect of event delegation.

Question : How can you simulate the click event, i.e. how can you initiate the click event without even clicking that button?
Answer : We can use the trigger() to achieve the same, at times, it is convenient to execute code that we have bound to an event, even if the normal circumstances of the event are not occurring. For example, suppose we wanted our style switcher to begin in its collapsed state. We could accomplish this by hiding buttons from within the stylesheet, or by adding our hidden class or calling the .hide() method from a $(document).ready() handler. Another way would be to simulate a click on the style switcher so that the toggling mechanism we've already established is triggered. The .trigger() method allows us to do just this:
$(document).ready(function() {
       $('#switcher').trigger('click');
});

Question : What is css()?
Answer : The css() method sets or returns one or more style properties for the selected elements.
Return a CSS Property : To return the value of a specified CSS property, use the following syntax:
css("propertyname");

The following example will return the background-color value of the FIRST matched element:
Example :  $("p").css("background-color");

Set a CSS Property : To set a specified CSS property, use the following syntax:
css("propertyname","value");

The following example will set the background-color value for ALL matched elements:
Example:  $("p").css("background-color", "yellow");

Set Multiple CSS Properties: To set multiple CSS properties, use the following syntax:
css({"propertyname":"value","propertyname":"value",...});

The following example will set a background-color and a font-size for ALL matched elements:
Example : $("p").css({"background-color": "yellow", "font-size": "200%"});

Question : How to make an ajax call using jQuery for the spring MVC application and get the response in form of JSON?
Answer : Basic steps to be followed for activating the ajax for spring mvc.

Step 1 : Activate jQuery and create method which can make a ajax call.
<!-- Activating jQuery -->
<script   src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- Creating method for making an ajax call -->
<script type="text/javascript">
function ajaxSubmit(){
       //this is to get all the form data
       var params = $('#findContactForm').serialize();
       //Spring mvc requestmapping annotated method name
       var actionMethodName = 'findContactSubmit'
       //Now making an ajax call
       $.getJSON(actionMethodName+'?'+params, function(data){
              //if response is in form of json,
              //then we can directly get the data by call data.propertyName
              //e.g. look at the below example
              alert(data.firstName);
              alert(data.lastName);
       });
}
</script>

Step 2: Create a for in the jsp which has fields and button to call the ajaxfunction declared in the first step.
<form method="POST" action="findContactSubmit" name="findContactForm" id="findContactForm">
<fieldset>
<legend >Contact Form</legend>
<table>
<tr><td>First Name</td><td><input type="text" id="firstName" name="firstName"/></td></tr>
<tr><td>Last Name</td><td><input type="text" id="lastName" name="lastName"/></td></tr>
<tr><td><button type="button" onclick="ajaxSubmit()">Submit</button></td></tr>
</table>
</fieldset>
</form>

Step 3 : Activate the jackson for JSON marshalling and unmarshalling, it's very easy just add the jackson 2 jars in the classpath, alternatively if you have maven project then add the dependency in the pom.xml file.
<dependency>
       <groupId>com.fasterxml.jackson.core</groupId>
       <artifactId>jackson-core</artifactId>
       <version>2.0.4</version>
</dependency>
<dependency>
       <groupId>com.fasterxml.jackson.core</groupId>
       <artifactId>jackson-databind</artifactId>
       <version>2.0.4</version>
</dependency>

Step 4: Spring mvc method needed to be annotated with the @RequestMapping and @ResponseBody, like the following and it should return an Object or desired object which will be later converted to the json format.

@RequestMapping(value="findContactSubmit", method = RequestMethod.GET)
@ResponseBody
public Object findContactSubmit(HttpServletRequest request){
       Contact contact = new Contact();
       contact.setFirstName("Vikash");
       contact.setLastName("Mishra");
       return contact;
}


Question : What is load() in jQuery?
Answer : It's load data from the server and place the returned HTML/text into the matched element.
the signature of the method is .load( url [, data ] [, complete ] )
url : A string containing the URL to which the request is sent.
data : A plain object or string that is sent to the server with the request.
complete : A callback function that is executed when the request completes ,it can be a function with the following argument , Function( String responseText, String textStatus, jqXHR jqXHR ).
Example code to be used for the load method :

$(document).ready(function() {
//It's click event applied on the element having the class letters
$('.letters').click( function(event){
       event.preventDefault();
       //creating the object to be sent along with the ajax request.
       var obj = {};
       obj.alpha = "A";
       //If we want to send the POST Request then we need provide the second argument as the
       //data, else it will be sent as the get request.
       //the load method can not be run gloablly or independently it needs the element upon
       //which it needs to fire, so here the #dictionary is the elemement with the id as                                    //dictionary
       $('#dictionary').load('responseAjax'/*First Argument as the request URL*/,
       obj/*second argument as the object, if present then it is treated as the POST else GET*/,
       function(responseText,status,jqXHR){
              alert("Load Status "+status);
              alert("jqXHR "+jqXHR);
       }/* Last argument as the Call back function which
            will be called once we get the response
       So even though there is a failure in getting
       response, we will still able execute the
       callback function*/);
});   
});

Question : What is global function  $.getJSON() and how to use the global function name $.getJSON() for the above scenario.
Answer : Load JSON-encoded data from the server using a GET HTTP request. The signature of the method is jQuery.getJSON( url [, data ] [, success ] )
url : A string containing the URL to which the request is sent.
data : A plain object or string that is sent to the server with the request.
success : A callback function that is executed if the request succeeds, and the signature of the function can be Function( PlainObject data, String textStatus, jqXHR jqXHR )
Note : Addition to the success the data returned from the server has to be in JSON format, otherwise, even if there is no error from the server the callback method will not be called,
$(document).ready(function() {
//It's click event applied on the element having the class letters
$('.letters').click( function(event){
       event.preventDefault();
       //creating the object to be sent along with the ajax request.
       var obj = {};
       obj.alpha = "A";
       //If we want to send the POST Request then we need
       //provide the second argument as the
       //data, else it will be sent as the get request.
       //the load method can not be run gloablly or independently
       //it needs the element upon
       //which it needs to fire, so here the #dictionary is the
       //element with the id as dictionary
       $.getJSON('responseAjax',
       obj/*second argument as the object*/,
       function(responseText){
       //process has to be written to parse the json array/data
       //and use that data to append or crate html content and can
       //be added into the corresponding div.
       }// Last argument as the Call back function which
       //will be called once we get the response
       //So even though there is a failure in getting
       //response, we will still able execute the
       //callback function*/
        );
       });   
});

Question : What is $.get() and can we use this in place of load() method?
Answer : Load data from the server using a HTTP GET request.
url :A string containing the URL to which the request is sent.
data : A plain object or string that is sent to the server with the request.
success : A callback function that is executed if the request succeeds. Required if dataType is provided, but you can use null or jQuery.noop as a placeholder. A function with the following argument can be passwed like Function( PlainObject data, String textStatus, jqXHR jqXHR )
dataType : The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).

Question: What is difference between prop() and attr()?
Answer:
JQuery.attr() :  Get the value of an attribute for the first element in the set of matched elements.
Whereas,
JQuery.Prop() :  Get the value of a property for the first element in the set of matched elements.

What is the diff between attribute and properties in terms of jQUery?
Answer : When writing HTML source code, you can define attributes on your HTML elements. Then, once the browser parses your code, a corresponding DOM node will be created. This node is an object, and therefore it has properties.
For instance, this HTML element:
<input type="text" value="Name:">
has 2 attributes.
Once the browser parses this code, a HTMLInputElement object will be created, and this object will contain dozens of properties like: accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, clientHeight, etc.
For a given DOM node object, properties are the properties of that object, and attributes are the elements of the attributes property of that object.

Update: When a DOM node is created for a given HTML element, a corresponding property is created for each attribute in the HTML source code. For instance, for this HTML element:
<input type="text" value="Name:">
the corresponding DOM node will have a type and a value property (among others). However, when the user manually changes the value of the input box, the value property will reflect this change. So if the user inputs "John" into the input box, then:
input.value // returns "John"
whereas:
input.getAttribute('value') // returns "Name:"
The value property reflects the current text-content inside the input box, whereas the valueattribute contains the initial text-content of the value attribute from the HTML source code.
So if you want to know what's currently inside the text-box, read the property. If you, however, want to know what the initial value of the text-box was, read the attribute.
Question: Difference between and Usages of Html(),Text() and Val() functions in JQuery.
Ans : one of my friend interviewed in a company last day and confronted a question which I found little interesting though its very basic in nature. This is the actual content as shown below: 
  1: <div id="DivOne" class="oddNum">Div One Called !!
  2:     <span id="span">This is span value</span>
  3:     <span id="span">This is span value2
  4:         <p>I m paragraph of span 2</p></span>
  5:     <span id="span">This is span value3</span>
  6: </div>
  7: <div id="DivTwo" class="evenNum">Two</div>
  8: <div id="DivThree" class="oddNum">Three</div>
  9: <button id="btnOne">Reset odd numbers</button>
 10: <button id="btnTwo">Reset even numbers</button>
 11: <input type="text" id="txtBox" value="This is Text Box"></input>


Interviewer wanted an answer using Html(),Text() and Val().So here I’ve tried to get value using all three methods. When I initially use .Html() function it gives me all inner elements of particular div or an element you choose.This is the code base I’ve used as depicted below:
  1: $('.oddNum').css('background-color', '#DEA');
  2: $('#DivTwo').css('background-color', '#FCC');
  3: 
  4: $('#btnOne').click(function() {
  5:     // Action goes here
  6:    var result = $('#DivOne').html();
  7:     var resultText = $('#txtBox').val();
  8:     
  9:     alert(result);
 10:    // alert(resultText);
 11: });
 12: $('#btnTwo').click(function() {
 13:     // Action goes here
 14:     $('#DivTwo').css('background-color', '#FFF');
 15: });

This is the initial look of the elements in browser as given below in image:

image

Case 1 : As soon as I click on the button Reset off numbers”  and keeps var result = $('#DivOne').html();  enable in code, it gives me following result set shown below in image:
  1:  var result = $('#DivOne').html();
  2:  alert(result);

Question: How to select id which contains Meta Character.
Answer: If any element id (<li id="first-li" class="list">Sachin Kalia</li>) contains meta character in between the id then it should be resolved using the two backslashes (\\) as prefix in ID selector.

Question : How reload the server data asynchronously, means automatically.
Answer : TODO..


Question : Create a form with all kind of validation.
Answer : TODO;

Question : Implement PhoneBook.
Answer : TODO.





Useful links
http://workshop.rs/2012/12/animated-progress-bar-in-4-lines-of-jquery/
http://vevlo.com/jquery-basic-selectors-example/
using-html5-data-attribute-as-selectors-in-jquery/
http://webdesignerhut.com/get-html5-data-attribute-with-jquery/?utm_content=buffer1d94c&utm_medium=social&utm_source=facebook.com&utm_campaign=buffer&fb_ref=Default&fb_source=message
http://talkerscode.com/webtricks/simple-and-best-delete-confirmation-box-message-using-jquery-html-and-css.php
http://webexplorar.com/jquery-autocomplete-example-with-database-accessing/
http://www.technicalkeeda.com/jquery-tutorial/jquery-index-function-example
http://vevlo.com/get-form-input-element-value-jquery-javascript/
http://www.code-sample.com/2015/06/convert-json-date-to-date-format-in.html
http://memorynotfound.com/serialise-java-object-json-using-gson/
http://webdesignerhut.com/create-responsive-fixed-resizing-header/?utm_content=bufferf9ef3&utm_medium=social&utm_source=facebook.com&utm_campaign=buffer&fb_ref=Default&fb_source=message
http://vevlo.com/dynamically-insert-javascript-and-css/
http://shivganesh.com/2015/08/es6-arrows/
http://vevlo.com/jquery-file-upload-plugin/
http://stas-melnikov.ru/animated_alert/doc/index.html

Comments

Popular posts from this blog

NodeJS

Question : Why You should use Node JS? Answer :  Following are the major factor influencing the use of the NodeJS Popularity : The popularity can be important factor, as it has more user base and hence solution  of any common problem faced by developer can found easily online, without any professional help. JavaScript at all levels of the stack :  A common language for frontend and backend offers several potential benefits: The same programming staff can work on both ends of the wire Code can be migrated between server and client more easily Common data formats (JSON) exist between server and client Common software tools exist for server and client Common testing or quality reporting tools for server and client When writing web applications, view templates can be used on both sides Leveraging Google's investment in V8 Engine. Leaner, asynchronous, event-driven model Microservice architecture Question : example of node JS code? Answer :  const fs = require('fs'); const uti

Kubernetes

What is Kubernetes? Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services, that facilitates both declarative configuration and automation. It has a large, rapidly growing ecosystem.  The name Kubernetes originates from Greek, meaning helmsman or pilot. Google open-sourced the Kubernetes project in 2014. Kubernetes combines over 15 years of Google’s experience running production workloads at scale with best-of-breed ideas and practices from the community. Why you need Kubernetes and what it can do? Containers are a good way to bundle and run your applications. In a production environment, you need to manage the containers that run the applications and ensure that there is no downtime. For example, if a container goes down, another container needs to start. Wouldn’t it be easier if this behavior was handled by a system? That’s how Kubernetes comes to the rescue! Kubernetes provides you with a framework to run distributed systems resi

Spring Interview Question - Version 3.5

Spring Overview Question :   What is Spring? Answer : Spring is an open source development framework for Enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make Java EE development easier to use and promote good programming practice by enabling a POJO based programming model.   Question : What are benefits of Spring Framework? Answer :   Lightweight : Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.   Inversion of control (IOC) : Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects.   Aspect oriented (AOP) : Spring supports Aspect oriented programming and separates application business logic from system services.   C