Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Friday, September 26, 2014

JavaScript jQuery questions and answers

1. Explain jQuery main features.

Answer:
jQuery includes the following features:
DOM element selections, traversal and modification;
DOM manipulation based on CSS selectors;
HTML Event methods;
Effects and animations;
AJAX;
Extensibility through plug-ins;
Utilities - such as user agent information, feature detection;
Multi-browser support.

2. How to include jQuery in your web pages?

Keyword:
<script> tag
CDN

Answer:
There are two ways to include jQuery:
a. Download jQuery library and add the jQuery file in HTML <script> tag in <head> section.
For example:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-{version}.min.js"></script>
</head>

b. Include jQuery from a CDN.
For example, use jQuery from Google CDN:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/{version}/jquery.min.js">></script>
</head>

3. What is the different between window.onload and $(document).ready?

Keyword:
window.onload: after all content (css, images) of web page loaded,
$(document).ready: after DOM loaded, before css, images loaded.

Answer:
window.onload is a built-in Javascript event that occurs when all content of the web page has been loaded, including css, images, etc.

$(document).ready is jQuery event that occurs as soon as the HTML DOM is loaded, before css, images and other resources are loaded.

We can add multiple document.ready() function in a page, while we can add only one window.onload function.

4. What is jQuery.noConflict?

Keyword:
relinquish jQuery's control of the $ variable

Answer:
jQuery.noConflict is used to relinquish jQuery's control of the $ variable.
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict().

Example:
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
//......
//Use jQuery for jQuery code
jQuery(document).ready(function(){
   jQuery( "div p" ).hide();
});
</script>

5. Explain different selectors in jQuery.

Keyword:
element selector, id selector, class selector, attribute selector, etc

Answer:
jQuery offers a powerful set of selectors for selecting and manipulating HTML element(s).

a. All Selector ("*")
$("*") Selects all elements

b. Element Selector ("element")
Selects all elements with the given tag name.
Example:
$("p") Select all <p> elements on a page

c. ID Selector ("#id")
Selects a single element with the given id attribute.
Example:
$("#book") Select the element with id="book"

d. Class Selector (".class")
Selects all elements with the given class.
Example:
$(".author") Select all elements with class="author"

e. Attribute Selector
Selects elements that have the specified attribute with a value matches a certain matching rule.
Example:
$( "input[value='Submit']" ) Select all input elements that "value" attribute equals "Submit"
$( "input[name^='share']" ) Select all input elements that "name" attribute starts with "share"

f. Child Selector ("parent > child")
Selects all direct child elements specified by "child" of elements specified by "parent". Example:
$( "ul.nav > li" ) Select all list items that are children of <ul class="nav">

6. How to hide/show HTML element in jQuery?

Keyword:
.hide(), .show(), .toggle()

Answer:
Use .hide(), .show(), .toggle() methods. For example:
$("showButton").click(function(){
  $("div").show();
});
$("hideButton").click(function(){
  $("div").hide();
});
$("toggleButton").click(function(){
  $("div").toggle();
});

7. How to update HTML element text in jQuery?

Keyword:
.text(), .html()

Answer:
Use .text() or .html() methods.
.text(): Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
Example:
$("button1").click(function(){
  $("#nav1").text("Question");
});

.html(): Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
Example:
$("button1").click(function(){
  $("#nav1").text("<b>Keyword</b>");
});

8. What are the differences between .empty(), .remove() and .detach() methods in jQuery?

Answer:
.empty(): Remove all child nodes of the set of matched elements from the DOM. This method removes not only child elements, but also any text within the set of matched elements.

.remove(): Similar to .empty(). This method removes the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

.detach(): Similar to .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

9. How to make Ajax request in jQuery?

Keyword:
.ajax(),
.getJSON(), .load(), .get(), .post()

Answer:
jQuery offers a couple of methods to make Ajax request:

