Javascript

Generic Q&A

What is Javascript?

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.

What's the difference between undefined and not defined 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 the script will stop executing thereafter. But If you use typeof undeclared_variable then it will return undefined.

Explain event delegation

Event delegation allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent. That event listener analyzes bubbled events to find a match on child elements.

What is the drawback of declaring methods directly in JavaScript objects?

One of the drawback of declaring methods directly in JavaScript objects is that they are very memory inefficient. When you do that, a new copy of the method is created for each instance of an object.

What is “closure” in javascript?

A closure is a function defined inside another function (called parent function) and has access to the variable which is declared and defined in parent function scope.
The closure has access to the variable in three scopes:
  • Variable declared in his own scope
  • Variable declared in parent function scope
  • Variable declared in the global namespace

Syntax

What's the difference between undefined and not defined 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 the script will stop executing thereafter. But If you use typeof undeclared_variable then it will return undefined.

How to check if an object is an array or not?

var arrayList = [1 , 2, 3];
console.log( Object.prototype.toString.call(arrayList) === '[object Array]' ); // true
console.log( Array.isArray(arrayList) ); // also true...

What's the difference between typeof and instanceof?

typeof is an operator that returns a string with the type of whatever you pass.
The typeof operator checks if a value belongs to one of the seven basic types: number, string, boolean, object, function, undefined or Symbol.

typeof(null) will return object.

instanceof is much more intelligent: it works on the level of prototypes. In particular, it tests to see if the right operand appears anywhere in the prototype chain of the left. instanceof doesn’t work with primitive types. It instanceof operator checks the current object and returns true if the object is of the specified type, for example:

What's the difference between Function, Method and Constructor calls in JavaScript?

Function call simple usage:
function helloWorld(name) {
  return "hello world, " + name;
}

helloWorld("JS Geeks"); // "hello world JS Geeks"
Methods in JavaScript are nothing more than object properties that are functions:
var obj = {
  helloWorld : function() {
    return "hello world, " + this.name;
  },
  name: 'John Carter'
}
obj.helloWorld(); // // "hello world John Carter"
We can copy a reference to the same function helloWorld in another object and get a difference answer:
var obj2 = {
  helloWorld : obj.helloWorld,
  name: 'John Doe'
}
obj2.helloWorld(); // "hello world John Doe"
A constructor call new Employee('John Doe', 28) creates a brand new object and passes it as the value of this, and implicitly returns the new object as its result. The primary role of the constructor function is to initialize the object:
function Employee(name, age) {
  this.name = name;
  this.age = age;
}

var emp1 = new Employee('John Doe', 28);
emp1.name; // "John Doe"
emp1.age; // 28

What are the ways of creating objects in JavaScript?

Method 1: function based:

:
function Employee(fName, lName, age, salary){
  	this.firstName = fName;
  	this.lastName = lName;
  	this.age = age;
  	this.salary = salary;
  }

  // Creating multiple object which have similar property but diff value assigned to object property.
  var employee1 = new Employee('John', 'Moto', 24, '5000$');
  var employee1 = new Employee('Ryan', 'Jor', 26, '3000$');
  var employee1 = new Employee('Andre', 'Salt', 26, '4000$');

Mehod 2: Object Literal

Object Literal is best way to create an object and this is used frequently.
var employee = {
	name : 'Nishant',
	salary : 245678,
	getName : function(){
		return this.name;
	}
}
Nester Object Literal:
var employee = {
	name : 'Nishant',
	salary : 245678,
	address : {
		addressLine1 : 'BITS Pilani',
		addressLine2 : 'Vidya Vihar'.
		phoneNumber: {
		  workPhone: 7098889765,
		  homePhone: 1234567898
		}
	}
}

Method 3: From Object using new keyword

Object.create(obj) will create a new object and set the obj as its prototype. It’s a modern way to create objects that inherit properties from other objects. Object.create function doesn’t run the constructor. You can use Object.create(null) when you don’t want your object to inherit the properties of Object.

Write a function called deepClone which takes an object and creates a object copy of it.

function deepClone(object){
	var newObject = {};
	for(var key in object){
		if(typeof object[key] === 'object'  && object[key] !== null ){
		 newObject[key] = deepClone(object[key]);
		}else{
		 newObject[key] = object[key];
		}
	}
	return newObject;
}
var newObject = deepClone(obj);
Explanation: Let's understand in this way you have been given an object personalDetail this object contains some property which again a type of object here as you can see address is an object and phoneNumber in side an address is also an object. In simple term personalDetail is nested object(object inside object). So Here deep copy means we have to copy all the property of personalDetail object including nested object. So when we do deep clone then we should copy every property (including the nested object):
var personalDetail = {
	name : 'Nishant',
	address : {
	  location: 'xyz',
	  zip : '123456',
	  phoneNumber : {
	    homePhone: 8797912345,
	    workPhone : 1234509876
	  }
	}
}

