javascript questions Flashcards

1
Q

What are the possible ways to create objects in JavaScript

A

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";
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a prototype chain

A

Prototype chaining is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between Call, Apply and Bind

A

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?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is JSON and its common operations

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the purpose of the array slice method

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the purpose of the array splice method

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are lambda or arrow functions

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a first order function

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is a higher order function

A

Higher-order function is a function that accepts another function as an argument or returns a function as a return value or both.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is a unary function

A

Unary function (i.e. monadic) is a function that accepts exactly one argument. It stands for a single argument accepted by a function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the currying function?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a pure function?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the purpose of the let keyword

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you redeclare variables in switch block without an error

A
let counter = 1;
    switch(x) {
      case 0: { //use curry braces
        let name;
        break;
      }
      case 1: {
        let name; // No SyntaxError for redeclaration.
        break;
      }
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is IIFE(Immediately Invoked Function Expression)

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the benefit of using modules

A

There are a lot of benefits to using modules in favour of a sprawling. Some of the benefits are,

Maintainability
Reusability
Namespacing

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is Hoisting

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What are classes in ES6

A

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’;
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are closures

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are modules

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is scope in javascript

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is a service worker

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do you manipulate DOM using a service worker

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do you reuse information across service worker restarts

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is IndexedDB

A

IndexedDB is a low-level API for client-side storage of larger amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.

26
Q

What is web storage

A

Web storage is an API that provides a mechanism by which browsers can store key/value pairs locally within the user’s browser, in a much more intuitive fashion than using cookies. The web storage provides two mechanisms for storing data on the client.

Local storage: It stores data for current origin with no expiration date.
Session storage: It stores data for one session and the data is lost when the browser tab is closed.

27
Q

What is a Cookie

A

A cookie is a piece of data that is stored on your computer to be accessed by your browser. Cookies are saved as key/value pairs.

28
Q

What is the main difference between localStorage and sessionStorage

A

LocalStorage is the same as SessionStorage but it persists the data even when the browser is closed and reopened(i.e it has no expiration time) whereas in sessionStorage data gets cleared when the page session ends.

29
Q

What is a promise

A

A promise is an object that may produce a single value some time in the future with either a resolved value or a reason that it’s not resolved(for example, network error). It will be in one of the 3 possible states: fulfilled, rejected, or pending.

30
Q

Why do you need a promise?

A

Promises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code.

31
Q

What are the three states of promise?

A

Promises have three states:

Pending: This is an initial state of the Promise before an operation begins.

Fulfilled: This state indicates that the specified operation was completed.

Rejected: This state indicates that the operation did not complete. In this case, an error value will be thrown.

32
Q

What is a callback function

A

A callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action.

33
Q

What is promise.all

A

Promise.all is a promise that takes an array of promises as an input (an iterable), and it gets resolved when all the promises get resolved or any one of them gets rejected.

34
Q

What is event bubbling?

A

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.

35
Q

How do you submit a form using JavaScript

A

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

function submit() {
    document.forms[0].submit();
}
36
Q

What is the purpose JSON stringify

A

When sending data to a web server, the data has to be in a string format. You can achieve this by converting JSON object into a string using stringify() method.

var userJSON = {'name': 'John', age: 31}
var userString = JSON.stringify(user);
console.log(userString); //"{"name":"John","age":31}"
37
Q

How do you parse JSON string

A

When receiving the data from a web server, the data is always in a string format. But you can convert this string value to a javascript object using parse() method.

var userString = '{"name":"John","age":31}';
var userJSON = JSON.parse(userString);
console.log(userJSON);// {name: "John", age: 31}
38
Q

Why do you need JSON

A

When exchanging data between a browser and a server, the data can only be text. Since JSON is text only, it can easily be sent to and from a server, and used as a data format by any programming language.

39
Q

How do you loop through or enumerate javascript object

A

You can use the for-in loop to loop through javascript object. You can also make sure that the key you get is an actual property of an object, and doesn’t come from the prototype using hasOwnProperty method.

var object = {
    "k1": "value1",
    "k2": "value2",
    "k3": "value3"
};
for (var key in object) {
    if (object.hasOwnProperty(key)) {
        console.log(key + " -> " + object[key]); // k1 -> value1 ...
    }
}
40
Q

How do you test for an empty object

A

Object.entries(obj).length === 0 && obj.constructor === Object // Since date object length is 0, you need to check constructor check as well

41
Q

How do you make first letter of the string in an uppercase

A

You can create a function which uses a chain of string methods such as charAt, toUpperCase and slice methods to generate a string with the first letter in uppercase.

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
42
Q

How do you display the current date in javascript

A

You can use new Date() to generate a new Date object containing the current date and time.

43
Q

How do you trim a string in javascript

A

JavaScript provided a trim method on string types to trim any whitespaces present at the beginning or ending of the string.

” Hello World “.trim(); //Hello World

44
Q

Can you write a random integers function to print integers with in a range

A
function randomInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}
randomInteger(1, 100); // returns a random integer from 1 to 100
randomInteger(1, 1000); // returns a random integer from 1 to 1000
45
Q

What is a Regular Expression

A

A regular expression is a sequence of characters that forms a search pattern. You can use this search pattern for searching data in a text.

46
Q

What are the string methods available in Regular expression

A

Regular Expressions has two string methods: search() and replace().

47
Q

What are the properties used to get size of window

A

You can use innerWidth, innerHeight, clientWidth, clientHeight properties of windows, document element and document body objects to find the size of a window.

48
Q

What is a conditional operator in javascript

A

ternary operator

49
Q

