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 && 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
What is the purpose of array splice method?
The splice() method is used either adds/removes items to/from an array, and then returns the removed item. The first argument specifies the array position for insertion or deletion whereas the option second argument indicates the number of elements to be deleted. Each additional argument is added to the array. Some of the examples of this method are,
let arrayIntegersOriginal1 = [1, 2, 3, 4, 5]; let arrayIntegersOriginal2 = [1, 2, 3, 4, 5]; let arrayIntegersOriginal3 = [1, 2, 3, 4, 5]; let arrayIntegers1 = arrayIntegersOriginal1.splice(0,2); // returns [1, 2]; original array: [3, 4, 5] let arrayIntegers2 = arrayIntegersOriginal2.splice(3); // returns [4, 5]; original array: [1, 2, 3] let arrayIntegers3 = arrayIntegersOriginal3.splice(3, 1, "a", "b", "c"); //returns [4]; original array: [1, 2, 3, "a", "b", "c", 5] |
Note: Splice method modifies the original array and returns the deleted array.
How do you compare Object and Map?
Objects are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Due to this reason, Objects have been used as Maps historically. But there are important differences that make using a Map preferable in certain cases.
- The keys of an Object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.
- The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion.
- You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.
- A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.
- An Object has a prototype, so there are default keys in the map that could collide with your keys if you’re not careful. As of ES5 this can be bypassed by using map = Object.create(null), but this is seldom done.
- A Map may perform better in scenarios involving frequent addition and removal of key pairs.
What are lambda or arrow functions?
An arrow function is a shorter syntax for a function expression and does not have its own this, arguments, super, or new.target. These function are best suited for non-method functions, and they cannot be used as constructors.
What is a first class function?
In Javascript, functions are first class objects. First-class functions means when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. For example, in the below example, handler functions assigned to a listener
const handler = () => console.log ( 'This is a click handler function' ); document.addEventListener ( 'click' , handler); |
What is a first order function?
First-order function is a function that doesn’t accept other function as an argument and doesn’t return a function as its return value.
const firstOrder = () => console.log ( 'Iam a first order functionn!' ); |
What is a higher order function?
Higher-order function is a function that accepts other function as an argument or returns a function as a return value.
const firstOrderFunc = () => console.log ( 'Hello I' am a First order function '); const higherOrder = ReturnFirstOrderFunc => ReturnFirstOrderFunc (); higherOrder (firstOrderFunc); |
What is a unary function?
Unary function (i.e. monadic) is a function that accepts exactly one argument. Let us take an example of unary function. It stands for single argument accepted by a function.
const unaryFunction = a => console.log (a + 10); //Add 10 to the given argument and display the value |
What is currying function?
Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. Currying is named after a mathematician Haskell Curry. By applying currying, a n-ary function turns it into a unary function. Let’s take an example of n-ary function and how it turns into a currying function
const multiArgFunction = (a, b, c) => a + b + c; const curryUnaryFunction = a => b => c => a + b + c; curryUnaryFunction (1); // returns a function: b => c => 1 + b + c curryUnaryFunction (1) (2); // returns a function: c => 3 + c curryUnaryFunction (1) (2) (3); // returns the number 6 Curried functions are great to improve code re-usability and functional composition. |
What is a callback hell?
Callback Hell is an anti-pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic. The callback hell looks like below,
async1( function (){ async2( function (){ async3( function (){ async4( function (){ .... }); }); }); }); |
What are server-sent events?
Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one way communications channel – events flow from server to client only. This is been used in Facebook/Twitter updates, stock price updates, news feeds etc.
How do you receive server-sent event notifications?
The EventSource object is used to receive server-sent event notifications. For example, you can receive messages from server as below,
if ( typeof (EventSource) !== "undefined" ) { var source = new EventSource( "sse_generator.js" ); source.onmessage = function (event) { document.getElementById( "output" ).innerHTML += event.data + "<br>" ; }; } |
How do you check browser support for server-sent events?
You can perform browser support for server-sent events before using it as below,
if ( typeof (EventSource) !== "undefined" ) { // Server-sent events supported. Let's have some code here! } else { // No server-sent events supported } |