Google News
logo
JavaScript Interview Questions
JavaScript is the programming language of the Web. Javascript Most commonly used websites this is client-side script to interact with the user and make dynamic pages. All modern web browsers on desktops, tablets, and smart phones are using JavaScript.
The first JavaScript engine was created by Brendan Eich at Netscape, for the Netscape Navigator Web browser. The engine, code-named SpiderMonkey, is implemented in C. It has since been updated (in JavaScript 1.5) to conform to ECMAScript 3.
To create function in JavaScript, follow the following syntax :

<script type="text/javascript">
   function function_name(){
     //function body
   }
</script>
JavaScript uses reserved keyword var to declare a variable. A variable must have a unique name. You can assign a value to a variable using equal to (=) operator when you declare it or before using it.

There are two types of variables in JavaScript  :
 
1. local variables  : A variable that is declared inside of a function definition is called local variable and has scope to that function only. 
2.global variables :  A variable that is declared outside of a function definition is called a global variable and its scope is throughout your program means its value is accessible and modifiable throughout your program.

Basic Syntax :
var <variable-name>;
var <variable-name> = <value>;
JavaScript operators are used to assign values, compare values, arithmetic operations, and more. For example 1 + 2, where + sign is an operator and 1 is left operand and 2 is right operand. + operator adds two numeric values and produces a result which is 3 in this case.

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment  Operators
Following are the JavaScript Data types :

1. Primitive data type
2. Non-primitive (reference) data type

JavaScript has dynamic types. This means that the same variable can be used to hold different data types :
var x;     // Now x is undefined
var x = 10;     // Now x is a Number
var x = "Name";     // Now x is a String

Primitive data types : There are six types of primitive data types in JavaScript. They are as follows :
Number
String
Boolean
Null
Symbol
Undefined

Non-Primitive data types : The non-primitive data types are as follows :
Object
Array
RegExp
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.
‘this’ keyword refers to the object from where it was called.
The == operator checks equality only whereas === checks equality and data type i.e. value must be of same type.
The functionality of delete operator is used to delete all variables and objects in a program but it cannot delete variables declared with VAR keyword.
An alert box displays only one button which is the OK button.

But a Confirmation box displays two buttons namely OK and cancel.
There are 3 ways to create object in JavaScript.

By object literal
By creating instance of Object
By Object Constructor

Let's see a simple code to create object using object literal.

Ex : emp={id:100,name:"Free Time Learn",salary:45000} 
Client side JavaScript comprises the basic language and predefined objects which are relevant to running java script in a browser. The client side JavaScript is embedded directly by in the HTML pages. This script is interpreted by the browser at run time.

Server side JavaScript also resembles like client side java script. It has relevant java script which is to run in a server. The server side JavaScript are deployed only after compilation.
The cursor can be set to wait in JavaScript by using the property "cursor". The following example illustrates the usage : 

<script type="text/javascript">
   window.document.body.style.cursor = "wait"; 
</script>
A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered.
Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope.
JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current web page. 
The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this  :

Syntax  :  document.cookie = "key1 = value1; key2 = value2; expires = date";
His is very simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head 
Section as follows :
<head>
  <script type="text/javascript">
     window.location="http://www.newlocation.com";
  </script>
</head>
The onerror event handler provides three pieces of information to identify the exact nature of the error :

Error message : The same message that the browser would display for the given error.
URL : The file in which the error occurred.
Line number : The line number in the given URL that caused the error.
The common errors in JavaScript programming are the following : 

Spelling and typing errors.
Missing brackets or quotation marks.
Mismatching quotation marks.
Using single equal sign instead of double equal sign in comparison.
Referencing objects that does not exist.
Using reserved keywords for the variable naming.
Using the wrong type of brackets.
These are the main causes of these errors.

In JavaScript, there are the following three types of errors :

Syntax Error
Runtime Error
Logic Error
The encodeURI() function is used to encode a URI. This function encodes all special characters, except these < , / ? : @ & = + $ #>.

Example : 
var uri="http://www.freetimelearning.com/this is a educational website";
var encodedURI = encodeURI(uri);
console.log(encodedURI);

Output :
http://www.freetimelearning.com/this%20is%20a%20educational%20website
NaN property represents “Not-a-Number” value. It indicates a value which is not a legal number.
 
