javascript : Interview Questions

Answer:

JavaScript is a client-side as well as server side scripting language that can be inserted into HTML pages and is understood by web browsers. JavaScript is also an Object based Programming language

Answer:

Java is a complete programming language. In contrast, JavaScript is a coded program that can be introduced to HTML pages. These two languages are not at all inter-dependent and are designed for the different intent. Java is an object - oriented programming (OOPS) or structured programming language like C++ or C whereas JavaScript is a client-side scripting language.

Answer:

Following are the JavaScript Data types:

  • Number
  • String
  • Boolean
  • Object
  • Undefined

Answer:

isNan function returns true if the argument is not a number otherwise it is false.

Answer:

JavaScript is faster. JavaScript is a client-side language and thus it does not need the assistance of the web server to execute. On the other hand, ASP is a server-side language and hence is always slower than JavaScript. Javascript now is also a server side language (nodejs).

Answer:

Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.

Answer:

Breaking within a string statement can be done by the use of a backslash, '\', at the end of the first line
 

[removed]("This is \a program");

And if you change to a new line when not within a string statement, then javaScript ignores break in line.
 
var x=1, y=2,
z=
x+y;

The above code is perfectly fine, though not advisable as it hampers debugging.

Answer:

Netscape is the software company who developed JavaScript.

Answer:

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

Answer:

<html> 
<head> 
<title>t1</title> 
<script type="text/javascript"> 
	function addNode() { var newP = document.createElement("p"); 
	var textNode = document.createTextNode(" This is a new text node"); 
	newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); } 
</script> </head> 
<body> <p id="firstP">firstP<p> </body> 
</html>

Answer:

Global variables are those that are available throughout the length of the code, that is, these have no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared.

Example:

// Declare a global globalVariable = "Test";

The problems that are faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.

Answer:

A prompt box is a box which allows the user to enter input by providing a text box. Label and box will be provided to enter the text or number.

Answer:

=== is called as strict equality operator which returns true when the two operands are having the same value without any type conversion.

Answer:

'This' keyword refers to the object from where it was called.

Answer:

To submit a form using JavaScript use document.form[0].submit();

document.form[0].submit();
 

Answer:

Timers are used to execute a piece of code at a set time or also to repeat the code in a given interval of time. This is done by using the functions setTimeout, setInterval and clearInterval.

The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay. The setInterval(function, delay) function is used to repeatedly execute the given function in the mentioned delay and only halts when cancelled. The clearInterval(id) function instructs the timer to stop.

Timers are operated within a single thread, and thus events might queue up, waiting to be executed.

Answer:

Yes JavaScript does support automatic type conversion, it is the common way of type conversion used by JavaScript developers

Answer:

// for Single line comments and

/* Multi

Line

Comment

*/

Answer:

It can be done in the following way:

document.getElementById("myText").style.fontSize = "20";
or
document.getElementById("myText").className = "anyclass";
 

Answer:

'ViewState' is specific to a page in a session.

'SessionState' is specific to user specific data that can be accessed across all pages in the web application.

Answer:

There are two ways to read and write a file using JavaScript

  • Using JavaScript extensions
  • Using a web page and Active X objects

Answer:

Following are looping structures in Javascript:

  • For
  • While
  • do-while loops

Answer:

Variable typing is used to assign a number to a variable and the same variable can be assigned to a string.

i = 10;
i = "string";
This is called variable typing.

Answer:

The parseInt() function is used to convert numbers between different bases. parseInt() takes the string to be converted as its first parameter, and the second parameter is the base of the given string.

In order to convert 4F (of base 16) to integer, the code used will be -
 

parseInt ("4F", 16);

Answer:

"==" checks only for equality in value whereas "===" is a stricter equality test and returns false if either the value or the type of the two variables are different.

Answer:

Since 3 and 2 are integers, they will be added numerically. And since 7 is a string, its concatenation will be done. So the result would be 57.

Answer:

In order to detect the operating system on the client machine, the navigator.platform string (property) should be used.

Answer:

The NULL value is used to represent no value or no object. It implies no object or null string, no valid boolean value, no number and no array object.

Answer:

The delete keyword is used to delete the property as well as its value.

var student= {age:20, batch:"ABC"};
delete student.age;
 

Answer:

Undefined value means the

  • Variable used in the code doesn't exist
  • Variable is not assigned to any value
  • Property doesn't exist

Answer:

  • Alert
  • Confirm and
  • Prompt

Answer:

