JavaScript Interview questions and answers

Set 2

1.What are Boolean operators in JavaScript.

Boolean operator in JavaScript return true and False based on a condition.

  • && (and)
  • ||(or)
  • ! (not)

2.What is JSON and use of JSON.stringify() in JavaScript

whenever we have to exchange data from browser to server it should in text only. JSON is a text, so we convert any JavaScript object into JSON and send it to server.

JSON.Stringify() convert object or values to JSON string.

console.log(JSON.stringify({ name: 'Rsack', age: 26 }));

Output

{"name":"Rsack","age":26}

3. Ways to redirect user to new page in JavaScript

//one way
window.location.replace('http://www.xyz.com')
//Second way
window.location.assign('http://www.xyz.com')
//Third way
window.location.href = 'http://www.xyz.com'


4.What are a window object and its methods in JavaScript.

The Window object is use to represent the current open browser window.

Methods of window Object

  • window.alert(): It’s open an alert box with Message and OK button.
  • window.confirm(): It displays a dialog box with a message with OK and cancel button.
  • window.pop(): It takes input from the user.
  • window.blur():Remove the focus from current item.

5.How to print the content of the current window in JavaScript

The window.print() method is use to print the content of the current window. It does not have any parameter value. It opens the Print Dialog to print the current document.

6.What the use of history object in JavaScript.

JavaScript window. history object contains the collection of URL visited by the user as an array and maintain browser history. We can use to load previous, forward, and any page.

  • forward(): The forward() method loads the next page.
  • back(): It loads the previous page.
  • go(): It loads based on the page number passed.

7.Explain the difference between firstChild and firstElementChild?

firstchild

We use it to return the first child node as an element node,text node or comment node, even space.

firstElementChild

IT returns an HTML element only.(ignore text and comment node). How to create a dynamic Html element in JavaScript.

document.createElement() : method create new element.

document.body.appendChild(): append element in parent element.

    childdiv = document.createElement('div');   
    childdiv.id = 'divchild';          //set ID of new element       
    document.body.appendChild(childdiv);

8.Explain different between NodeList and HTMLCollection

NodeList and HTMLCollection are collections of DOM nodes.

HTMLCollection

  • The element methods in javascript getElementsByClassName()  and getElementsByTagName() return a live HTMLCollection. It contain collection of node elements(Element in HTMLcollection is one special type of node. It can be a list item, div, the body, the window).
  • It returns the matching element with (classname ,tagname). It does not contain the text node.
  • It has two methods item(),namedItem()
  • We can’t use a for-each loop to traverse HTMLCollection elements.

NodeList

  • Accessing Nodelist using the querySelectorAll() method returns a static(not live) NodeList contain a list of the document’s elements that matches the specified group of selectors.
  • It has these methods item(), entries(), keys(), and values().
  • Accessing the Nodelist by childNodes return the live NodeList.
  • Foreach loop uses to traverse the NodeList elements.

9.What is the difference between childNode and children?

childNode

The childNodes property of Node is used to returns a NodeList. It is access based on the index. The first element start from index 0.

children

It is the property of an element. Only elements have children. it is used to return an HTML collection.

10.How we can iterate over the HTMLCollection.

We cant use a for-each loop directly on HTMLCollection.First, need to convert into an array then traverse using for-each loop

 let Html_collection = document.getElementsByTagName(".color"); 
  
    
        for (Element of Html_collection) { 
            console.log(Element); 
        } 

11.How to get the total number of arguments that are passed to a function in JavaScript.

function arg(a,b,c,d,e){
  console.log('argument length =',arguments.length);
};

arg(10,20,30,40,50)

//Output

argument length = 5

12.What is a self-executing function in JavaScript give example?

Self executing anonymous function also know as IIFE (Immediately Invoked Function Expression).It execute immediately after define.

The self-executing anonymous function used to manage the scope of variables. All the variables defined in the self-executing anonymous function has scope inside the self-executing function only, not outside the function.

(function(){
  console.log('good morning!');
})();

//Output
Good Morning!

The above code consist of two part

First part, as shown below is anonymous function.

(function(){
  //code write here
})