.ajax(): Perform an asynchronous HTTP (Ajax) request. It is jQuery's low-level AJAX implementation. All jQuery AJAX methods use this method internally. This method is mostly used for requests where the other methods cannot be used.
$.ajax({
  type: "POST",
  url: "http://",
  data: data,
  success: function(){...},
  error : function(){...},
  complete : function(){...},
  dataType: "json"
});

.getJSON(): Load JSON-encoded data from the server using a GET HTTP request.

.load(): Load data from the server and place the returned HTML into the matched element.

.get(): Load data from the server using a HTTP GET request.

.post(): Load data from the server using a HTTP POST request.

More JavaScript jQuery interview questions and answers: JavaScript Interview Notes

  • What is the meaning of symbol $ in jQuery?
  • How to use multiple jQuery version on the same page?
  • What is CDN? Why use it?
  • How to handle events in jQuery?
  • What are the differences between .bind(), .live(), .delegate() and .on()?
  • How to add HTML element in jQuery?
  • How to check if an element is empty in jQuery?
  • What are global Ajax event handlers in jQuery?
  • ......

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


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


JavaScript DOM & BOM questions and answers

1. How to add JavaScript to an HTML page?

Keyword:
<script> tag,
external js file

Answer:
a. Use <script> tag in the HTML page:
In the following example, a JavaScript function is placed between the <script> and </script> tags. The function is invoked when a button is clicked.
<!DOCTYPE html>
<html>
<head>
<script>
function showHello() {
    alert("hello");
}
</script>
</head>
<body>
    <button type="button" onclick="showHello()">Show Hello</button>
</body>
</html>

b. Use external JavaScript file:
To use an external script, put the name of the script file in the source (src) attribute of the <script> tag.
<!DOCTYPE html>
<html>
<head>
<script src="hello.js"></script>
</head>
<body>
    <button type="button" onclick="showHello()">Show Hello</button>
</body>
</html>

2. What is element, nodeList, attribute and namedNodeMap in HTML DOM?

Answer:
Element refers to an HTML element in the DOM. Element objects can have child nodes of type element nodes, text nodes, or comment nodes. Element objects implement the DOM Element interface and also the more basic Node interface.

NodeList is an array of elements. Items in a nodeList are accessed by index in either of two ways: list.item(1) or list[1].

Attribute refers to an HTML attribute. An attribute belongs to an HTML element.

NamedNodeMap is an unordered collection of an elements attribute nodes. Items in a namedNodeMap are accessed by name or index.

3. How to find HTML element in an HTML page using DOM API?

Keyword:
document.getElementById(),
Element.getElementsByTagName(),
document.getElementsByClassName()

Answer:
There are several ways to do this:
a. Find by id
Example: finds the element with id="add":
var e = document.getElementById("add");

b. Find by Tag Name
Example: finds the element with id="nav", and then finds all <p> elements inside "nav":
var navElement = document.getElementById("nav");
var elements = navElement.getElementsByTagName("p");

c. Find by Class Name
Example: find all HTML elements with class="category":
var elements = document.getElementsByClassName("category");

4. What is innerHTML?

Answer:
The innerHTML is a property of HTML element object. It refers to the HTML code and the text that occurs between the element's opening and closing tag.
We can use innerHTML either to retrieve the current content of the element or to insert new content into that element.

The following example uses innerHTML to insert new elements to a HTML page:
<!DOCTYPE html>
<html>
<head>
<script>
function updateDiv(){
    document.getElementById("div1").innerHTML = "<p>New title</p><p>New Text...</p>";
}
</script>
</head>
<body>
<div id="div1">Default Text</div>
    <button type="button" onclick="updateDiv()">Update</button>
</body>
</html>

5. What is BOM?

Keyword:
Browser Object Model,
window, navigator, location, document, history, screen, frames collection

Answer:
The Browser Object Model (BOM) is the part of JavaScript that allows JavaScript to interface and interact with the web browser. There are no official standards for the BOM.

At the top of the BOM is the window object. It represents the entire browser, with its toolbars, menus, status bar and the page itself. Under the window object, there are the following objects: navigator, location, document (DOM), history, screen, frames collection.