typeof of a NaN will return a Number .
 
To check if a value is NaN, we use the isNaN() function,

Note :  isNaN() function converts the given value to a Number type, and then equates to NaN.

isNaN("Hello")  // Returns true
isNaN(345)   // Returns false
isNaN('1')  // Returns false, since '1' is converted to Number type which results in 0 ( a number) 
isNaN(true) // Returns false, since true converted to Number type results in 1 ( a number)
isNaN(false) // Returns false
isNaN(undefined) // Returns true
Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.
 
Higher order functions are a result of functions being first-class citizens in javascript.
 
Examples of higher order functions :
 
function higherOrder(fn) {
  fn();
}
     
higherOrder(function() { console.log("Hello world") }); 
 
function higherOrder2() {
  return function() {
    return "Do something";
  }
}
        
var x = higherOrder2();
x()   // Returns "Do something"
Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.
Breaking within a string statement can be done by the use of a backslash, '\', at the end of the first line
 
Example :
document.write("This is \a program");
And if you change to a new line when not within a string statement, then javaScript ignores break in line.
 
Example:
var x=1, y=2,
z=
x+y;
The above code is perfectly fine, though not advisable as it hampers debugging.
<html> 
	<head> 
	<title>Adding New Elements</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>
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.
In JavaScript, the keyword ‘this’ refers to the object it belongs to and gives different values depending upon its usage.
 
For Example :
 
* In method – refers own object
* Alone – refers to the global object
* Function – undefined (in strict mode)
// for Single line comments and
 
/* Multi Line Comment */
'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.
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.
The delete keyword is used to delete the property as well as its value.
 
Example :
 
var student= {age:20, batch:"ABC"};
delete student.age;
Undefined value means the
 
* Variable used in the code doesn't exist
* Variable is not assigned to any value
* Property doesn't exist
The following code has to be inserted to achieve the desired effect:
 
<script language="JavaScript" type="text/javascript" >
   <!-- location.href="https://freetimelearning.com/javascript/index.php"; //-->
</script>
An alert box displays only one button which is the OK button.
 
But a Confirmation box displays two buttons namely OK and cancel.
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.
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
There are two types of data types in JavaScript. JavaScript, also known as ECMAScript specifies six primitive data types and object (or) non-primitive data types
 
1. Primitive data type
2. Non-primitive (reference) data type
 
JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

var x;     // Now x is undefined
var x = 10;     // Now x is a Number
var x = "Name";     // Now x is a String
Generic objects can be created as:
var I = new object();
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
}
Blur function is used to remove the focus from the specified object.
The 'Navigator.appversion' is used to find the name of the operating system in the client machine.
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.
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
Both are almost similar. JavaScript is developed by Netscape and Jscript was developed by Microsoft .
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";
}
This is an increasingly common practice, employed by many popular JavaScript libraries (jQuery, Node.js, etc.). This technique creates a closure around the entire contents of the file which, perhaps most importantly, creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries.
 
Another feature of this technique is to allow for an easily referenceable (presumably shorter) alias for a global variable. This is often used, for example, in jQuery plugins. jQuery allows you to disable the $ reference to the jQuery namespace, using jQuery.noConflict(). If this has been done, your code can still use $ employing this closure technique, as follows:
 
(function($) { /* jQuery plugin code referencing $ */ } )(jQuery);
DOM stands for Document Object Model is an interface (API) for HTML and XML documents. When the browser first reads (parses) our HTML document it creates a big object, a really big object based on the HTML document this is the DOM. It is a tree-like structure that is modeled from the HTML document. The DOM is used for interacting and modifying the DOM structure or specific Elements or Nodes.
 
<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Document Object Model</title>
</head>

<body>
   <div>
      <p>
         <span></span>
      </p>
      <label></label>
      <input>
   </div>
</body>

</html>
 
The document object in JavaScript represents the DOM. It provides us many methods that we can use to selecting elements to update element contents and many more.
The status can be acquired as follows  : 
 
alert(document.getElementById('checkbox1').checked);
 
If the CheckBox will be checked, this alert will return TRUE.
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.
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.
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();​
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.
The 'And' Operator (&&), 'Or' Operator (||) and the 'Not' Operator (!) can be used in JavaScript.
 