What is the easiest way to convert an array to an object

A

You can convert an array to an object with the same data using spread(…) operator.

var fruits = ["banana", "apple", "orange", "watermelon"];
var fruitsObject = {...fruits};
console.log(fruitsObject); // {0: "banana", 1: "apple", 2: "orange", 3: "watermelon"}
50
Q

what are falsy values

A
THERE ARE FIVE FALSY VALUES.
empty string,
value of 0,
null
undefined,
NaN
51
Q

how many bits makes a byte

A

8 bits

52
Q

whats is does a remainder sign do in javaScript?

A

it returns the remainder of a division operator

53
Q

Can you name two programming paradigms important for JavaScript app developers?

A

OOP - Prototypal inheritance (also: prototypes, OLOO).

Functional programming (also: closures, first class functions, lambdas).

54
Q

What is functional programming?

A

Functional programming produces programs by composing mathematical functions and avoids shared state & mutable data.
It is heavily inspired by lambda calculus.

Concepts of FP are
Pure functions / function purity.

Avoid side-effects.

Simple function composition.

Examples of functional languages: Lisp, ML, Haskell, Erlang, Clojure, Elm, F Sharp, OCaml, etc…

features that support FP: first-class functions, higher order functions, functions as arguments/values.

55
Q

What is the difference between classical inheritance and prototypal inheritance?

A

is that classical inheritance is limited to classes inheriting from other classes while prototypal inheritance supports the cloning of any object using an object linking mechanism.

56
Q

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

A

OOP Pros: It’s easy to understand the basic concept of objects and easy to interpret the meaning of method calls. OOP tends to use an imperative style rather than a declarative style, which reads like a straight-forward set of instructions for the computer to follow.
OOP Cons: OOP Typically depends on shared state. Objects and behaviors are typically tacked together on the same entity, which may be accessed at random by any number of functions with non-deterministic order, which may lead to undesirable behavior such as race conditions.
FP Pros: Using the functional paradigm, programmers avoid any shared state or side-effects, which eliminates bugs caused by multiple functions competing for the same resources. With features such as the availability of point-free style (aka tacit programming), functions tend to be radically simplified and easily recomposed for more generally reusable code compared to OOP.
FP also tends to favor declarative and denotational styles, which do not spell out step-by-step instructions for operations, but instead concentrate on what to do, letting the underlying functions take care of the how. This leaves tremendous latitude for refactoring and performance optimization, even allowing you to replace entire algorithms with more efficient ones with very little code change. (e.g., memoize, or use lazy evaluation in place of eager evaluation.)
Computation that makes use of pure functions is also easy to scale across multiple processors, or across distributed computing clusters without fear of threading resource conflicts, race conditions, etc…
FP Cons: Over exploitation of FP features such as point-free style and large compositions can potentially reduce readability because the resulting code is often more abstractly specified, more terse, and less concrete.
More people are familiar with OO and imperative programming than functional programming, so even common idioms in functional programming can be confusing to new team members.
FP has a much steeper learning curve than OOP because the broad popularity of OOP has allowed the language and learning materials of OOP to become more conversational, whereas the language of FP tends to be much more academic and formal. FP concepts are frequently written about using idioms and notations from lambda calculus, algebras, and category theory, all of which requires a prior knowledge foundation in those domains to be understood.

57
Q

When is classical inheritance an appropriate choice?

A

The answer is never, or almost never. There is a saying “If a feature is sometimes useful
and sometimes dangerous
and if there is a better option
then always use the better option.”

58
Q

When is prototypal inheritance an appropriate choice?

A

There is more than one type 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).
Each type of prototypal inheritance has its own set of use-cases, but all of them are equally useful in their ability to enable composition.

59
Q

What are the pros and cons of monolithic vs microservice architectures?

A

A 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.
A microservice architecture means that 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.
Monolithic Pros: The major advantage of the monolithic architecture is that most apps typically have a large number of cross-cutting concerns, such as logging, rate limiting, and security features such audit trails and DOS protection.
When everything is running through the same app, it’s easy to hook up components to those cross-cutting concerns.
There can also be performance advantages, since shared-memory access is faster than inter-process communication (IPC).
Monolithic cons: Monolithic app services tend to get tightly coupled and entangled as the application evolves, making it difficult to isolate services for purposes such as independent scaling or code maintainability.
Monolithic architectures are also much harder to understand, because there may be dependencies, side-effects, and magic which are not obvious when you’re looking at a particular service or controller.
Microservice pros: Microservice architectures are typically better organized, since each microservice has a very specific job, and is not concerned with the jobs of other components. Decoupled services are also easier to recompose and reconfigure to serve the purposes of different apps (for example, serving both the web clients and public API).
They can also have performance advantages depending on how they’re organized because it’s possible to isolate hot services and scale them independent of the rest of the app.
Microservice cons: As you’re building a new microservice architecture, you’re likely to discover lots of cross-cutting concerns that you did not anticipate at design time. A monolithic app could establish shared magic helpers or middleware to handle such cross-cutting concerns without much effort.
In a microservice architecture, you’ll either need to incur the overhead of separate modules for each cross-cutting concern, or encapsulate cross-cutting concerns in another service layer that all traffic gets routed through.
Eventually, even monolthic architectures tend to route traffic through an outer service layer for cross-cutting concerns, but with a monolithic architecture, it’s possible to delay the cost of that work until the project is much more mature.
Microservices are frequently deployed on their own virtual machines or containers, causing a proliferation of VM wrangling work. These tasks are frequently automated with container fleet management tools.

60
Q

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

A

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.