What is IIFE (Immediately Invoked Function Expression) and how it can be useful?

IIFE a function that runs as soon as it's defined. Usually it's anonymous (doesn't have a function name), but it also can be named. Example:
(function() {
  console.log("Hi, I'm IIFE!");
})();
// outputs "Hi, I'm IIFE!"

PWAs: Progressive web apps

What are Service Workers and when can you use them?

It's a technology that allows your web application to use cached resources first, and provide default experience offline, before getting more data from the network later. This principle is commonly known as Offline First.

Service Workers actively use promises. A Service Worker has to be installed,activated and then it can react on fetch, push and sync events.

As of 2017, Service Workers are not supported in IE and Safari.

Programming paradigms

Can you name two important programming paradigms for JavaScript developers?

JavaScript is a multi-paradigm language, supporting imperative/procedural programming along with OOP (Object-Oriented Programming) and functional programming. JavaScript supports OOP with prototypal inheritance. See programming paradigms.

What is the difference between classical inheritance and prototypal inheritance?

Class Inheritance: instances inherit from classes (like a blueprint  - a description of the class), and create sub-class relationships: hierarchical class taxonomies. Instances are typically instantiated via constructor functions with the `new` keyword. Class inheritance may or may not use the `class` keyword from ES6.
Prototypal Inheritance: instances inherit directly from other objects. Instances are typically instantiated via factory functions or `Object.create()`. Instances may be composed from many different objects, allowing for easy selective inheritance.

What are the pros and cons of object-oriented programming?

OOP Pros:
  • It uses prototypical inheritance instead of classes
  • Modern JS: Typescript is easy to learn. ES6 is less intuitive instead.
OOP Cons in Javascript:
  • Prototypical inheritance is hard to learn
  • It does not have a keyword for 'private'
  • It abuses the keyword for 'this' making it unusable as a pointer to an object in many cases
  • It's hard to use for big projects. You have to use Typescript and\or ES6. They offer the possibility to use data structures like classes and interfaces.

When is classical inheritance an appropriate choice?

Rarely, almost never, or never.

What are the types of prototypal inheritance?

  • Delegation (i.e., the prototype chain).
  • Concatenative (i.e. mixins, 'Object.assign()').
  • Functional (Not to be confused with functional programming). A function used to create a closure for private state / encapsulation.

When is prototypal inheritance an appropriate choice?

Types of prototypal inheritance:
Prototypal inheritance can be good when:
  • In situations where modules or functional programming don't provide an obvious solution
  • When you need to compose objects from multiple sources.
  • Any time you need inheritance.

What does “favor object composition over class inheritance” mean?

Code reuse should be achieved by assembling smaller units of functionality into new objects instead of inheriting from classes and creating object taxonomies. Use can-do, has-a, or uses-a relationships instead of is-a relationships.

What are two-way data binding and one-way data flow, and how are they different?

Two way data binding means that UI fields are bound to model data dynamically such that when a UI field changes, the model data changes with it and vice-versa.

One way data flow means that the model is the single source of truth. Changes in the UI trigger messages that signal user intent to the model (or “store” in React). Only the model has the access to change the app’s state. The effect is that data always flows in a single direction, which makes it easier to understand.

One way data flows are deterministic, whereas two-way binding can cause side-effects which are harder to follow and understand.

React is the new canonical example of one-way data flow, so mentions of React are a good signal. Cycle.js is another popular implementation of uni-directional data flow.
Angular is a popular framework which uses two-way binding.

What are monolithic and microservice architectures?

Monolithic architecture means that your app is written as one cohesive unit of code whose components are designed to work together, sharing the same memory space and resources.

Microservice architecture: your app is made up of lots of smaller, independent applications capable of running in their own memory space and scaling independently from each other across potentially many separate machines.

Good to hear:
  • Positive attitudes toward microservices, despite the higher initial cost vs monolthic apps. Aware that microservices tend to perform and scale better in the long run.
  • Practical about microservices vs monolithic apps. Structure the app so that services are independent from each other at the code level, but easy to bundle together as a monolithic app in the beginning. Microservice overhead costs can be delayed until it becomes more practical to pay the price.

What is asynchronous programming, and why is it important in JavaScript?

Synchronous programming means that, barring conditionals and function calls, code is executed sequentially from top-to-bottom, blocking on long-running tasks such as network requests and disk I/O.

Asynchronous programming means that the engine runs in an event loop. When a blocking operation is needed, the request is started, and the code keeps running without blocking for the result. When the response is ready, an interrupt is fired, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations.

User interfaces are asynchronous by nature, and spend most of their time waiting for user input to interrupt the event loop and trigger event handlers.

Node is asynchronous by default, meaning that the server works in much the same way, waiting in a loop for a network request, and accepting more incoming requests while the first one is being handled.

This is important in JavaScript, because it is a very natural fit for user interface code, and very beneficial to performance on the server.

ES6

Define ES6 and mention the new features of ES6?

Refer the introduction part for definition of ES6. Below are the new features listed:
  • Constants (Immutable variables)
  • Scoping
  • Arrow functions
  • Extended parameter handling
  • Template literals
  • Extended literals
  • Modules
  • Classes
  • Enhanced Regular expressions
  • Enhanced object properties.
  • Destructuring Assignment
  • Symbol Type
  • Iterators
  • Generator
  • Map/Set & WeakMap/WeakSet
  • Typed Arrays
  • Built-in Methods
  • Promises
  • Metaprogramming
  • Internationalization and Localization.

How do you use ES6 or the best way to use ES6 in a project?

As it is mentioned that ES6 is not supported by all the browsers, so to use ES6 script we need to convert into the ES5 script which is supported by all the browsers. To convert into a pre-ES6 script, we required transpilers like Babel. Babel is a popular javascript transpiler used for this purpose, which allows ES-6 code to convert into an ES-5 script to support by all the browsers.

What are Constants in ES6?

Constants are also referred to as Immutable variable. It means that the value of a constant variable cannot be changed. The value that has been assigned at the time of declaration remains unchanged. For e.g. const X= 5.0, here the value of X remains 5 every time and it cannot be changed.

What are Block Scoped variables and functions?

The variables and function that are defined as indefinite blocks. It means these can be used where the variables and functions are defined or declared. If we have declared variable and function in any function block then their scope will be limit to that function only, they cannot be accessible outside the block/function. ‘Const’ keyword cannot change the value of a variable. ‘let’ keyword allows variable value to be re-assigned, it can be in for loop or arrays.

Explain briefly about Arrow functions?

Arrow functions support expressions bodies and statement bodies which returns the value of an expression and makes the syntax more expressive. Arrow functions have lexical ‘this’ feature as well. Arrow (=>) is used as part of the syntax. Lexical this is declared or defined where the function is written. It comes under the umbrella of lexical scope; lexical scope has access to variables which are in its parent scope.

Explain about Webpack and benefits of using Webpack?

Webpack is used to bundle javascript files that can be used in a browser. Webpack processes the application and builds a dependency graph to map each module of the project requirement and generated the bundles. It allows you to run that environment which has been hosted babel. The advantages of using web pack are that it bundles multiple modules and packs into single JavaScript file. It integrated the dev server which helps in updating code and asset management.

Explain about Default parameter values, Rest parameter, Spread operator?

Default parameter values are used to initialize the functions with default values. The value of a parameter can be anything like null value, number or function.
Rest parameter is used to retrieve all the arguments to invoke the function. It means we can push the items of different categories separately. Rest parameter uses the rest parameter to combine parameters into single array parameter.
A spread operator is donated by … and then the variable name has been provided. E.g. ‘…X’ syntax of spread operator. It has been used to manipulate objects and array in ES6 and to copy the enumerable properties from one object to another.

Explain about Internationalization and localization?

These are the APIs which are standard API of JavaScript that helps in different tasks like collation, Number formatting, Currency formatting, Date and time formatting. Collation: – It is used for searching within a set of strings and sorting a set of strings. It is parameterized by locale and aware of Unicode.
Number Formatting: Numbers can be formatted with localized separators and digit grouping. The other things that include are style formatting, numbering system, percent, and precision.
Currency formatting: Numbers can be formatted mainly with currency symbol, with localized separators and digit grouping.
Date and time formatting: it has been formatted with localized separators and ordering. The format can be short, long and other parameters like locale and time zone.

What is a Destructuring assignment and explain in brief?

This is the frequently asked ES6 Interview Questions which is asked in an interview. Destructuring assignment is used to bind the set of variable to the corresponding values. It mainly refers to the use of patterns to extract the parts of an object. A destructuring assignment has different forms like array matching, object matching, shorthand notation, object matching, deep matching, object and array matching, default values, parameter context matching and fail-soft destructuring. Some are explained as:
Array matching/object matching, shorthand notation/ object matching, deep matching: – It is intuitive and flexible of arrays into individual variables during an assignment.
Object and Array matching: – it is simple and defined default values for destructuring of objects and arrays.

Explain briefly about classes, modules and proxies?

Classes are based on the OOP style that is object-oriented programming. The class declaration makes the patterns easier to use. It supports inheritance, base class access, static methods, and constructors.
Modules: it defines the patterns from popular javascript module loaders. It supports for exporting or importing the values from or to modules without the global namespace. It supports marking the value as the default exported value and max-min values.
Proxies: It enables object creation with a wide variety of behaviors available to host objects. It can be used for logging, profiling, etc.