* Operators are without the parenthesis.
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.
Break statement is used to come out of the current loop while the continue statement continues the current loop with a new recurrence.
This can be done by Using JavaScript extensions (runs from JavaScript Editor), example for opening of a file -
 
fh = fopen(getScriptPath(), 0);
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.
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
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. For example :
 
var name = [ "free" ];
name.unshift( "time" );
name.unshift( "learning", "FTL" );
console.log(name);
 
The output is shown below:
 
[" free "," time ", " learning ", " FTL "]
EncodeURI() is used to convert URL into their hex coding. And DecodeURI() is used to convert the encoded URL back to normal.
 
<script>
	var url="my test.php?name=volkswagen&car=polo";

	document.write(encodeURI(url)+ "<br>");

	document.write(decodeURI(url));
</script>
 
Output:
 
my%20test.php?name=volkswagen&car=polo
my test.php?name=volkswagen&car=polo
The event.preventDefault() method prevents the default behavior of an element. If used in a form element it prevents it from submitting. If used in an anchor element it prevents it from navigating. If used in a contextmenu it prevents it from showing or displaying. While the event.stopPropagation() method stops the propogation of an event or it stops the event from occurring in the bubbling or capturing phase.
We can use the event.defaultPrevented property in the event object. It returns a boolean indicating if the event.preventDefault() was called in a particular element.
const falsyValues = ['', 0, null, undefined, NaN, false];
falsy values are values that when converted to boolean becomes false.
A prototype in simplest terms is a blueprint of an object. It is used as a fallback for properties and methods if it does exist in the current object. It's the way to share properties and functionality between objects. It's the core concept around JavaScript's Prototypal Inheritance.

  const o = {};
  console.log(o.toString()); // logs [object Object] 
 
Even though the o.toString method does not exist in the o object it does not throw an error instead returns a string [object Object]. When a property does not exist in the object it looks into its prototype and if it still does not exist it looks into the prototype's prototype and so on until it finds a property with the same in the Prototype Chain. The end of the Prototype Chain is the Object.prototype.

   console.log(o.toString === Object.prototype.toString); // logs true
   // which means we we're looking up the Prototype Chain and it reached 
   // the Object.prototype and used the "toString" method.
The apply invokes a function specifying the this or the "owner" object of that function on that time of invocation.

const details = {
  message: 'Hello World!'
};

function getMessage(){
  return this.message;
}
getMessage.apply(details); // returns 'Hello World!'
 
 
This method works like Function.prototype.call the only difference is how we pass arguments. In apply we pass arguments as an array.

const person = {
  name: "Marko Polo"
};

function greeting(greetingMessage) {
  return `${greetingMessage} ${this.name}`;
}

greeting.apply(person, ['Hello']); // returns "Hello Marko Polo!"
The call invokes a function specifying the this or the "owner" object of that function on that time of invocation.
const details = {
  message: 'Hello World!'
};

function getMessage(){
  return this.message;
}

getMessage.call(details); // returns 'Hello World!'

This method works like Function.prototype.apply the only difference is how we pass arguments. In call we pass directly the arguments separating them with a comma , for every argument.

const person = {
  name: "Marko Polo"
};

function greeting(greetingMessage) {
  return `${greetingMessage} ${this.name}`;
}

greeting.call(person, 'Hello'); // returns "Hello Marko Polo!"
It is not a jQuery feature but a feature for debugging purposes used by developers. It is used to writes a message to the console.
 
console.log() accepts a parameter which can be an object, an array or any message.
 
Syntax : console.log(name); // here name is object, an array or variable.
 
Example :
                                                    
$('#form').submit(function() {

     console.log(‘Your form is submitted successfully!’);

     // do something

}); 
It is a client side technology, it is mainly used for gives client side validation, but it have lot of features which are given below;
 
* It is an object-based scripting language.
* It helps the user more control over the browser.
* JavaScript Handling dates and time also.
* It also helps to Detect the client's browser and Operating System.
* JavaScript is light weighted & case sensitive.
* All most JavaScript control statements syntax is same as syntax of control statements in C programming language.
The export statement is used when creating modules for JavaScript to export functions, primitive values or objects from the blades so they can be used by the programs with import statement which works opposite to it.
 