Using BOM, we can modify, move the window or can change the text in status bar, read the current URL, go back or forward of the current page which otherwise not possible with DOM.

6. What is the window object?

Keyword:
window = web browser,
global variables/methods belong to window

Answer:
The window object represents the web browser itself. All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object. Global functions are methods of the window object. The document property points to the DOM document loaded in that window.

7. How to get web browser window size?

Keyword:
use window object

Answer:
Use the window object innerWidth and innerHeight property.
var w = window.innerWidth; //return the width of browser window including the vertical scrollbar.
var h = window.innerHeight; //return the height of browser window including the horizontal scrollbar.

The innerWidth and innerHeight is not supported by in Internet Explorer < 9. To get the size of window in IE 6, 7, 8:
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;

8. How to detect web browser information?

Keyword:
use navigator object

Answer:
The navigator object contains information about the browser:
var browserName = navigator.appName; //returns the name of the browser.
var browserVersion = navigator.appVersion; //returns the version of the browser.
var userAgent = navigator.userAgent //returns the user agent string for the browser.
var cookieEnabled = navigator.cookieEnabled; //returns whether cookies are enabled in the browser.

9. What is DOM level 0 event handling model and DOM level 2 event handling model?

Keyword:
DOM level 0: onclick="...", single event handler,
DOM level 2: addEventListener, removeEventListener, allow multiple event handlers

Answer:
DOM level 0 event handling model is based around the concept of using element attributes or named events on DOM elements. There are two model types: inline model and traditional model.
In inline model, event handlers are added as attributes of elements. For example:
<input type="button" onclick="handleButtonClickEvent();" />
In traditional model, event handlers can be added/removed by scripts. The event is added by assigning the handler name to the event property of the element object. For example:
<script>
    document.onclick = function(){
        //......
    }
</script>

DOM level 2 event handling model defines an advanced event-handling API to manage events and subscriptions. With this model, we can add multiple event handlers for a single event.
There are three important methods:
addEventListener: Allows the registration of event listeners on the event target.
removeEventListener: Allows the removal of event listeners from the event target.
dispatchEvent: Allows sending the event to the subscribed event listeners.

10. How to add/remove JavaScript file to a web page at runtime?

Answer:
Use DOM API. For example:

/* Add script to head element */
function addScript(loc) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = loc;
    document.getElementsByTagName('head')[0].appendChild(script);
    return script;  
}

/* Removes script from head element */
function removeScript(script) {
    var head = document.getElementsByTagName('head')[0];
    if (head && script) {
        head.removeChild(script);
        script = null;
    }
}

/* Usage */
var myScript = addScript("http://www.iraylab.com/test/test.js");
......
removeScript(myScript);

More JavaScript DOM & BOM interview questions and answers: JavaScript Interview Notes

  • What is the document object?
  • How to change the style of an HTML element?
  • How to change HTML content dynamically?
  • How to detect the screen resolution?
  • How to detect the operating system on the client machine?
  • How to make web browser go back to previous page?
  • What is DOM event?
  • What is event bubbling and event capture?
  • What are onload event and onunload event?
  • ......

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


JavaScript Basics questions and answers

1. What is the relationship between JavaScript, JScript and ECMAScript?

Keyword:
ECMAScript: language standard
JavaScript, JScript: different implementations

Answer:
ECMAScript is the name of the language standard developed by ECMA. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript and ActionScript.

JavaScript is the Netscape/Mozilla implementation of the ECMA specification. JScript is the Microsoft implementation of the ECMAScript specification. While both JavaScript and JScript aim to be compatible with ECMAScript, they also provide additional features not described in the ECMA specifications.

2. What is the difference between undefined and null?

Keyword:
undefined: declared,but no value; undefined type
null: a null value; object type

Answer:
a. undefined means a variable has been declared but has not yet been assigned a value. null is an assignment value. It can be assigned to a variable as a representation of no value.