Void(0) is used to prevent the page from refreshing and parameter "zero" is passed while calling.

Void(0) is used to call another method without refreshing the page.

Answer:

The following code has to be inserted to achieve the desired effect:

 

Answer:

All variables in the JavaScript are object data types.

Answer:

An alert box displays only one button which is the OK button.

But a Confirmation box displays two buttons namely OK and cancel.

Answer:

Escape characters (Backslash) is used when working with special characters like single quotes, double quotes, apostrophes and ampersands. Place backslash before the characters to make it display.

document.write "I m a "good" boy"
document.write "I m a \"good\" boy"
 

Answer:

Cookies are the small test files stored in a computer and it gets created when the user visits the websites to store information that they need. Example could be User Name details and shopping cart information from the previous visits.

Answer:

The pop() method is similar as the shift() method but the difference is that the Shift method works at the start of the array. Also the pop() method take the last element off of the given array and returns it. The array on which is called is then altered.

var cloths = ["Shirt", "Pant", "TShirt"];
cloths.pop();
//Now cloth becomes Shirt,Pant

Answer:

No. JavaScript does not have concept level scope. The variable declared inside the function has scope inside the function.

Answer:

If you use innerHTML in JavaScript the disadvantage is

  • Content is replaced everywhere
  • We cannot use like "appending to innerHTML"
  • Even if you use +=like "innerHTML = innerHTML + 'html'" still the old content is replaced by html
  • The entire innerHTML content is re-parsed and build into elements, therefore its much slower
  • The innerHTML does not provide validation and therefore we can potentially insert valid and broken HTML in the document and break it

Answer:

Break statement exits from the current loop.

Continue statement continues with next statement of the loop.

Answer:

They are as –

  • Primitive
  • Reference types.
Primitive types are number and Boolean data types. Reference types are more complex types like strings and dates.

Answer:

Generic objects can be created as:

var I = new object();
 

Answer:

'Typeof' is an operator which is used to return a string description of the type of a variable.

Answer:

Try… Catch---finally is used to handle exceptions in the JavaScript

Try{
	Code
}
Catch(exp){
	Code to throw an exception
}
Finally{
	Code runs either it finishes successfully or after catch
}
 

Answer:

document.write("Welcome") is used to print the text – Welcome in the screen.

Answer:

Blur function is used to remove the focus from the specified object.

Answer:

There are three types of errors:

  • Load time errors: Errors which come up when loading a web page like improper syntax errors are known as Load time errors and it generates the errors dynamically.
  • Run time errors: Errors that come due to misuse of the command inside the HTML language.
  • Logical Errors: These are the errors that occur due to the bad logic performed on a function which is having different operation.

Answer:

The push method is used to add or append one or more elements to the end of an Array. Using this method, we can append multiple elements by passing multiple arguments

Answer:

Unshift method is like push method which works at the beginning of the array. This method is used to prepend one or more elements to the beginning of the array

Answer:

Both are almost similar. JavaScript is developed by Netscape and Jscript was developed by Microsoft .

Answer:

Properties are assigned to objects in the following way -

obj["class"] = 12;
or
obj.class = 12;
 

Answer:

Strict Mode adds certain compulsions to JavaScript. Under the strict mode, JavaScript shows errors for a piece of codes, which did not show an error before, but might be problematic and potentially unsafe. Strict mode also solves some mistakes that hamper the JavaScript engines to work efficiently.

Strict mode can be enabled by adding the string literal "use strict" above the file. This can be illustrated by the given example:
 

function myfunction() {
    "use strict";
    var v = "This is a strict mode function";
}

Answer:

The status can be acquired as follows -

alert(document.getElementById('checkbox1').checked);

If the CheckBox will be checked, this alert will return TRUE.

Answer:

The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed.

onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.

Answer:

Closure is a locally declared variable related to a function which stays in memory when the function has returned.

function greet(message) {

    console.log(message);

}

function greeter(name, age) {

    return name + " says howdy!! He is " + age + " years old";

}

// Generate the message

var message = greeter("James", 23);

// Pass it explicitly to greet

greet(message);

This function can be better represented by using closures

function greeter(name, age) {

    var message = name + " says howdy!! He is " + age + " years old";

    return function greet() {

        console.log(message);

    };

}

// Generate the closure

var JamesGreeter = greeter("James", 23);

// Use the closure

JamesGreeter();
 

Answer:

A value can be appended to an array in the given manner -

arr[arr.length] = value;

Answer:

The for-in loop is used to loop through the properties of an object.