The import statement is used when we import buildings which are exported by another module. All imported modules are in strict mode. This statement can’t be used in embedded scripts.
To perform a character count in JavaScript, use the following syntax:
 
var str = "Hello World!";

var n = str.length;
Generally, the page title varies based on the HTML document and the element structure. We can give id to an element and use code:
 
document.getElementById(‘page-title-id’).innerHTML=NewTitle;
Yes, it is possible to redirect a page to another page or URL using JavaScript by using location, replace, and location.assign.
The concept of hoisting stands for uplifting the variable and functions on the top of their scope before the code execution takes place. In the JavaScript mechanism, no matter wherever the functions are declared, they are taken on the topmost position, immaterial of their scope (global or local).
To submit a simple form, the below code will work.
 
document.form[0].submit();
BOM stands for Browser Object Model, a more extensive representation of elements provided by the browser like document, location, history, and frames exposed to JavaScript. DOM is a part of BOM, and to access the document, one can use code document or window.document.
Whenever somebody wants to reuse solutions for regularly occurring problems in software designing, Design Patterns will solve the purpose.
 
Latest Design Patterns in JS are :
 
* Module Design pattern
* Revealing Module pattern
* Prototype Design pattern
* Revealing Prototype pattern
* Observer Design pattern
* Singleton
Deep Coping : This means that all the values of the existing/original variables are copied to a new variable, and thus, disconnected from the existing variables.

Shallow Coping : When commanded for shallow coping, not all the existing variables are disconnected, and some of the values or sub-values are still connected to the original.
A cookie is a set of data saved on the computer and accessed by the browser.
 
Step to create a JavaScript cookie :
 
document.cookie = “cookiename=Ftl”; expires = date”;
Fibonacci series is a pattern in which each given value is the sum of the previous two, and it starts with 0,1.
 
Method :
 
* use function fib(n),
* Declare var a=0 and b=1
* Use this condition (var i=0; i<n; i++)
* Use var temp = a+b;
* Next make a=b
* And b=temp;
* }
* Return a;

The series will come like 0,1,1,2,3,5…
To append an element in a JavaScript array, we use push(), and to remove an array, pop() is used.
 
Syntax :
array.push(item1, item2, …, itemX)
We can add a property to an object by using :
object.property_name =value
To delete a property, we can use :
object.property_name
Example :
 
   let user = new Object();

    // adding a property

    user.name=’ftl’;

    user.age  =22;

    console.log(user);

    delete user.age;
Syntax :
 
var arr1 = [1,2,3]
var arr2 = [4,5,6,7]
var mergedArrays = […arr1, …arr2]
document.write(‘Merged arrays’, mergedArrays)
Currying is a method of evaluating the function with many arguments, into a sequence of function with a single argument. Currying helps you to avoid spending the same variable again and again. It helps to create a larger order function
When it comes to inheritance, JavaScript simply has one construct: objects. Each object has a separate property which operates a link to another object called its model. That prototype object has a prototype of its individual, and so on until an object is terminated with null as its prototype.
The onabort event is executed when the loading of an image is aborted. Use it in an image tag like this:
 
<img src="demo_image.jpg" onabort="display()">

Here, you can display an alert when the loading of image aborts : 
 
function abortFunc()
{
  alert('Image isn’t loading!');
}
Logic errors occur when there is a mistake in the logic. This can lead your script to work inappropriately to give unexpected results.
The blur event triggers when object loses focus. An example here displays that we write a name in the textbox and then when the object loses focus, the text color is changed. This happens since the blur event triggers when the focus ends: 
 
<!DOCTYPE html>
<html>
  <body>
  <h2>Testing</h2>
  <input type="text" onblur="display(this)">
    <script>
         function display(z) {
         z.style.color = "green";
       }
    </script>
  </body>
</html> 
When a visitor leaves the web page, then the onpagehide event triggers. The visitor can move to another page or click a link after leaving the current web page. An example here displays an alert box when the user tries to leave the page. This happens since onpagehide event fires when the page is left : 
 
<!DOCTYPE html>
<html>
	<body onpagehide="display()">
	  <p>Close the page</p>
	  <script>
	     function display() {
    	     alert("It was nice having you here!");
	    }
	  </script>
	</body>
</html>
Advertisement