Javascript Set1 of 10 Interview Questions

1) What are the basic types used in JavaScript?

Ans:
Primitive: String, Number, Boolean, Null, Undefined .

undefined means a variable has been declared but has not yet been assigned a value. On the other hand, null is an assignment value. It can be assigned to a variable as a representation of no value. Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Complex: Object (Arrays are Objects, Functions are Objects)

2) What are the ways to create object in JS?

1) // object constructor

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

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

2) // object literal

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

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

3) // constructor pattern

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

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

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

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


}

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

4) // using prototype pattern

function Fruit () {

}

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

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

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

var mangoFruit = new Fruit ();
   

3) Creating Arrays in JS

var a = new Array();
a[0] = 1.2;
a[1] = “Javascript”;
a[2] = true;
a[3] = { x:1, y:3};

var a = new Array(1.2,”Javascript”, true)

4) What is the difference between using call and apply to invoke a function?

var func = function(){
alert(‘hello!’);
};
func.apply();
vs
func.call();

The main difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly.
[A for apply, A for array]
[C for call, C for column of args]

theFunction.apply(valueForThis, arrayOfArgs)

theFunction.call(valueForThis, arg1, arg2, …)

5) What do you understand by this keyword in JavaScript?
Ans: In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most context that is placed on the stack. The following gives two different results (in the browser, where by-default the window object is the 0-level context):

var obj = { outerWidth : 20 };

function say() {
alert(this.outerWidth);
}

say();//will alert window.outerWidth
say.apply(obj);//will alert obj.outerWidth

6) What would be the output of the following statements?

var object1 = { same: ‘same’ };
var object2 = { same: ‘same’ };
console.log(object1 === object2);
Ans: // Logs false, JavaScript does not care that they are identical and of the same object type.
When comparing complex objects, they are equal only when they reference the same object (i.e., have the same address). Two variables containing identical objects are not equal to each other since they do not actually point at the same object.

What would be the output of the following statements?

Code

var object1 = { same: ‘same’ };
var object2 = object1;
console.log(object1 === object2);

7) Consider the following statements and tell what would be the output of the logs statements?

var price1 = 10;
var price2 = 10;
var price3 = new Number(’10’); // A complex numeric object because new was used.
console.log(price1 === price2);
console.log(price1 === price3);
Ans:

console.log(price1 === price2); // Logs true.
console.log(price1 === price3); /* Logs false because price3
contains a complex number object and price 1
is a primitive value. */

8 ) Javascript Timing Events
It’s very easy to time events in JavaScript. The two key methods that are used are:

setInterval() – executes a function, over and over again, at specified time intervals
setTimeout() – executes a function, once, after waiting a specified number of milliseconds

9) How do you add a css class to an existing html element?
document.getElementById(“p1″).className += ” big”;

This will add the class big to the list of existing classes of element p1. If the “+=” was replaced by “=” then the class “big” will REPLACE all the existing classes of p1.

10) If you forget to declare a variable using “var” keyword inside a function what happens?
That variable will be treated as a global variable.

Why should I use node.js?

http://www.toptal.com/nodejs/why-the-hell-would-i-use-node-js

  • real-time websites with push capability
  • unifies the language and data format (JSON) across the stack
  • web applications with real-time, two-way connections, where both the client and server can initiate communication, allowing them to exchange data freely
  • non-blocking, event-driven I/O to remain lightweight and efficient in the face of data-intensive real-time applications that run across distributed devices.
  • You definitely don’t want to use Node.js for CPU-intensive operations
  • Node.js operates on a single-thread, using non-blocking I/O calls, allowing it to support support tens of thousands of concurrent connections
  • Although Node.js really shines with real-time applications, it’s quite a natural fit for exposing the data from object DBs (e.g. MongoDB). JSON stored data allow Node.js to function without the impedance mismatch and data conversion
  • Typical examples include: the logging or writing of user-tracking data, processed in batches and not used until a later time; as well as operations that don’t need to be reflected instantly (like updating a ‘Likes’ count on Facebook) where eventual consistency (so often used in NoSQL world) is acceptable.

Closure and Lexical Scoping in Javascript

A closure is the combination of a function and the lexical environment within which that function was declared. Note that Merely accessing a variable outside of the immediate scope (no return statement is necessary) will create something called a closure. A function accessing a global variable will also create a closure as can be seen by console.dir(function).