The syntax for the for-in loop is -
 

for (variable name in object){
	statement or block to execute
}
In each repetition, one property from the object is associated to the variable name, and the loop is continued till all the properties of the object are depleted.

Answer:

A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration.

Anonymous function declaration -
 

var anon = function() {
	alert('I am anonymous');
};
anon();

Answer:

The function .call() and .apply() are very similar in their usage except a little difference. .call() is used when the number of the function's arguments are known to the programmer, as they have to be mentioned as arguments in the call statement. On the other hand, .apply() is used when the number is not known. The function .apply() expects the argument to be an array.

The basic difference between .call() and .apply() is in the way arguments are passed to the function. Their usage can be illustrated by the given example.
 

var someObject = {
myProperty : 'Foo',

myMethod : function(prefix, postfix) {

	alert(prefix + this.myProperty + postfix);
}
};
someObject.myMethod('<', '>'); // alerts ''
var someOtherObject  = {

	myProperty : 'Bar'

};
someObject.myMethod.call(someOtherObject, '<', '>'); // alerts ''

someObject.myMethod.apply(someOtherObject, ['<', '>']); // alerts ''

Answer:

JavaScript allows DOM elements to be nested inside each other. In such a case, if the handler of the child is clicked, the handler of parent will also work as if it were clicked too.

Answer:

Yes, JavaScript is case sensitive. For example, a function parseInt is not same as the function Parseint.

Answer:

The 'And' Operator (&&), 'Or' Operator (||) and the 'Not' Operator (!) can be used in JavaScript.

*Operators are without the parenthesis.

Answer:

This can be done by including the name of the required frame in the hyperlink using the 'target' attribute.

>New Page
 

Answer:

Break statement is used to come out of the current loop while the continue statement continues the current loop with a new recurrence.

Answer:

Both web-garden and web-farm are web hosting systems. The only difference is that web-garden is a setup that includes many processors in a single server while web-farm is a larger setup that uses more than one server.

Answer:

Assigning properties to objects is done in the same way as a value is assigned to a variable. For example, a form object's action value is assigned as 'submit' in the following manner - Document.form.action="submit"

Answer:

This can be done by Using JavaScript extensions (runs from JavaScript Editor), example for opening of a file -

fh = fopen(getScriptPath(), 0);
 

Answer:

DOM stands for Document Object Model and is responsible for how various objects in a document interact with each other. DOM is required for developing web pages, which includes objects like paragraph, links, etc. These objects can be operated to include actions like add or delete. DOM is also required to add extra capabilities to a web page. On top of that, the use of API gives an advantage over other existing models.

Answer:

Events are the actions that result from activities, such as clicking a link or filling a form, by the user. An event handler is required to manage proper execution of all these events. Event handlers are an extra attribute of the object. This attribute includes event's name and the action taken if the event takes place.

Answer:

By default, the parsing of the HTML code, during page loading, is paused until the script has not stopped executing. It means, if the server is slow or the script is particularly heavy, then the webpage is displayed with a delay. While using Deferred, scripts delays execution of the script till the time HTML parser is running. This reduces the loading time of web pages and they get displayed faster.

Answer:

The different functional components in JavaScript are-

First-class functions: Functions in JavaScript are utilized as first class objects. This usually means that these functions can be passed as arguments to other functions, returned as values from other functions, assigned to variables or can also be stored in data structures.

Nested functions: The functions, which are defined inside other functions, are called Nested functions. They are called 'everytime' the main function is invoked.

Answer:

Screen objects are used to read the information from the client's screen. The properties of screen objects are -

  • AvailHeight: Gives the height of client's screen
  • AvailWidth: Gives the width of client's screen.
  • ColorDepth: Gives the bit depth of images on the client's screen
  • Height: Gives the total height of the client's screen, including the taskbar
  • Width: Gives the total width of the client's screen, including the taskbar

Answer:

This method is functional at the starting of the array, unlike the push(). It adds the desired number of elements to the top of an array.

var name = [ "john" ];
name.unshift( "charlie" );
name.unshift( "joseph", "Jane" );
console.log(name);
The output is shown below:
[" joseph "," Jane ", " charlie ", " john "]
 

Answer:

The escape () function is responsible for coding a string so as to make the transfer of the information from one computer to the other, across a network.

Output: Hello%3F%20How%20are%20you%21

The unescape() function is very important as it decodes the coded string.

It works in the following way. 
 

Output: Hello? How are you!

Answer:

EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is used to convert the encoded URL back to normal.

