Friday, September 26, 2014

JavaScript JSON, XML & Ajax questions and answers

1. Explain JSON data types.

Keyword:
Number, String, Boolean, Array, Object, null

Answer:
JSON has the following basic data types:
a. Number — a signed decimal number that may contain a fractional part and may use exponential E notation.
b. String — a sequence of zero or more Unicode characters. Strings are delimited with double-quotation marks and support a backslash escaping syntax.
c. Boolean — either of the values true or false.
d. Array — an ordered list of zero or more values, each of which may be of any type. Arrays use square bracket notation with elements being comma-separated.
e. Object — an unordered associative array (name/value pairs). Objects are delimited with curly brackets and use commas to separate each pair, while within each pair the colon ':' character separates the key or name from its value.
f. null — An empty value, using the word null.

Example:
{
    "id": 1,
    "name": "iraylab",
    "active": true,
    "apps": [
        {"name": "JavaScript Interview Notes", "version":"1.0"},
        {"name": "Java Interview Notes", "version":"1.5"}
    ]
}

2. How to convert JSON text to JavaScript object?

Keyword:
eval(),
JSON.parse()

Answer:
There are two ways to convert a JSON text into an object:

var myJSONtext = '{"id":1, "name":"JavaScript Interview Notes"}';

a. Use the eval() method:
var myObject = eval('(' + myJSONtext + ')');

b. Use JSON object and its parse() method:
try{
    var myObject = JSON.parse(myJSONtext);
} catch(e){
    console.log("Parse error:", e);
}

3. What is JSONP?

Answer:
JSONP (JSON with padding) is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on <script> tags.

JSONP wraps up a JSON response into a JavaScript function and sends that back as a Script to the browser. A script is not subject to the Same Origin Policy and when loaded into the client, the function acts just like the JSON object that it contains.

4. How to parse an XML Document in JavaScript?

Keyword:
Use browser built-in DOM parser

Answer:
All modern browsers have a built-in XML parser. Firefox, Chrome, and IE 9 support DOMParser object. For IE<9, we need to use loadXML() method.

For example:
var xmlStr = "<app><title>JavaScript Interview Notes</title><author>iraylab</author></app>";
var xmlDoc;
if (window.DOMParser) {
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(txt,"application/xml");
}
else { // Internet Explorer < 9
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async=false;
    xmlDoc.loadXML(txt);
}

5. How to manipulate XML Document in JavaScript?

Keyword:
XMLDocument object

Answer:
XMLDocument object is a container object for an XML document, it provides a series of methods manipulate XML Document.

a. To create a new empty XMLDocument object, use the createDocument method;
b. To build an XMLDocument object from a string, use the DOMParser object. In IE<9, use loadXML method;
c. To build an XMLDocument object from a file or from a response of an HTTP request, use the XMLHttpRequest object and its responseXML property;
d. To get the root element of an XML document, use the documentElement property;
e. To retrieve an element in an XML document, use the firstChild, lastChild, nextSibling and previousSibling properties, the getElementsByTagName method and the childNodes collection.

6. What is Ajax?

Keyword:
Asynchronous JavaScript and XML,
XMLHttpRequest,
XML, JSON

Answer:
Ajax is Asynchronous JavaScript and XML. Ajax is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications.

Ajax uses the XMLHttpRequest object to communicate with server-side scripts. It can make requests to the server and update portions of a page without reloading the whole page.

Ajax can send as well as receive information in a variety of formats, including JSON, XML, HTML, and even text files.

7. What is XMLHttpRequest?

Answer:
XMLHttpRequest (XHR) is an API available to web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests to a web server and load the server response data back into the script.  XMLHttpRequest is used heavily in AJAX programming.

In JavaScript, XMLHttpRequest is an object. XMLHttpRequest makes sending HTTP requests very easy.  You simply create an instance of XMLHttpRequest, open a URL, send the request and handler the response when readyState changes.

8. How to make cross-browser Ajax request using XmlHttpRequest?

Keyword:
new XMLHttpRequest()
new ActiveXObject("Microsoft.XMLHTTP") for IE