A closure is a function having access to the parent scope, even after the parent function has closed.

One example of A closure is a function that returns a function. The function that is returned (the inner function) is created inside the called function (the outer) so – due to the scoping rules we’ve seen – the inner has access to the variables and arguments of the outer.

JavaScript variables can belong to the local or global scope. Global variables can be made local (private) with closures.

Mozilla Development Network(MDN) gives a great definition:
“A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.”

JavaScript has lexical scoping with function scope. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

http://www.htmldog.com/guides/javascript/advanced/closures/

http://howtonode.org/why-use-closure

https://spin.atomicobject.com/2014/10/20/javascript-scope-closures/

Uses:
1) Most useful for events and callbacks
2) Used to simulate private variables i.e, encapsulation. Read more on Private members in javascript and privileged methods here : http://www.crockford.com/javascript/private.html
3) Used to create function factories
https://medium.com/written-in-code/practical-uses-for-closures-c65640ae7304

Ajax and XMLHttpRequest

Ajax – an acronym for Asynchronous JavaScript and XML)[1] is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With Ajax, Web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data can be retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not required; JSON is often used instead (see AJAJ), and the requests do not need to be asynchronous.

Technologies involved:
HTML (or XHTML) and CSS for presentation
The Document Object Model (DOM) for dynamic display of and interaction with data
XML for the interchange of data, and XSLT for its manipulation
The XMLHttpRequest object for asynchronous communication
JavaScript to bring these technologies together

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. All browsers supports XMLHttpRequest.

typical use:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
       document.getElementById("demo").innerHTML = xhttp.responseText;
    }
};
xhttp.open("GET", "filename", true);
xhttp.send();

With Jquery :

$('#main-menu a').click(function(event) {
   event.preventDefault();
 
   $.ajax(this.href, {
      success: function(data) {
         $('#main').html($(data).find('#main *'));
         $('#notification-bar').text('The page has been successfully loaded');
      },
      error: function() {
         $('#notification-bar').text('An error occurred');
      }
   });
});

Javascript Questions Set4

Global Variables:
The var keyword is used to declare a local variable or object, while omitting the var keyword creates a global variable.

Types in Javascript:
JavaScript is a loosely-typed language (some call this weakly typed); this means that no type declarations are required when variables are created. Strings and numbers can be intermixed with no worries. JavaScript is smart, so it easily determines what the type should be. The types supported in JavaScript are: Number, String, Boolean, Function, Object, Null, and Undefined.

What does “this” refer to in Javascript?
In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most context that is placed on the stack.

Every line of JavaScript code is run in an “execution context.” The JavaScript runtime environment maintains a stack of these contexts, and the top execution context on this stack is the one that’s actively running.

There are three types of executable code: Global code, function code, and eval code. Roughly speaking, global code is code at the top level of your program that’s not inside any functions, function code is code that’s inside the body of a function, and eval code is global code evaluated by a call to eval.

The object that this refers to is redetermined every time control enters a new execution context and remains fixed until control shifts to a different context. The value of this is dependent upon two things: The type of code being executed (i.e., global, function, or eval) and the caller of that code.

That’s it! You can figure out what object this refers to by following a few simple rules:

– By default, this refers to the global object.
– When a function is called as a property on a parent object, this refers to the parent object inside that function.
– When a function is called with the new operator, this refers to the newly created object inside that function.
– When a function is called using call or apply, this refers to the first argument passed to call or apply. If the first argument is null or not an object, this refers to the global object.

Why to use call and apply instead of calling a function directly ?
You use call or apply when you want to pass a different this value to the function. In essence, this means that you want to execute a function as if it were a method of a particular object. The only difference between the two is that call expects parameters separated by commas, while apply expects parameters in an array.

Advantages and Disadvantages of AJAX

Advantages

  • Your page will be more pleasant to use, when you can update parts of it without a refresh, which causes the browser to flicker and the statusbar to run.
  • Because you only load the data you need to update the page, instead of refreshing the entire page, you save bandwidth.

Disadvantages

  • Because the updates are done by JavaScript on the client, the state will not register in the browsers history, making it impossible to use the Back and Forward buttons to navigate between various states of the page.
  • For the same reason, a specific state can’t be bookmarked by the user.
  • Data loaded through AJAX won’t be indexed by any of the major search engines.
  • People using browsers without JavaScript support, or with JavaScript disabled, will not be able to use the functionality that you provide through AJAX.