Output -

my%20test.asp?name=st%C3%A5le&car=saab

my test.asp?name=ståle&car=saab

Answer:

innerHTML content is refreshed every time and thus is slower. There is no scope for validation in innerHTML and, therefore, it is easier to insert rouge code in the document and, thus, make the web page unstable.

Answer:

ECMA Script are like rules and guideline while Javascript is a scripting language used for web development.

Answer:

Namespacing is used for grouping the desired functions, variables etc. under a unique name. It is a name that has been attached to the desired functions, objects and properties. This improves modularity in the coding and enables code reuse.

Answer:

In JavaScript, if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error var name is not defined and script will stop executing. However, if you use typeof undeclared_variable, then it will return undefined.

Before getting further into this, let's first understand the difference between declaration and definition.

Let's say var x is a declaration because you have not defined what value it holds yet, but you have declared its existence and the need for memory allocation.
 

var x; // declaring x
> console.log(x); //output: undefined 
 

Here var x = 1 is both a declaration and definition (also we can say we are doing an initialisation). In the example above, the declaration and assignment of value happen inline for variable x. In JavaScript, every variable or function declaration you bring to the top of its current scope is called hoisting.

The assignment happens in order, so when we try to access a variable that is declared but not defined yet, we will get the result undefined.
 

var x; // Declaration
if(typeof x === 'undefined') // Will return true

If a variable that is neither declared nor defined, when we try to reference such a variable we'd get the result not defined.
console.log(y);  // Output: ReferenceError: y is not defined
 

Answer:

One of the drawbacks of creating true private methods in JavaScript is that they are very memory-inefficient, as a new copy of the method would be created for each instance.

var Employee = function (name, company, salary) {
    this.name = name || "";       //Public attribute default value is null
    this.company = company || ""; //Public attribute default value is null
    this.salary = salary || 5000; //Public attribute default value is null

    // Private method
    var increaseSalary = function () {
        this.salary = this.salary + 1000;
    };

    // Public method
    this.dispalyIncreasedSalary = function() {
        increaseSlary();
        console.log(this.salary);
    };
};

// Create Employee class object
var emp1 = new Employee("John","Pluto",3000);
// Create Employee class object
var emp2 = new Employee("Merry","Pluto",2000);
// Create Employee class object
var emp3 = new Employee("Ren","Pluto",2500);

Here each instance variable emp1emp2emp3 has its own copy of the increaseSalary private method.

So, as a recommendation, don’t use private methods unless it’s necessary.

Answer:

The best way to find out whether or not an object is an instance of a particular class is to use the toString method from Object.prototype:

var arrayList = [1,2,3];

One of the best use cases of type-checking an object is when we do method overloading in JavaScript. For example, let's say we have a method called greet, which takes one single string and also a list of strings. To make our greet method workable in both situations, we need to know what kind of parameter is being passed. Is it a single value or a list of values?
function greet(param){
 	if(){ // here have to check whether param is array or not 
 	}else{
 	}
}

However, as the implementation above might not necessarily check the type for arrays, we can check for a single value string and put some array logic code in the else block.
function greet(param){
 	if(typeof param === 'string'){ 
 	}else{
 	  // If param is of type array then this block of code would execute
 	}
}


Now it's fine we can go with either of the aforementioned two implementations, but when we have a situation where the parameter can be single valuearray, and object type, we will be in trouble.

Coming back to checking the type of an object, as mentioned previously we can use
Object.prototype.toString
 

if( Object.prototype.toString.call( arrayList ) === '[object Array]' ) {
    console.log('Array!');
}

Answer:

In JavaScript, variable and functions are hoisted. Let's take function hoisting first. Basically, the JavaScript interpreter looks ahead to find all variable declarations and then hoists them to the top of the function where they're declared.

foo(); // Here foo is still undefined 
var foo = function foo(){ 
 	return 12; 
}; 
Behind the scene of the code above looks like this:
var foo = undefined;
    foo(); // Here foo is undefined 
 	   foo = function foo(){
 	      / Some code stuff
      }


var foo = undefined;
 	 foo = function foo(){
 	     / Some code stuff
    }
    foo(); // Now foo is defined here
 

Answer:

Both the Array() and [] work almost the same in JavaScript.If we use them as is (i.e. without any argument) to create an array object, then they will result in an array object of zero length. Even if we pass a string or a list of strings as arguments, the result will be similar.However, they differ when the input argument is of integer type. In that case, the statement will create an uninitialized array of size n. Whereas, the [n] statement will create an array of size 1 and assign n as the value of the first element.