Second Part These brackets-(); makes everything inside the parentheses({}) to execute immediately.

//brackets 
();

13.Different ways to include JavaScript code in HTML.

In JavaScript we have 3 ways to include JavaScript code in HTML

  • Inline
  • Internal
  • External

14. Different Ways to access an HTML element in JavaScript.

These are the ways how an HTML element can be access in JavaScript

  • getElementById(‘id’): we pass the ID of element to access an single element based on ID.
  • getElementsByClass(‘classname’): It access all the element that have given classname.
  • getElementsByTagName(‘tagname’): It accesses all the elements that have given tag name.
  • querySelector(): It takes the CSS Style Selector (#id/.classname/tagname) and returns the first selected element.
  • querySelectorAll(): It is work like querySelector, this function returns a NodeList of html elements.

15. What is different between attribute and property

When a web page loads in the browser it creates a DOM object. DOM contain HTML element as object,their property,method,element. DOM defines the standard for accessing, modifying, adding, or deleting HTML elements.

Attribute

  • Attributes are defined by HTML, provide more details of an element like id, type, value.
  • Attribute mainly use to initialize the DOM properties.
  • The attribute value is never changed
  • Some attributes id, class contain only one value in DOM. Where checked, selected contain two values in DOM

Property

  • Property defines by the DOM
  • Property defines characteristics of an object
  • Property is like type=” text”, value=’Name’ etc.
  • We can change the Property values.

16.How to check checkbox is checked in JavaScript

var chkbox = window.document.getElementById("chkcity").checked;

17.What different between InneText and Inner-html,text Content.

innerText: It gets or sets the text content of the specified node all it’s descendant.

<p id="pagexp">
<br>
<label for="name">Here is the Javascript example</label>
   this is <span>span</span> tag
  <br />
</p>
//Javascript code
let pag = document.getElementById('pagexp');
console.log(pag.innerText)

Output

Here is the Javascript example this is span tag

Inner html:It set or get plain text along HTML contents of an element.It parse the content into HTML.

<p id="pagexp">
<br>
<label for="name">Here is the Javascript example</label>
   this is <span>span</span> tag
  <br />
</p>
//JavaScript Code
let pag = document.getElementById('pagexp');
console.log(pag.innerHTML)

Output

"<br>
<label for=name>                                                                                                                                                  Here is the Javascript example </label>;
   this is <span>span<span/> tag
<b> "

text Content: It is plain text return by an element and all its children, it is for formatting purposes only. Its return plain text does not parse HTML and is faster.

<p id="pagexp">
<br>
<label for="name">Here is the Javascript example</label>
   this is <span>span</span> tag
  <br />
</p>
//JavaScript Code
let pag = document.getElementById('pagexp');
console.log(pag.textContent)

Output

"

Here is the Javascript example
   this is span tag
  
"

18.What are all ways to create object in JavaScript.

Object constructor:It is easiest Way to create object.It is not suggested way

var animal = new Object();

Create Method :Another way to create object in JS using Create() Method by pass object prototype.

var animal = new Object();

Object Literal:Object literal behave as create method if pass ‘null’ as parameter.

var animal = new Object();

function constructor: In this case, we create a function,use new to create its object.

function animal(name){
   var anm_detail = {};
   anm_detail.name=name;
   
   return anm_detail;
}
var object = new animal("Dog");
console.log(object) 

Output

{ name: 'Dog' }

Class Syntax:It is introduce in ES6(2015).First create a class and then use new to create object

class Animal{
   constructor(animalname) {
      this.animalname= animalname;
   }
}

var object = new Animal("Dog");
console.log(object) 

//Output:Animal { animalname: 'Dog' }

19.What is ECMAScript

The full form of ECMA is the European Computer Manufacturer’s Association.ECMAScript is often short known as ES.ECMAScript presents the rules, details, and guidelines that a scripting language(Javascript, Actionscript, JScript), etc must use to be considered ECMAScript compliant. All specifications are defined in ES-262 and mention how to use and code any scripting language.

When many browses started programming in a scripting language, all have their own rules to write code or any implementation that created a huge confusion and mismatch. ECMAScript comes with standard rules to code in a scripting language includes Javascript, Actionscript, JScript.

20.What is different between call(),Apply(),Bind()

The Call(),Apply(),Bind() are use in context of Object.But they are used with basic function too.We use Call() and Apply() to call the function Imediately.Whereas bind() return a function and it execute later.

Call(): Call() calls the function with (this or custom object) as the first parameter and arguments pass one by one.

Syntax

//function
add(param1, param2,parar3...);

with call()
call.add(this,param1,param2,param3)

Example

var obj_animal = {name:"Dog"};
function dogaction(walk,jump,where){
    console.log(this.name + ' ' +walk + ' ' +jump+' '+where);
};


dogaction.call(obj_animal, 'walk', 'jump','over bed');

Output

Dog walk jump over bed

Apply():It work same as Call() except it allow pass the arguments as an Array

Syntax

//function
add([param1, param2,parar3...]);

with apply()
apply.add(this,[param1,param2,param3])

Example

var obj_animal = {name:"Dog"};
function dogaction(walk,jump,where){
    console.log(this.name + ' ' +walk + ' ' +jump+' '+where);
};


dogaction.apply(obj_animal, ['walk', 'jump','over bed']);


Output

Dog walk jump over bed

Bind(): It returns a function that does not run immediately and allows us to pass a number of arguments. Return function execute later.

var obj_animal = {name:"Dog"};
function dogaction(walk,jump,where){
    console.log(this.name + ' ' +walk + ' ' +jump+' '+where);
};

var animal = dogaction.bind(obj_animal);
animal('walk', 'jump','over bed'); 

Output

Dog walk jump over bed

21. What is closure in JavaScript why it is useful.

A Closure is a combination of function bundle(enclosed) together with reference to their scope or in simple word, closure is a mechanism where the inner function can access the outer function(enclosed)’s variables. Every time we create a function Closure is created.

Scope of closure

  • It has its own scope within {}.
  • It can access the outer function variable
  • It can access global variables.
function out_fun(num) {
   
   return function in_func(num1) 
   {
        
         return num+num1;
    };
   
}
var sum = out_fun(6);
console.log(sum(7))
//Output
13

22.What is MAP in JavaScript with Example.

Follow this for all about the Map JavaScript in introduce in ES6.

23.What is the Difference Between Map and Object in Javascript?

Difference in both.

24.What is object Prototype in JavaScript give example.

Object Prototype is the technique by which javascript objects inherit features from another object. The prototype is a blue-print(base class) of an object. The prototype used as an alternative if property or method does not exist in Object.

const animal = {name:'Dog',Age:34}
console.log(Object.keys(animal));
console.log(animal.toString());

//Output
[ 'name', 'Age' ]
[object Object]

In this example above, we did not define toString() methods but when we are calling is it returning [object object] from Object. Prototype and same for Object.Prototype.Object.keys() method does not exist but inherited from the Prototype.

25.What are Rest Parameters and Spread operator in JavaScript with example

Rest parameter and Spread operator in JavaScript

26.How to pass a default value to JavaScript function arguments? give an example

To pass default values to Javascript function argument we need to use default function parameters.it introduced in ES6.

27.What is this operator in JavaScript with example.

this refers to the object it belongs to. The value of this operator decide during run-time on which object or function it is executing. So the value of this operator changes depend on Object or function we use it.

In function or class it this operator refer to Owner Object

here is the example

const animal = {
      name: "Pet Dog",
     age: 7,
     returnname(){
        return this.name;
     }
     
     
   };

   console.log(animal.returnname());
//Output: Pet Dog

Outside of function it refer to Global object

console.log(this === window);

var a = 40;
console.log(this.a == window.a); 
console.log(`Gloabl object and this have same value\n gloabl object = ${window.a},this = ${this.a}`)

//Output:
//true
//true
//"Gloabl object and this have same value
 gloabl object = 40,this = 40"

28.What are framework based on the JavaScript

  • Angular
  • React
  • Vue.

29. Give an example of removing special elements from an Array In JavaScript.

We use array function to remove specific element form array

30. What are the Numeric constant represent min and max values in Javascript.

Number.MAX_VALUE : for max value
Number.MIN_VALUE: for min value