Answer:
Modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object, we can create XMLHttpRequest object directly. For old versions of Internet Explorer (IE5 and IE6), we need to create an ActiveX Object.

//Create cross-browser XmlHttpRequest instance:
var xhr;
if(window.XMLHttpRequest) { // Modern browsers, like IE8, firefox, etc
    xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject){ // for IE 6
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
   
if(xhr) {
    //Register or define callback function:
    xhr.onreadystatechange = function(){
        if(xhr.readyState==4 && xhr.status==200) {
           //handle response
        }
    }
    //Send request:
    xhr.open("GET", "http://www.iraylab.com/sample", true);
    xhr.send();
}

More JavaScript JSON, XML & Ajax interview questions and answers: JavaScript Interview Notes

  • What is JSON?
  • Can you add comments to JSON?
  • How to convert JavaScript object to JSON text?
  • What are the difference between JSON and XML?
  • List some technologies used by Ajax?
  • What are the advantages and disadvantages of using Ajax?
  • Explain XMLHttpRequest object common properties.
  • Explain different type of ready state in XMLHttpRequest object.
  • ......

JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.


SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


Thursday, September 25, 2014

JavaScript Function, Scope & Closure questions and answers

1. What is Scope in JavaScript?

Keyword:
global scope, local scope

Answer:
In JavaScript, scope refers to the region of your code in which it is defined.
Variables declared outside of a function definition are global variables and have global scope;
Variables declared within a function are local variables and have local scope. Function parameters also count as local variables and have local scope.

For example:
var scope = "global";         // Declare a global variable
function checkscope() {
    var scope = "local";      // Declare a local variable with the same name
    return scope;             // Return the local value, not the global one
}
checkscope()                  // => "local"

2. Explain JavaScript Scope Chain.

Answer:
In JavaScript, every chunk of code (global code or functions) has a scope chain associated with it. This scope chain is a list or chain of objects that defines the variables that are “in scope” for that code. When JavaScript needs to look up the value of a variable x, it starts by looking at the first object in the chain. If that object has a property named x, the value of that property is used. If the first object does not have a property named x, JavaScript continues the search with the next object in the chain. If the second object does not have a property named x, the search moves on to the next object, and so on. If x is not a property of any of the objects in the scope chain, then x is not in scope for that code, and a ReferenceError occurs.

In top-level JavaScript code, the scope chain consists of a single object: the global object. In a non-nested function, the scope chain consists of two objects: the object that defines the function, and the global object. In a nested function, the scope chain has three or more objects.

3. What is the difference between var x = 1 and x = 1?

Answer:
var x = 1 declares variable x in current scope. If the declaration is in a function, x is a local variable. If the declaration is outside of function, x is a global variable.

x = 1 tries to resolve x in the scope chain: if found, it performs assignment. If not found, it creates x property on a global object.

4. What are Function Scope and Hoisting?

Keyword:
variables declared within a function are visible before they are declared

Answer:
JavaScript doesn't support block scope, in which variables are not visible outside of the block (within curly braces). Instead, JavaScript uses function scope: variables are visible within the function in which they are defined and within any functions that are nested within that function.

With function scope, all variables declared within a function are visible throughout the body of the function, even visible before they are declared. This feature is called hoisting: JavaScript code behaves as if all variable declarations in a function are “hoisted” to the top of the function.

For example:
var scope = "global";
function f() {
    console.log(scope);  // Outputs "undefined", not "global"
    var scope = "local"; // Variable initialized here, but defined everywhere
    console.log(scope);  // Outputs "local"
}

5. How is the "this" determined in event handler?

Answer:
When the "this" is used in a event handler function, the "this" is set to the element the event fired from.
For example:
//<div class="intro">Intro</div>
var element = document.querySelector('.intro');
var showThis = function () {
  console.log(this);  //"this" refer to <div class="intro">Intro</div>
};
element.addEventListener('click', showThis, false);

When the code is called from an in–line handler, the "this" is set to the DOM element on which the listener is placed.
For example:
<button onclick="alert(this.tagName);">This</button>
The above alert shows "Button"

When the code is called from an inner function, the "this" isn't set and it refers to the global/window object.
For example:
<button onclick="alert((function(){return this}()));">This</button>
The above alert shows "[object window]"

6. What is the difference between call() method and apply() method?

Keyword:
call() requires a parameter list,
apply() requires an array of parameters.

Answer:
call() and apply() allow you to indirectly invoke a function as if it were a method of some other object. The first argument to both call() and apply() is the object on which the function is to be invoked; this argument becomes the this value within function body.

f.call(o);
f.apply(o);
These two lines equal to:
o.m = f; // Make f a temporary method of o.
o.m(); // Invoke it, passing no arguments.
delete o.m; // Remove the temporary method.

The main difference between them is that apply() lets you invoke the function with arguments as an array; call() requires the parameters be listed explicitly.
f.call(o, 1, 2);
f.apply(o, [1,2]);

f.call(o, a, b, c); // Fixed number of arguments
f.apply(o, arguments); // Forward current function's arguments to o directly

7. What is Closure in JavaScript?

Keyword:
the function defined in the closure remembers the environment in which it was created

Answer:
A closure is a function that refer to independent (free) variables. In other words, the function defined in the closure remembers the environment in which it was created.

A closure is created when an inner function is made accessible from outside of the function that created it. This typically occurs when an outer function returns an inner function.  When this happens, the inner function maintains a reference to the environment in which it was created, which means that it remembers all variables and their values that were in scope at the time.

For example:
function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

In the above example, add5 and add10 are two closures. They share the same function body definition, but store different environments. In add5's environment, x is 5, while for add10, x is 10.

8. How to emulate private methods with closures?

Answer:
Private methods are methods that can only be called by other methods inside the same class. JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures.

For example:
var myCounter = (function() {
  // private variable
  var _counter = 0;

  // private method
  function doCount(val) {
    _counter += val;
  }

  return {
    increment: function() {
      doCount(1);
    },
    decrement: function() {
      doCount(-1);
    },
    value: function() {
      return _counter;
    }
  };
})();

console.log(myCounter.value()); /* Prints 0 */
myCounter.increment();
myCounter.increment();
alert(myCounter.value()); /* Prints 2 */
myCounter.decrement();
alert(myCounter.value()); /* Prints 1 */

For the above code, the function returns an object with three methods: increment, decrement and value. They have access to the private method doCount and private variable _counter. But the outer world can not directly access them.

More JavaScript Function, Scope & Closure interview questions and answers: JavaScript Interview Notes

  • Explain the "this" keyword in JavaScript?
  • How is the "this" determined in prototype method?
  • How to find the min/max number in an array?
  • What does Function.prototype.bind() method do?
  • What is the arguments object?
  • What is the difference between setTimeout() and setInterval()?
  • What is Immediately-invoked function expression in JavaScript?
  • ......

JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.


SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


Object-Oriented JavaScript questions and answers

1. What is the difference between Classic Inheritance and Prototypical Inheritance?

Keyword:
Classic Inheritance: class and object
Prototypical Inheritance: object, no class

Answer:
In Classic Inheritance, there are two types of abstraction: class and object. To create an object, first define the structure of the object, using a class declaration, then instantiate the class to create a new object. Objects created in this manner have their own copies of all instance attributes, plus a link to the single copy of each of the instance methods. Java and C# use classic inheritance.

In Prototypical Inheritance, there is only one type of abstraction: object. We create an object directly, instead of defining the structure through a class. The object can be reused by new objects. JavaScript use prototypical inheritance.


2. What are the different ways to create an object in JavaScript?

Keyword:
object literal,
constructor function,
Object.create method

Answer:
There are three typical ways to create an object:

a. Using object literal
An object literal is a comma-separated list of colon-separated name:value pairs, enclosed within curly braces.
For example:
var myObject = {
    property1 : "www.iraylab.com",
    property2 : {
       nestedProperty1 : "JavaScript"
    }
};

b. Using constructor function
Define the object type by writing a constructor function. Then, create an instance of the object with new keyword.
For example:
function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
var myCar = new Car("BMW", "X5", 2014);

c. Using the Object.create method
With ECMAScript 5, we can a static function Object.create() to create an object.
The Object.create() method creates a new object with the specified prototype object and properties: Object.create(prototype [, propertiesObject ])

For example:
var obj = Object.create(null, {
     make: "BMW",
     model: "X5",
     year: 2014
});

3. How to access the properties of an object?

Keyword:
dot notation .
bracket notation []

Answer:
There are two ways to access the properties of an object.

var car = {
    make: "BMW",
    year: 2014
};

a. Using the dot notation: .
var m = car.make; // get property value
car.make = "GM";  // set property new value

b. Using the bracket notation: []
var m = car["make"];
car["make"] = "GM";


4. How to define public and private properties/methods in an object?

Keyword:
private: var
public: this

Answer:
In a JavaScript object, properties/methods defined with var keyword can only be accessed inside the object;
properties/methods defined with this keyword can be accessed from outside the object.
For example:
function Car (maker, model, year) {
    //public properties and methods:
    this.maker = maker;
    this.model = model;
    this.year = year;
    this.getInfo = function() {
        return "Car info: maker=" + this.maker + ", model="+ this.model +", year=" + this.year;
    };
    //private properties and methods:
    var color;
    var getColor = function() {
        return "color=" + color;
    };

    //access a private method inside the object
    this.getDetailedInfo = function() {
        return this.getInfo() + ", " + getColor();
    }
}


5. How to add custom methods and properties to an object?

Keyword:
use prototype

Answer:
To add properties and methods to an object, we can modify its prototype property.

For example:
function Car (maker, model, year) {
    this.maker = maker;
    this.model = model;
    this.year = year
}

//add new property and new method:
Car.prototype.color = "Black";
Car.prototype.getRating = function() {
    return 1;
};


6. How to create a namespace in JavaScript?

Answer:
In JavaScript, there is no the concept of namespace, we can create global object to emulate namespace.

For example, the following code create a namespace "iraylab.JSModule" and create two functions inside this namespace:

var iraylab = iraylab || {};
iraylab.JSModule = {
    add: function(a, b) {
        return a + b;
    },
    subtract: function(a, b) {
        return a -b;
    }
};

7. How to implement inheritance in JavaScript?

Keyword:
use prototype and constructor function

Answer:
JavaScript is a class-free, object-oriented language, we can implement prototypal inheritance by using prototype and constructor function.

The following is an example to implement this kind of inheritance.
a. Define super class:
function Vehicle () {}

b. Define sub class:
function Car (maker, model, year) {
    this.maker = maker;
    this.model = model;
    this.year = year
}

c. Set up inheritance:
Car.prototype = new Vehicle;

d. Extend super class using prototype:
Vehicle.prototype.getInfo = function(){
    console.log("This is a vehicle.");
}

e. Sub class override super class's method:
Car.prototype.getInfo = function() {
    console.log("This is a car.");
};

8. How to implement Singleton Pattern in JavaScript?

Answer:
The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

In JavaScript, we can implement a Singleton as follows:

var Singleton = (function () {
  var instance;

  function init() {

    //define private methods and variables here...
    function privateMethod(){
        console.log( "a private method" );
    }
    var privateVariable = "a private variable";

    return {

      // Public methods and variables
      publicMethod: function () {
        console.log( "a public method" );
      },

      publicProperty: "a public property"
    };
  };

  return {
    // Get the Singleton instance if one exists or create one if it doesn't
    getInstance: function () {
      if ( !instance ) {
        instance = init();
      }
      return instance;
    }
  };
})();

// Use the singleton class:
var mySingleton = Singleton.getInstance();
......

More Object-Oriented JavaScript interview questions and answers: JavaScript Interview Notes

  • What is constructor in JavaScript?
  • How to list all properties of an object itself?
  • How to define static properties and methods in an object?
  • What is the global object in JavaScript?
  • What is prototype in JavaScript?
  • What is the difference of using prototype and "this" to define a method?
  • How to handle error in JavaScript?
  • ......

JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.


SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play