Answer:

  • Class Inheritance: A constructor function instantiates an instance via the "new" keyword. This new instance inherits properties from a parent class.
  • Prototypal Inheritance: An instance is created by cloning an existing object that serves as a prototype. Instances are typically instantiated via factory functions, object literals, or Object.create(). Instances may be composed from many different source objects, allowing for easy selective inheritance.
 

Answer:

Every JavaScript function has a prototype property (by default this property is null), that is mainly used for implementing inheritance. We add methods and properties to a function's prototype so that it becomes available to instances of that function.

Answer:

This is a common practice used in many popular JavaScript libraries (jQuery, Node.js, etc.). It creates a closure around the entire contents of the file which makes a private namespace and thereby avoids potential name clashes between different JavaScript modules and libraries.

Answer:

A function is a piece of code that is called by name and it is not associated with any object, nor defined inside an object. It can be passed data to operate on (i.e. parameter) and can optionally return data (the return value).

/* Function definition*/
function myFunc() {
/* Do some stuff; */
}
myFunc();/* Calling the function */


A method is a piece of code that is called by name and is defined inside an object. It is almost identical to a function except that it is always associated with an object and operating only on data inside it.
 

var methodObject = {
attribute: "xyz",
display: function () { /* Method*/
console.log(this.attribute);
}
}methodObject.display(); /* Calling the method */
 

Answer:

A self-invoking anonymous function runs immediately when we define it and doesn't have a name. E.g.

(function() {
console.log("this will print automatically");
})();
 

Answer:

This may sound trivial and, in fact, it is trivial with ECMAscript 6 which introduces a new Number.isInteger() function for precisely this purpose. However, prior to ECMAScript 6, this is a bit more complicated, since no equivalent of the Number.isInteger() method is provided.

The issue is that, in the ECMAScript specification, integers only exist conceptually; i.e., numeric values are always stored as floating point values.

With that in mind, the simplest and cleanest pre-ECMAScript-6 solution (which is also sufficiently robust to return false even if a non-numeric value such as a string or null is passed to the function) would be the following use of the bitwise XOR operator:
 

function isInteger(x) { return (x ^ 0) === x; } 

The following solution would also work, although not as elegant as the one above:
function isInteger(x) { return (typeof x === 'number') && (x % 1 === 0); }

The following function (or with Math.ceil() or Math.floor() in place of Math.round()) might also seem useful, but the results are not exactly the same as with the above two functions:
function isInteger(x) { return Math.round(x) === x; }

The difference is, these Math-based solutions return true for Infinity and -Infinity, whereas the others (and notably ES6’s Number.isInteger()) return false.

Another fairly common incorrect solution is the following:
function isInteger(x) { return parseInt(x, 10) === x; }

While this parseInt-based approach will work well for many values of x, once x becomes quite large, it will fail to work properly. The problem is that parseInt() coerces its first parameter to a string before parsing digits. Therefore, once the number becomes sufficiently large, its string representation will be presented in exponential form (e.g., 1e+21). Accordingly, parseInt() will then try to parse 1e+21, but will stop parsing when it reaches the e character and will therefore return a value of 1. Observe:
 
String(1000000000000000000000)
'1e+21'
 parseInt(1000000000000000000000, 10)
1
 parseInt(1000000000000000000000, 10) === 1000000000000000000000
false
 

Answer:

var obj = {a: 1 ,b: 2}
var objclone = Object.assign({},obj);
 

Now the value of objclone is {a: 1 ,b: 2} but points to a different object than obj.

Note the potential pitfall, though: Object.clone() will just do a shallow copy, not a deep copy. This means that nested objects aren’t copied. They still refer to the same nested objects as the original:
 

let obj = {
    a: 1,
    b: 2,
    c: {
        age: 30
    }
};

var objclone = Object.assign({},obj);
console.log('objclone: ', objclone);

obj.c.age = 45;
console.log('After Change - obj: ', obj);           // 45 - This also changes
console.log('After Change - objclone: ', objclone); // 45
 

Answer:

var myArray = ['a', 'b', 'c', 'd'];
myArray.push('end');
myArray.unshift('start');
console.log(myArray); // ["start", "a", "b", "c", "d", "end"]

With ES6, one can use the spread operator:
 
myArray = ['start', ...myArray];
myArray = [...myArray, 'end'];

Or, in short:
 
myArray = ['start', ...myArray, 'end'];