javascript questions Flashcards
What are the possible ways to create objects in JavaScript
There are many ways to create objects in javascript as below
1.Object constructor:
The simplest way to create an empty object is using the Object constructor. Currently this approach is not recommended.
var object = new Object();
2.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);
3.Object literal syntax:
The object literal syntax is equivalent to create method when it passes null as parameter
var object = {};
4.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");
5.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);
6.ES6 Class syntax:
ES6 introduces class feature to create the objects
class Person { constructor(name) { this.name = name; } }
var object = new Person(“Sudheer”);
7.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 a 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.
What is the difference between Call, Apply and Bind
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?’); // Hello John Rodson, How are you?
invite. call(employee2, ‘Hello’, ‘How are you?’); // Hello Jimmy Baily, How are you?
Apply: Invokes the function with a given this value 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 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?
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 the 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 a new array.
What is the purpose of the 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 optional 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.
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 functions are best suited for non-method functions, and they cannot be used as constructors.
What is a first order function
First-order function is a function that doesn’t accept another function as an argument and doesn’t return a function as its return value.
What is a higher order function
Higher-order function is a function that accepts another function as an argument or returns a function as a return value or both.
What is a unary function
Unary function (i.e. monadic) is a function that accepts exactly one argument. It stands for a single argument accepted by a function.
What is the 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 the mathematician Haskell Curry. By applying currying, a n-ary function turns it into a unary function.
const multiArgFunction = (a, b, c) => a + b + c; console.log(multiArgFunction(1,2,3));// 6
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 reusability and functional composition.
What is a pure function?
A Pure function is a function where the return value is only determined by its arguments without any side effects. i.e, If you call a function with the same arguments ‘n’ number of times and ‘n’ number of places in the application then it will always return the same value.
//Impure let numberArray = []; const impureAddNumber = number => numberArray.push(number);
//Pure const pureAddNumber = number => argNumberArray => argNumberArray.concat([number]);
//Display the results
console. log (impureAddNumber(6)); // returns 1
console. log (numberArray); // returns [6]
console. log (pureAddNumber(7) (numberArray)); // returns [6, 7]
console. log (numberArray); // returns [6]
Push function is impure itself by altering the array and returning an push number index which is independent of parameter value. Whereas Concat on the other hand takes the array and concatenates it with the other array producing a whole new array without side effects. Also, the return value is a concatenation of the previous array.
What is the purpose of the let keyword
The let statement declares a block scope local variable. Hence the variables defined with let keyword are limited in scope to the block, statement, or expression on which it is used. Whereas variables declared with the var keyword used to define a variable globally, or locally to an entire function regardless of block scope.
let counter = 30; if (counter === 30) { let counter = 31; console.log(counter); // 31 } console.log(counter); // 30
How do you redeclare variables in switch block without an error
let counter = 1; switch(x) { case 0: { //use curry braces let name; break; } case 1: { let name; // No SyntaxError for redeclaration. break; } }
What is IIFE(Immediately Invoked Function Expression)
IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The signature of it would be as below,
(function () { // logic here } ) ();
The primary reason to use an IIFE is to obtain data privacy because any variables declared within the IIFE cannot be accessed by the outside world. i.e, If you try to access variables with IIFE then it throws an error as below,
(function () { var message = "IIFE"; console.log(message); } ) (); console.log(message); //Error: message is not defined
What is the benefit of using modules
There are a lot of benefits to using modules in favour of a sprawling. Some of the benefits are,
Maintainability
Reusability
Namespacing
What is Hoisting
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Remember that JavaScript only hoists declarations, not initialisation.
What are classes in ES6
In ES6, Javascript classes are primarily syntactic sugar over JavaScript’s existing prototype-based inheritance. For example, the prototype based inheritance written in function expression as below,
function Bike(model,color) { this.model = model; this.color = color; }
Bike.prototype.getDetails = function() {
return this.model + ‘ bike has’ + this.color + ‘ color’;
};
Whereas ES6 classes can be defined as an alternative
class Bike{ constructor(color, model) { this.color= color; this.model= model; }
getDetails() {
return this.model + ‘ bike has’ + this.color + ‘ color’;
}
}
What are closures
A Closure gives a function access to all the variables of its parent function even after the parent function has returned. The function keeps a reference to its outer scope which preserves the scope chain throughout time.
A closure makes sure that a function doesn’t loose connection to variables that existed at the function’s birth place even if that function is gone.
const secureBooking = function () { let passengerCount = 0;
return function () { passengerCount++; console.log(`${passengerCount} passengers`); }; };
const booker = secureBooking();
booker(); // 1
booker(); // 2
booker();// 3
What are modules
Modules refer to small units of independent, reusable code and also act as the foundation of many JavaScript design patterns. Most of the JavaScript modules export an object literal, a function, or a constructor
What is scope in javascript
Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.
What is a service worker
A Service worker is basically a script (JavaScript file) that runs in the background, separate from a web page and provides features that don’t need a web page or user interaction. Some of the major features of service workers are Rich offline experiences(offline first web application development), periodic background syncs, push notifications, intercept and handle network requests and programmatically managing a cache of responses.
How do you manipulate DOM using a service worker
Service worker can’t access the DOM directly. But it can communicate with the pages it controls by responding to messages sent via the postMessage interface, and those pages can manipulate the DOM.
How do you reuse information across service worker restarts
The problem with service worker is that it gets terminated when not in use, and restarted when it’s next needed, so you cannot rely on global state within a service worker’s onfetch and onmessage handlers. In this case, service workers will have access to IndexedDB API in order to persist and reuse across restarts.