b. For the data type, undefined is a type itself (undefined) while null is an object.

The following example shows their differences:
var a;  //undefined variable
console.log(a); //output undefined
console.log(typeof a); //output undefined
var b = null;
console.log(b); //output null
console.log(typeof b); //output object

3. What is the difference between "===" and "=="?

Keyword:
===: strict equality, no type conversion
==:  try type conversion if not the same type. null == undefined

Answer:
The strict equality (===) returns true if the operands are strictly equal with no type conversion: If the two values have different types, they are not equal.

The equality operator (==) is similar to the strict equality operator, but it is less strict. If the values of the two operands are not the same type, it attempts some type conversions and then tries the comparison. If one value is null and the other is undefined, they are equal.

4. What is the difference between instanceof and typeof?

Keyword:
instanceof: return true/fase,
typeof: return type string representation

Answer:
The instanceof operator returns true if the specified object is of the specified object type.
Usage: obj instanceof type
For example:
var today = new Date(2014, 12, 31);
if (today instanceof Date) {
  //......
}

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned.
Usage: typeof operand   //or: typeof (operand)
For example:
var str = "www.iraylab.com";
var num = 1;
var obj = {};
function hello() {
  console.log("Hello world.");
}
typeof str;   // returns "string"
typeof num;   // returns "number"
typeof obj;   // returns "object"
typeof hello; // returns "function"
typeof true;  // returns "boolean"
typeof null;  // returns “object"

5. How to convert a comma separated string from/to an array?

Keyword:
split()
join()

Answer:
To convert a comma separated string to an array, use split() method:
var str = "a,b,c,d";
var arr = str.split(',');

To convert an array to a comma separated string, use join() method:
var arr = ["Apple", "Orange", "Banana"];
var str = arr.join(","); //the default separator is comma (,)

6. What is the difference between String literal and String object?

Keyword:
String literal: string type
String object: object type

Answer:
String literals (denoted by double or single quotes) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. When a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

String literal is a type of string, while String object is a type of object:
var s1 = "iraylab.com";
var s2 = new String("iraylab.com");
console.log(typeof s1); // output "string"
console.log(typeof s2); // output "object"

7. How to create an array in JavaScript?

Keyword:
array literal
new Array()

Answer:
There are two typical ways to create an array:
a. Using array literal:
var myArray1 = [1,2,5,6];
var myArray2 = ["Apple", "Orange", "Banana"];

b. Using new keyword:
var myArray3 = new Array(1,2,5,6);
var myArray4 = new Array("Apple", "Orange", "Banana");

8. How to add/remove elements from an array?

Keyword:
push()
pop()

Answer:
Use push() and pop method:
var arr = ["Apple", "Orange", "Banana"];
//add element to the end of the array
arr.push("Pear");
//remove element from the end of the array
var element = arr.pop(); //return "Pear", arr is now ["Apple", "Orange", "Banana"]

9. What is associative array in JavaScript?

Keyword:
object is associative array

Answer:
JavaScript doesn't have a specific associative array type, but every object has the ability to act as an associative array.

To create an associative array is to create a JavaScript object:
var obj ={};
obj["someKey"]=3;
obj["someOtherKey"]= someObject;
obj["anotherKey"]="Some text";
Access elements in the associative array:
var someValue = obj["someKey"];
obj["otherKey"]= someValue;

10. How to validate e-mail address using JavaScript?

Answer:
Use regular expression and test() method. For example:

function validateEmail(email){
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if (!reg.test(email)) {
        return false;
    }
    return true;
}

More JavaScript Basics interview questions and answers: JavaScript Interview Notes

  • What is delete operator in JavaScript?
  • What is || operator in JavaScript?
  • How to generate a random integer value between two numbers?
  • How to trim leading and trailing spaces from a string?
  • What are the built-in types in JavaScript?
  • What is the difference between slice(), substring() and substr()?
  • How to sort an array of objects?
  • How to create a Regular 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