window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-63172957-1');
Sound
Awwwards
</html>
Created by potrace 1.16, written by Peter Selinger 2001-2019
Back to blog
JavaScript

Javascript Interview Questions & Answers (Part 1)

Article index:

What are the possible ways to create objects in JavaScript?

There are many ways to create objects in javascript as below,

Object constructor:

The simplest way to create an empty object is using Object constructor. Currently this approach is not recommended.

var object = new Object();

Object’s create method:

The create method of Object creates a new object by passing the prototype object as a parameter

var object = Object.create(null);

Object literal syntax:

The object literal syntax is equivalent to create method when it passes null as parameter

var object = {};

Function constructor:

Create any function and apply the new operator to create object instances,

function Person(name){
var object = {};
object.name=name;
object.age=21;
return object;
}
var object = new Person("Sudheer");

Function constructor with prototype:

This is similar to function constructor but it uses prototype for their properties and methods,

function Person(){}
Person.prototype.name = "Sudheer";
var object = new Person();

This is equivalent to an instance created with an object create method with a function prototype and then call that function with an instance and parameters as arguments.

function func {};

new func(x, y, z);

/*(OR)*/

// Create a new instance using function prototype.
var newInstance = Object.create(func.prototype)

// Call the function
var result = func.call(newInstance, x, y, z),

// If the result is a non-null object then use it otherwise just use the new instance.
console.log(result &amp;amp;amp;&amp;amp;amp; typeof result === 'object' ? result : newInstance);

ES6 Class syntax

ES6 introduces class feature to create the objects

class Person {
constructor(name) {
this.name = name;
}
}

var object = new Person("Sudheer");

Singleton pattern

A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance and this way one can ensure that they don’t accidentally create multiple instances.

var object = new function(){
this.name = "Sudheer";
}

What is prototype chain?

Prototype chaining is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language. The prototype on object instance is available through Object.getPrototypeOf(object) or proto property whereas prototype on constructors function is available through object.prototype.

What is the difference between Call, Apply and Bind?

The difference between Call, Apply and Bind can be explained with below examples:

Call: The call() method invokes a function with a given this value and arguments provided one by one


var employee1 = {firstName: 'John', lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};

function invite(greeting1, greeting2) {
console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}

invite.call(employee1, 'Hello', 'How are you?');
invite.call(employee2, 'Hello', 'How are you?');

Apply: Invokes the function and allows you to pass in arguments as an array

var employee1 = {firstName: 'John', lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};

function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}

invite.apply(employee1, ['Hello', 'How are you?']); // Hello John Rodson, How are you?
invite.apply(employee2, ['Hello', 'How are you?']); // Hello Jimmy Baily, How are you?

bind: returns a new function, allowing you to pass in an array and any number of arguments

var employee1 = {firstName: 'John', lastName: 'Rodson'};
var employee2 = {firstName: 'Jimmy', lastName: 'Baily'};

function invite(greeting1, greeting2) {
    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);
}

var inviteEmployee1 = invite.bind(employee1);
var inviteEmployee2 = invite.bind(employee2);
inviteEmployee1('Hello', 'How are you?'); // Hello John Rodson, How are you?
inviteEmployee2('Hello', 'How are you?'); // Hello Jimmy Baily, How are you?

Call and apply are pretty interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to send in an array or a comma separated list of arguments. You can remember by treating Call is for comma (separated list) and Apply is for Array. Whereas Bind creates a new function that will have this set to the first parameter passed to bind().

What is JSON and its common operations?

JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. It is useful when you want to transmit data across a network and it is basically just a text file with an extension of .json, and a MIME type of application/json Parsing: **Converting a string to a native object

JSON.parse(text)

Stringification: **converting a native object to a string so it can be transmitted across the network

JSON.stringify(object)

 

What is the purpose of array slice method?

The slice() method returns the selected elements in an array as a new array object. It selects the elements starting at the given start argument, and ends at the given optional end argument without including the last element. If you omit the second argument then it selects till the end. Some of the examples of this method are,

let arrayIntegers = [1, 2, 3, 4, 5];
let arrayIntegers1 = arrayIntegers.slice(0,2); // returns [1,2]
let arrayIntegers2 = arrayIntegers.slice(2,3); // returns [3]
let arrayIntegers3 = arrayIntegers.slice(4); //returns [5]

Note: Slice method won’t mutate the original array but it returns the subset as new array.

What is the purpose of isFinite function?

The isFinite() function is used to determine whether a number is a finite, legal number. It returns false if the value is +infinity, -infinity, or NaN (Not-a-Number), otherwise it returns true.

isFinite(Infinity);  // false
isFinite(NaN);       // false
isFinite(-Infinity); // false

isFinite(100);         // true

What is an event flow?

Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event each of its parent elements first, starting at the top with the global window object. There are two ways of event flow

  • Top to Bottom(Event Capturing)
  • Bottom to Top (Event Bubbling)

What is event bubbling?

Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element.

What is event capturing?

Event bubbling is a type of event propagation where the event is first captured by the outermost element and , and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the inner DOM element.

How do you submit a form using JavaScript?

You can submit a form using JavaScript use document.form[0].submit(). All the form input’s information is submitted using onsubmit event handler

function submit() {
    document.form[0].submit();
}

How do you find operating system details?

The window.navigator object contains information about the visitor’s browser os details. Some of the OS properties are avaialble under platform property,

console.log(navigator.platform);

What is the difference between document load and DOMContentLoaded events?

The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets(stylesheets, images, and subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources(stylesheets, images)

What is the difference between native, host and user objects?

Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification. For example, String, Math, RegExp, Object, Function etc core objects defined in the ECMAScript spec. Host objects are objects provided by the browser or runtime environment (Node). For example, window, XmlHttpRequest, DOM nodes etc considered as host objects. User objects are objects defined in the javascript code. For example, User object created for profile information.

What are the tools or techniques used for debugging JavaScript code?

You can use below tools or techniques for debugging javascript

  • Chrome Devtools
  • debugger statement
  • Good old console.log statement

What are the pros and cons of promises over callbacks?

Below are the list of pros and cons of promises over callbacks

Pros:

  • It avoids callback hell which is unreadable
  • Easy to write sequential asynchronous code with .then()
  • Easy to write parallel asynchronous code with Promise.all()
  • Solves some of the common problems of callbacks(call the callback too late, too early, many times and swallow errors/exceptions)

Cons:

  • It makes little complex code
  • You need to load a polyfill if ES6 is not supported


Back to blog

</html>
Wordpress Developer Loader, Web Developer Loader , Front End Developer Loader Jack is thinking