All interview topics
Full-Stack, Web & Mobile

JavaScript Interview Questions and Answers

Practice JavaScript interview questions and answers organized by difficulty, with revealable explanations and related topics.

179 questionsEntry → Expert

Entry questions

13 questions
  1. Question 1
    Entry

    What is the object type?

    • JavaScript
    Reveal answer

    The object type refers to a compound value where you can set properties (named locations) that each hold their own values of any type.

    var obj = {
      a: "hello world",
      // property
      b: 42,
      c: true
    };
    obj.a;
    // "hello world", accessed with doted notation
    obj.b;
    // 42
    obj.c;
    // true
    obj["a"];
    // "hello world", accessed with bracket notation
    obj["b"];
    // 42
    obj["c"];
    // true
    

    Bracket notation is also useful if you want to access a property/key but the name is stored in another variable, such as:

    var obj = {
      a: "hello world",
      b: 42
    };
    var b = "a";
    obj[b];
    // "hello world"
    obj["b"];
    // 42
    
  2. Question 2
    Entry

    Explain how Bubble Sort works

    • Sorting JavaScript
    Reveal answer

    Bubble Sort is based on the idea of repeatedly comparing pairs of adjacent elements and then swapping their positions if they are in the wrong order. Bubble sort is a stable, in-place sort algorithm. How it works: In an unsorted array of n elements, start with the first two elements and sort them in ascending order. (Compare the element to check which one is greater). Compare the second and third element to check which one is greater, and sort them in ascending order. Compare the third and fourth element to check which one is greater, and sort them in ascending order. ... Repeat steps 1– n until no more swaps are required. Visualisation:

    Complexity Analysis: Time Complexity: O(n^2) Space Complexity: O(n^2) Bubble sort has a worst-case and average complexity of

    O(
    

    n2) , where n is the number of items being sorted. When the list is already sorted (best-case), the complexity of bubble sort is only O(n) . The space complexity for Bubble Sort is O(1) , because only single additional memory space is required (for temp swap element). Implementation: JS

    // Normal
    const bubbleSort = function(array) {
      let swaps;
      do {
        swaps = false;
        for (let i = 0; i < array.length - 1; i++) {
          if (array[i] > array[i + 1]) {
            let temp = array[i + 1];
            array[i + 1] = array[i];
            array[i] = temp;
            swaps = true;
          }
      }
    } while (swaps);
    return array;
    };// Recursively
    const bubbleSort = function (array, pointer = array.length - 1) {
      // Base Case
      if (pointer === 0) {
        return array;
      }
    for (let i = 0; i < pointer; i++) {
      if (array[i] > array[i + 1]) {
        let temp = array[i + 1];
        array[i + 1] = array[i];
        array[i] = temp;
      }
    }
    // Recursive call on smaller portion of the array
    return bubbleSort(array, pointer - 1);
    };
    PY
    def bubbleSort(arr):
    n = len(arr)# Traverse through all array elements
    for i in range(n):
    # Last i elements are already in place
    for j in range(0, n-i-1):
    # traverse the array from 0 to n-i-1
    # Swap if the element found is greater
    # than the next element
    if arr[j] > arr[j+1] :
    arr[j], arr[j+1] = arr[j+1], arr[j]
    
  3. Question 2
    Entry

    Explain arrays in JavaScript

    • JavaScript
    Reveal answer

    An array is an object that holds values (of any type) not particularly in named properties/keys, but rather in numerically indexed positions:

    var arr = [
    "hello world",
    42,
    true
    ];
    arr[0];
    // "hello world"
    
    arr[1];
    // 42
    arr[2];
    // true
    arr.length;
    // 3
    typeof arr;
    // "object"
    
  4. Question 3
    Entry

    Explain how Bubble Sort works

    • Sorting JavaScript
    Reveal answer

    Bubble Sort is based on the idea of repeatedly comparing pairs of adjacent elements and then swapping their positions if they are in the wrong order. Bubble sort is a stable, in-place sort algorithm. How it works: In an unsorted array of n elements, start with the first two elements and sort them in ascending order. (Compare the element to check which one is greater). Compare the second and third element to check which one is greater, and sort them in ascending order. Compare the third and fourth element to check which one is greater, and sort them in ascending order. ... Repeat steps 1– n until no more swaps are required. Visualisation: Complexity Analysis: Time Complexity: O(n^2) Space Complexity: O(n^2) Bubble sort has a worst-case and average complexity of

    O(
    

    n2) , where n is the number of items being sorted. When the list is already sorted (best-case), the complexity of bubble sort is only O(n) . The space complexity for Bubble Sort is O(1) , because only single additional memory space is required (for temp swap element). Implementation: JS

    // Normal
    const bubbleSort = function(array) {
      let swaps;
      do {
        swaps = false;
        for (let i = 0; i < array.length - 1; i++) {
          if (array[i] > array[i + 1]) {
            let temp = array[i + 1];
            array[i + 1] = array[i];
            array[i] = temp;
            swaps = true;
          }
      }
    } while (swaps);
    return array;
    };// Recursively
    const bubbleSort = function (array, pointer = array.length - 1) {
    
      // Base Case
      if (pointer === 0) {
        return array;
      }
    for (let i = 0; i < pointer; i++) {
      if (array[i] > array[i + 1]) {
        let temp = array[i + 1];
        array[i + 1] = array[i];
        array[i] = temp;
      }
    }
    // Recursive call on smaller portion of the array
    return bubbleSort(array, pointer - 1);
    };
    PY
    def bubbleSort(arr):
    n = len(arr)# Traverse through all array elements
    for i in range(n):
    # Last i elements are already in place
    for j in range(0, n-i-1):
    # traverse the array from 0 to n-i-1
    # Swap if the element found is greater
    # than the next element
    if arr[j] > arr[j+1] :
    arr[j], arr[j+1] = arr[j+1], arr[j]
    
  5. Question 4
    Entry

    Sum of Array Plus One

    • JavaScript
    Reveal answer

    Problem

    Write a function that takes an array of integers and returns the sum of the integers after adding 1 to each.

    Solution

    // ES5 method is nice and clean
    exports.es5 = function (array) {
      return array.reduce(function (memo, num) {
        return memo + num;
      }, array.length);
    };// Without array.reduce method isn't much different
    exports.iterative = function (array) {
      var result = array.length;
      for (var i = 0; i < array.length; i++) {
        result += array[i];
      }
    return result;
    };
    
  6. Question 5
    Entry

    String Rotation

    • JavaScript
    Reveal answer

    Problem

    Find out if a string is a rotation of another string. E.g. ABCD is a rotation of BCDA but not ACBD .

    Solution

    First make sure a and b are of the same length. Then check to see if b is a substring of a concatenated with a :

    module.exports = function (a, b) {
      return a.length === b.length && (a + a).indexOf(b) > -1;
    };
    
  7. Question 6
    Entry

    Explain equality in JavaScript

    • JavaScript
    Reveal answer

    JavaScript has both strict and type–converting comparisons: Strict comparison (e.g., ===) checks for value equality without allowing coercion Abstract comparison (e.g. ==) checks for value equality with coercion allowed

    var a = "42";
    var b = 42;
    a == b;
    // true
    a === b;
    // false
    Some simple equalityrules:
    If either value (aka side) in a comparison could be the true or false value, avoid == and use === .
    If either value in a comparison could be of these specific values ( 0 , "" , or [] -- empty array), avoid ==
    and use === .
    In all other cases, you're safe to use == . Not only is it safe, but in many cases it simplifies your code in a
    

    way that improves readability.

  8. Question 6
    Entry

    Oddball sum

    • JavaScript
    Reveal answer

    Problem

    Write a function called oddball_sum which takes in a list of numbers and returns the sum of all the odd elements. Try to solve with and without reduce function.

    Solution

    To solve this challenge we'll simply loop through the array while maintaining a final count, and every time an odd number is encountered we'll add it to the count. Without reduce :

    function oddball_sum(nums) {// final count of all odd numbers added up
      var final_count = 0;// loop through entire list
      for (var i = 0; i < nums.length; i++) {// we divide by 2, and if there is a remainder then
        // the number must be odd so we add it to final_count
        if (nums[i] % 2 === 1) {
          final_count += nums[i]
        }
    }
    return final_count;
    }
    oddball_sum([1, 2, 3, 4, 5]);
    

    With reduce :

    function oddball_sum(nums) {
      return nums.reduce(function(total, item){
        if (item % 2 === 1) {
          return total += item;
        }
      return total;
    });
    }
    
  9. Question 7
    Entry

    Explain equality in JavaScript

    • JavaScript
    Reveal answer

    JavaScript has both strict and type–converting comparisons: Strict comparison (e.g., ===) checks for value equality without allowing coercion Abstract comparison (e.g. ==) checks for value equality with coercion allowed

    var a = "42";
    var b = 42;
    a == b;
    // true
    a === b;
    // false
    Some simple equalityrules:
    If either value (aka side) in a comparison could be the true or false value, avoid == and use === .
    If either value in a comparison could be of these specific values ( 0 , "" , or [] -- empty array), avoid ==
    and use === .
    In all other cases, you're safe to use == . Not only is it safe, but in many cases it simplifies your code in a
    

    way that improves readability.

  10. Question 10
    Entry

    Explain arrays in JavaScript

    • JavaScript
    Reveal answer

    An array is an object that holds values (of any type) not particularly in named properties/keys, but rather in numerically indexed positions:

    var arr = [
    "hello world",
    42,
    true
    ];
    arr[0];
    // "hello world"
    arr[1];
    // 42
    arr[2];
    // true
    arr.length;
    // 3
    typeof arr;
    // "object"
    
  11. Question 11
    Entry

    What is the object type?

    • JavaScript
    Reveal answer

    The object type refers to a compound value where you can set properties (named locations) that each hold their own values of any type.

    var obj = {
      a: "hello world",
      // property
      b: 42,
      c: true
    };
    obj.a;
    // "hello world", accessed with doted notation
    obj.b;
    // 42
    obj.c;
    // true
    obj["a"];
    // "hello world", accessed with bracket notation
    obj["b"];
    // 42
    obj["c"];
    // true
    

    Bracket notation is also useful if you want to access a property/key but the name is stored in another variable, such as:

    var obj = {
      a: "hello world",
      b: 42
    };
    
    var b = "a";
    obj[b];
    // "hello world"
    obj["b"];
    // 42
    
  12. Question 12
    Entry

    What is typeof operator?

    • JavaScript
    Reveal answer

    JavaScript provides a typeof operator that can examine a value and tell you what type it is:

    var a;
    typeof a;
    // "undefined"
    a = "hello world";
    typeof a;
    // "string"
    a = 42;
    typeof a;
    // "number"
    a = true;
    typeof a;
    // "boolean"
    a = null;
    typeof a;
    // "object" -- weird, bug
    a = undefined;
    typeof a;
    // "undefined"
    a = { b: "c" };
    typeof a;
    // "object"
    
  13. Question 13
    Entry

    What is Scope in JavaScript?

    • JavaScript
    Reveal answer

    In JavaScript, each function gets its own scope. Scope is basically a collection of variables as well as the rules for how those variables are accessed by name. Only code inside that function can access that function's scoped variables. A variable name has to be unique within the same scope. A scope can be nested inside another scope. If one scope is nested inside another, code inside the innermost scope can access variables from either scope.

Junior questions

40 questions
  1. Question 1
    Junior

    What is let keyword in JavaScript?

    • JavaScript
    Reveal answer

    In addition to creating declarations for variables at the function level, ES6 lets you declare variables to belong to individual blocks (pairs of { .. } ), using the let keyword.

  2. Question 2
    Junior

    Is there anyway to force using strict mode in Node.js?

    • JavaScript
    Reveal answer

    you can place

    "use strict";
    at the top of your file in node >= 0.10.7, but if you want your whole app to run in strict (including external
    modules) you can do this
    node --use_strict
    
  3. Question 2
    Junior

    Explain what is Binary Search

    • Searching Java JavaScript
    Reveal answer

    When the list is sorted we can use the binary search (also known as half-interval search, logarithmic search, or binary chop) technique to find items on the list. Here's a step-by-step description of using binary search:

    1. Let min = 1 and max = n .
    2. Guess the average of max and min rounded down so that it is an integer.
    3. If you guessed the number, stop. You found it!
    4. If the guess was too low, set min to be one larger than the guess.
    5. If the guess was too high, set max to be one smaller than the guess.
    6. Go back to step two. In this example we looking for array item with value 4 : When you do one operation in binary search we reduce the size of the problem by half (look at the picture below how do we reduce the size of the problem area) hence the complexity of binary search is
    O(
    log n) . The binary
    

    search algorithm can be written either recursively or iteratively.

    Complexity Analysis: Time Complexity: O(log n) Space Complexity: O(log n) Implementation: JS

    var binarySearch = function(array, value) {
      var guess,
      min = 0,
      max = array.length - 1;
      while(min <= max){
        guess = Math.floor((min + max) /2);
        if(array[guess] === value)
        return guess;
        else if(array[guess] < value)
        min = guess + 1;
        else
        max = guess - 1;
      }
    return -1;
    }
    
    Java
    // binary search example in Java
    /* here Arr is an of integer type, n is size of array
    

    and target is element to be found */ int binarySearch(int Arr[], int n, int target) {//set stating and ending index

    int start = 0, ending = n-1;
    while(start <= ending) {
      // take mid of the list
      int mid = (start + end) / 2;
      // we found a match
      if(Arr[mid] == target) {
        return mid;
      }
    // go on right side
    else if(Arr[mid] < target) {
      start = mid + 1;
    }
    // go on left side
    else {
      end = mid - 1;
    }
    }
    // element is not present in list
    return -1;
    }
    PY
    def BinarySearch(lys, val):
    first = 0
    last = len(lys)-1
    index = -1
    while (first <= last) and (index == -1):
    mid = (first+last)//2
    if lys[mid] == val:
    index = mid
    else:
    if val<lys[mid]:
    last = mid -1
    else:
    first = mid +1
    

    return index

  4. Question 3
    Junior

    Explain what is Linear (Sequential) Search and when may we use one?

    • Searching Python JavaScript
    Reveal answer
    Linear (sequential) search goes through all possible elements in some array and compare each one with the
    

    desired element. It may take up to

    O(
    n) operations, where N is the size of an array and is widely considered to
    

    be horribly slow. In linear search when you perform one operation you reduce the size of the problem by one

    (when you do one operation in binary search you reduce the size of the problem by half). Despite it, it can still be used when: You need to perform this search only once, You are forbidden to rearrange the elements and you do not have any extra memory, The array is tiny, such as ten elements or less, or the performance is not an issue at all, Even though in theory other search algorithms may be faster than linear search (for instance binary search), in practice even on medium-sized arrays (around 100 items or less) it might be infeasible to use anything else. On larger arrays, it only makes sense to use other, faster search methods if the data is large enough, because the initial time to prepare (sort) the data is comparable to many linear searches, When the list items are arranged in order of decreasing probability, and these probabilities are geometrically distributed, the cost of linear search is only

    O(
    1)
    

    You have no idea what you are searching. When you ask MySQL something like SELECT x FROM y WHERE z = t , and z is a column without an index, linear search is performed with all the consequences of it. This is why adding an index to searchable columns is important. Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n) A linear search runs in at worst linear time and makes at most n comparisons, where n is the length of the list. If each element is equally likely to be searched, then linear search has an average case of (n+1)/2 comparisons, but the average case can be affected if the search probabilities for each element vary. When the list items are arranged in order of decreasing probability, and these probabilities are geometrically distributed, the cost of linear search is only

    O(
    1)
    Implementation:
    JS
    function linearSearch(array, toFind){
      for(let i = 0; i < array.length; i++){
        if(array[i] === toFind) return i;
      }
    return -1;
    }
    PY
    # can be simply done using 'in' operator
    if x in arr:
    print arr.index(x)# If you want to implement Linear Search in Python
    def search(arr, x):
    for i in range(len(arr)):
    if arr[i] == x:
    

    return i return -1

  5. Question 4
    Junior

    Why would you use something like the load event? Does this event have disadvantages? Do you know any alternatives, and why would you use those?

    • JavaScript
    Reveal answer

    The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading. The DOM event DOMContentLoaded will fire after the DOM for the page has been constructed, but do not wait for other resources to finish loading. This is preferred in certain cases when you do not need the full page to be loaded before initializing.

  6. Question 4
    Junior

    Explain how Insertion Sort works

    • Sorting Python JavaScript
    Reveal answer

    Insertion Sort is an in-place, stable, comparison-based sorting algorithm. The idea is to maintain a sub-list which is always sorted. An element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort. Steps on how it works: If it is the first element, it is already sorted. Pick the next element. Compare with all the elements in sorted sub-list. Shift all the the elements in sorted sub-list that is greater than the value to be sorted. Insert the value. Repeat until list is sorted. Visualisation: Complexity Analysis: Time Complexity: O(n^2) Space Complexity: O(n^2) Insertion sort runs in

    O(
    n2) in its worst and average cases. It runs in O(n) time in its best case.
    

    Insertion sort performs two operations: it scans through the list, comparing each pair of elements, and it swaps elements if they are out of order. Each operation contributes to the running time of the algorithm. If the input array is already in sorted order, insertion sort compares O(n) elements and performs no swaps. Therefore, in the best case, insertion sort runs in O(n) time. Space complexity is O(1) because an extra variable key is used (as a temp variable for insertion). Implementation: JS

    var insertionSort = function(a) {
      // Iterate through our array
      for (var i = 1, value; i < a.length; i++) {
        // Our array is split into two parts: values preceeding i are sorted, while others are unsorted
        // Store the unsorted value at i
        value = a[i];
        // Interate backwards through the unsorted values until we find the correct location for our
    
        `next` value
        for (var j = i; a[j - 1] > value; j--) {
          // Shift the value to the right
          a[j] = a[j - 1];
        }
      // Once we've created an open "slot" in the correct location for our value, insert it
      a[j] = value;
    }
    // Return the sorted array
    return a;
    };
    Java
    import java.util.Arrays;
    class InsertionSort {
      void insertionSort(int array[]) {
        int size = array.length;
        for (int step = 1; step < size; step++) {
          int key = array[step];
          int j = step - 1;
          // Compare key with each element on the left of it until an element smaller than
          // it is found.
          // For descending order, change key<array[j] to key>array[j].
          while (j >= 0 && key < array[j]) {
            array[j + 1] = array[j];
            --j;
          }
        // Place key at after the element just smaller than it.
        array[j + 1] = key;
      }
    }// Driver code
    public static void main(String args[]) {
      int[] data = { 9, 5, 1, 4, 3 };
      InsertionSort is = new InsertionSort();
      is.insertionSort(data);
      System.out.println("Sorted Array in Ascending Order: ");
      System.out.println(Arrays.toString(data));
    }
    }
    PY
    def insertionSort(array):
    for step in range(1, len(array)):
    key = array[step]
    j = step - 1
    # Compare key with each element on the left of it until an element smaller than it is found
    # For descending order, change key<array[j] to key>array[j].
    while j >= 0 and key < array[j]:
    array[j + 1] = array[j]
    j = j - 1
    # Place key at after the element just smaller than it.
    array[j + 1] = key
    data = [9, 5, 1, 4, 3]
    insertionSort(data)
    
    print('Sorted Array in Ascending Order:')
    print(data)
    
  7. Question 5
    Junior

    What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?

    • JavaScript
    Reveal answer

    Some examples of languages that compile to JavaScript include CoffeeScript, Elm, ClojureScript, PureScript, and TypeScript. Advantages: Fixes some of the longstanding problems in JavaScript and discourages JavaScript anti-patterns. Enables you to write shorter code, by providing some syntactic sugar on top of JavaScript, which I think ES5 lacks, but ES2015 is awesome. Static types are awesome (in the case of TypeScript) for large projects that need to be maintained over time. Disadvantages: Require a build/compile process as browsers only run JavaScript and your code will need to be compiled into JavaScript before being served to browsers. Debugging can be a pain if your source maps do not map nicely to your pre-compiled source. Most developers are not familiar with these languages and will need to learn it. There's a ramp up cost involved for your team if you use it for your projects. Smaller community (depends on the language), which means resources, tutorials, libraries, and tooling would be harder to find. IDE/editor support might be lacking. These languages will always be behind the latest JavaScript standard. Developers should be cognizant of what their code is being compiled to — because that is what would actually be running, and that is what matters in the end. Practically, ES2015 has vastly improved JavaScript and made it much nicer to write. I don't really see the need for CoffeeScript these days.

  8. Question 5
    Junior

    Return the N-th value of the Fibonacci sequence Recursively

    • Fibonacci Series Data Structures Java JavaScript
    Reveal answer

    Recursive solution looks pretty simple (see code). Let’s look at the diagram that will help you understand what’s going on here with the rest of our code. Function fib is called with argument 5: Basically our fib function will continue to recursively call itself creating more and more branches of the tree until it hits the base case, from which it will start summing up each branch’s return values bottom up, until it finally sums them all up and returns an integer equal to 5. Complexity Analysis:

    Time Complexity: O(2^n)
    

    In case of recursion the solution take exponential time, that can be explained by the fact that the size of the tree exponentially grows when n increases. So for every additional element in the Fibonacci sequence we get an increase in function calls. Big O in this case is equal to

    O(
    2n) . Exponential Time complexity denotes an algorithm
    

    whose growth doubles with each addition to the input data set. Implementation: JS

    function fib(n) {
      if (n < 2){
    

    return n

    }
    return fib(n - 1) + fib (n - 2)
    }
    Java
    public int fibonacci(int n) {
      if (n < 2) return n;
      return fibonacci(n - 1) + fibonacci(n - 2);
    }
    PY
    def F(n):
    if n == 0: return 0
    elif n == 1: return 1
    else: return F(n-1)+F(n-2)
    
  9. Question 6
    Junior

    What language constructions do you use for iterating over object properties and array items?

    • JavaScript
    Reveal answer

    For objects:

    for loops - for (var property in obj) { console.log(property); } . However, this will also iterate through its
    inherited properties, and you will add an obj.hasOwnProperty(property) check before using it.
    Object.keys() - Object.keys(obj).forEach(function (property) { ... }) . Object.keys() is a static method
    

    that will lists all enumerable properties of the object that you pass it.

    Object.getOwnPropertyNames() - Object.getOwnPropertyNames(obj).forEach(function (property) { ... }) .
    Object.getOwnPropertyNames() is a static method that will lists all enumerable and non-enumerable properties
    

    of the object that you pass it. For arrays: for loops - for (var i = 0; i < arr.length; i++) . The common pitfall here is that var is in the function scope and not the block scope and most of the time you would want block scoped iterator variable. ES2015 introduces let which has block scope and it is recommended to use that instead. So this becomes: for (let

    i = 0; i < arr.length; i++) .
    forEach - arr.forEach(function (el, index) { ... }) . This construct can be more convenient at times
    

    because you do not have to use the index if all you need is the array elements. There are also the every and some methods which will allow you to terminate the iteration early. Most of the time, I would prefer the .forEach method, but it really depends on what you are trying to do. for loops allow more flexibility, such as prematurely terminate the loop using break or incrementing the iterator

    more than once per loop.

  10. Question 6
    Junior

    Return the N-th value of the Fibonacci sequence. Solve in O(n) time

    • Fibonacci Series Data Structures Python JavaScript
    Reveal answer

    The easiest solution that comes to mind here is iteration:

    function fib(n){
      let arr = [0, 1];
      for (let i = 2; i < n + 1; i++){
        arr.push(arr[i - 2] + arr[i -1])
      }
    return arr[n]
    }
    

    And output:

    fib(4)
    => 3
    

    Notice that two first numbers can not really be effectively generated by a for loop, because our loop will involve adding two numbers together, so instead of creating an empty array we assign our arr variable to [0, 1] that we know for a fact will always be there. After that we create a loop that starts iterating from i = 2 and adds numbers to the array until the length of the array is equal to n + 1 . Finally, we return the number at n index of array. Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n)

    An algorithm in our iterative solution takes linear time to complete the task. Basically we iterate through the loop n-2 times, so Big O (notation used to describe our worst case scenario) would be simply equal to O (n) in this case. The space complexity is O(n) . Implementation: JS

    function fib(n){
      let arr = [0, 1]
      for (let i = 2; i < n + 1; i++){
        arr.push(arr[i - 2] + arr[i -1])
      }
    return arr[n]
    }
    Java
    double fibbonaci(int n){
      double prev=0d, next=1d, result=0d;
      for (int i = 0; i < n; i++) {
        result=prev+next;
        prev=next;
        next=result;
      }
    return result;
    }
    PY
    def fib_iterative(n):
    a, b = 0, 1
    while n > 0:
    a, b = b, a + b
    n -= 1
    

    return a

  11. Question 7
    Junior

    Explain what a callback function is and provide a simple example

    • JavaScript
    Reveal answer

    A callback function is a function that is passed to another function as an argument and is executed after some operation has been completed. Below is an example of a simple callback function that logs to the console after some operations have been completed.

    function modifyArray(arr, callback) {
      // do something to arr here
      arr.push(100);
      // then execute the callback function that was passed
      callback();
    }
    var arr = [1, 2, 3, 4, 5];
    modifyArray(arr, function() {
      console.log("array has been modified", arr);
    });
    
  12. Question 7
    Junior

    Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

    • JavaScript
    Reveal answer

    Every script has access to the global scope, and if everyone uses the global namespace to define their variables, collisions will likely occur. Use the module pattern (IIFEs) to encapsulate your variables within a local namespace.

  13. Question 8
    Junior

    Determine overlapping numbers in ranges

    • JavaScript
    Reveal answer

    Problem

    You will be given an array with 5 numbers. The first 2 numbers represent a range, and the next two numbers represent another range. The final number in the array is X . The goal of your program is to determine if both ranges overlap by at least X numbers. For example, in the array [4, 10, 2, 6, 3] the ranges 4 to 10 and 2 to 6 overlap by at least 3 numbers (4, 5, 6) , so your program should return true . Solve with and without looping. If the array is [10, 20, 4, 14, 4] then the ranges are: 10 11 12 13 14 15 16 17 18 19 20 4 5 6 7 8 9 10 11 12 13 14 These ranges overlap by at least 4 numbers, namely: 10, 11, 12, 13, 14 so your program should return true .

    Solution

    With loop:

    function OverlappingRanges(arr) {// keep a count of how many numbers overlap
      var counter = 0;// loop through one of the ranges
      for (var i = arr[0]; i < arr[1]; i++) {// check if a number within the first range exists
        // in the second range
        if (i >= arr[2] && i <= arr[3]) {
          counter += 1;
        }
    }// check if the numbers that overlap is equal to or greater
    // than the last number in the array
    return (counter >= arr[4]) ? true : false;
    }
    OverlappingRanges([4, 10, 2, 6, 3]);
    Without loop:
    function overlapping(input){
      var nums1 = listOfNums(input[0], input[1]);
      var nums2 = listOfNums(input[2], input[3]);
      var overlappingNum = 0;
      if(nums1[0] >= nums2[0] && nums1[0] <= nums2[1]){
        overlappingNum = nums2[1] - nums1[0] + 1;
      } else {
        overlappingNum = nums1[1] - nums2[0] + 1;
      }
    if(overlappingNum >= input[4]){
      return true;
    }
    }
    function listOfNums(a, b){
      var start = a;
      var end = b;
      if(a > b){
        start = b;
        end = a;
      }
    return [a, b];
    }
    var a = [4, 10, 2, 6, 3];
    overlapping(a)
    
  14. Question 8
    Junior

    What does use strict do?

    • JavaScript
    Reveal answer

    The use strict literal is entered at the top of a JavaScript program or at the top of a function and it helps you write safer JavaScript code by throwing an error if a global variable is created by mistake. For example, the following program will throw an error:

    function doSomething(val) {
      "use strict";
      x = val + 10;
    }`
    

    It will throw an error because x was not defined and it is being set to some value in the global scope, which isn't allowed with use strict The small change below fixes the error being thrown:

    function doSomething(val) {
      "use strict";
      var x = val + 10;
    }
    
  15. Question 8
    Junior

    How would you check if a number is an integer?

    • JavaScript
    Reveal answer

    A very simply way to check if a number is a decimal or integer is to see if there is a remainder left when you divide by 1.

    function isInt(num) {
      return num % 1 === 0;
    }
    console.log(isInt(4));
    // true
    console.log(isInt(12.2));
    // false
    console.log(isInt(0.3));
    // false
    
  16. Question 9
    Junior

    Explain what is Binary Search

    • Searching Java JavaScript
    Reveal answer

    When the list is sorted we can use the binary search (also known as half-interval search, logarithmic search, or binary chop) technique to find items on the list. Here's a step-by-step description of using binary search:

    1. Let min = 1 and max = n .
    2. Guess the average of max and min rounded down so that it is an integer.
    3. If you guessed the number, stop. You found it!
    4. If the guess was too low, set min to be one larger than the guess.
    5. If the guess was too high, set max to be one smaller than the guess.
    6. Go back to step two. In this example we looking for array item with value 4 : When you do one operation in binary search we reduce the size of the problem by half (look at the picture below how do we reduce the size of the problem area) hence the complexity of binary search is
    O(
    log n) . The binary
    

    search algorithm can be written either recursively or iteratively. Complexity Analysis: Time Complexity: O(log n) Space Complexity: O(log n) Implementation:

    JS

    var binarySearch = function(array, value) {
      var guess,
      min = 0,
      max = array.length - 1;
      while(min <= max){
        guess = Math.floor((min + max) /2);
        if(array[guess] === value)
        return guess;
        else if(array[guess] < value)
        min = guess + 1;
        else
        max = guess - 1;
      }
    return -1;
    }
    Java
    // binary search example in Java
    /* here Arr is an of integer type, n is size of array
    

    and target is element to be found */ int binarySearch(int Arr[], int n, int target) {//set stating and ending index

    int start = 0, ending = n-1;
    while(start <= ending) {
      // take mid of the list
      int mid = (start + end) / 2;
      // we found a match
      if(Arr[mid] == target) {
        return mid;
      }
    // go on right side
    else if(Arr[mid] < target) {
      start = mid + 1;
    }
    // go on left side
    else {
      end = mid - 1;
    }
    }
    // element is not present in list
    return -1;
    }
    PY
    def BinarySearch(lys, val):
    first = 0
    last = len(lys)-1
    index = -1
    while (first <= last) and (index == -1):
    mid = (first+last)//2
    if lys[mid] == val:
    index = mid
    else:
    if val<lys[mid]:
    last = mid -1
    else:
    
    first = mid +1
    

    return index

  17. Question 9
    Junior

    Implement Bubble Sort

    • JavaScript
    Reveal answer

    The steps in the bubble sort algorithm are:

    1. Loop through the whole array starting from index 1
    2. If the number in the array at index i-1 is greater than i, swap the numbers and continue
    3. Once the end of the array is reached, start looping again from the beginning
    4. Once no more elements can be swapped, the sorting is complete
    function swap(arr, i1, i2) {
      var temp = arr[i1];
      arr[i1] = arr[i2];
      arr[i2] = temp;
    }
    function bubblesort(arr) {
      var swapped = true;// keep going unless no elements can be swapped anymore
      while (swapped) {// set swapped to false so that the loop stops
        // unless two element are actually swapped
        swapped = false;// loop through the whole array swapping adjacent elements
        for (var i = 1; i < arr.length; i++) {
          if (arr[i-1] > arr[i]) {
            swap(arr, i-1, i);
            swapped = true;
          }
      }
    }
    return arr;
    }
    bubblesort([103, 45, 2, 1, 97, -4, 67]);
    
  18. Question 10
    Junior

    Implement a Queue using two Stacks

    • Queues Stacks Java C# JavaScript
    Reveal answer

    Problem

    Suppose we have two stacks and no other temporary variable. Is to possible to "construct" a queue data structure using only the two stacks?

    Solution

    Keep two stacks, let's call them inbox and outbox . Enqueue: Push the new element onto inbox Dequeue: If outbox is empty, refill it by popping each element from inbox and pushing it onto outbox Pop and return the top element from outbox Complexity Analysis: Time Complexity: O(1) Space Complexity: O(1) In the worst case scenario when outbox stack is empty, the algorithm pops n elements from inbox stack and pushes n elements to outbox, where n is the queue size. This gives 2*n operations, which is O(n) . But when outbox stack is not empty the algorithm has O(1) time complexity that gives amortised O(1) . Implementation: CS public class Queue where T : class

    {
      private Stack<T> input = new Stack<T>();
      private Stack<T> output = new Stack<T>();
      public void Enqueue(T t)
      {
        input.Push(t);
      }
    public T Dequeue()
    {
      if (output.Count == 0)
      {
        while (input.Count != 0)
        {
          output.Push(input.Pop());
        }
    }
    return output.Pop();
    
    }
    }
    Java
    public class Queue<E>
    {
      private Stack<E> inbox = new Stack<E>();
      private Stack<E> outbox = new Stack<E>();
      public void queue(E item) {
        inbox.push(item);
      }
    public E dequeue() {
      if (outbox.isEmpty()) {
        while (!inbox.isEmpty()) {
          outbox.push(inbox.pop());
        }
    }
    return outbox.pop();
    }
    }
    PY
    class Queue(object):
    def __init__(self):
    self.instack=[]
    self.outstack=[]
    def enqueue(self,element):
    self.instack.append(element)
    def dequeue(self):
    if not self.outstack:
    while self.instack:
    self.outstack.append(self.instack.pop())
    return self.outstack.pop()
    JS
    import { Stack } from "./Stack";
    class QueueUsingTwoStacks {
      constructor() {
        this.stack1 = new Stack();
        this.stack2 = new Stack();
      }
    enqueue(data) {
      this.stack1.push(data);
    }
    dequeue() {
      //if both stacks are empty, return undefined
      if (this.stack1.size() === 0 && this.stack2.size() === 0)
      return undefined;//if stack2 is empty, pop all elements from stack1 to stack2 till stack1 is empty
      if (this.stack2.size() === 0) {
        while (this.stack1.size() !== 0) {
          this.stack2.push(this.stack1.pop());
    
        }
    }//pop and return the element from stack 2
    return this.stack2.pop();
    }
    }
    export { QueueUsingTwoStacks };
    
  19. Question 11
    Junior

    Is there anyway to force using strict mode in Node.js?

    • JavaScript
    Reveal answer

    you can place

    "use strict";
    at the top of your file in node >= 0.10.7, but if you want your whole app to run in strict (including external
    modules) you can do this
    node --use_strict
    
  20. Question 11
    Junior

    Explain Values and Types in JavaScript

    • JavaScript
    Reveal answer

    JavaScript has typed values, not typed variables. The following built-in types are available: string number boolean null and undefined object

    symbol (new to ES6)
    
  21. Question 11
    Junior

    Remove duplicates of an array and return an array of only unique elements

    • JavaScript
    Reveal answer
    // ES6 Implementation
    var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8];
    Array.from(new Set(array));
    // [1, 2, 3, 5, 9, 8]
    // ES5 Implementation
    var array = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8];
    uniqueArray(array);
    // [1, 2, 3, 5, 9, 8]
    function uniqueArray(array) {
      var hashmap = {};
      var unique = [];
      for(var i = 0; i < array.length; i++) {
        // If key returns undefined (unique), it is evaluated as false.
    
        if(!hashmap.hasOwnProperty(array[i])) {
          hashmap[array[i]] = 1;
          unique.push(array[i]);
        }
    }
    return unique;
    }
    
  22. Question 12
    Junior

    What's the difference between Host objects and Native objects?

    • JavaScript
    Reveal answer

    Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification, such as String , Math , RegExp , Object , Function , etc. Host objects are provided by the runtime environment (browser or Node), such as window , XMLHTTPRequest , etc.

  23. Question 12
    Junior

    What is Callback Hell and what is the main cause of it?

    • Node.js JavaScript
    Reveal answer

    Asynchronous JavaScript, or JavaScript that uses callbacks, is hard to get right intuitively. A lot of code ends up looking like this:

    fs.readdir(source, function (err, files) {
      if (err) {
        console.log('Error finding files: ' + err)
      } else {
        files.forEach(function (filename, fileIndex) {
          console.log(filename)
          gm(source + filename).size(function (err, values) {
            if (err) {
              console.log('Error identifying file size: ' + err)
            } else {
              console.log(filename + ' : ' + values)
              aspect = (values.width / values.height)
              widths.forEach(function (width, widthIndex) {
                height = Math.round(width / aspect)
                console.log('resizing ' + filename + 'to ' + height + 'x' + height)
                this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
                  if (err) console.log('Error writing file: ' + err)
                })
            }.bind(this))
        }
    })
    })
    }
    })
    See the pyramid shape and all the }) at the end? This is affectionately known as callback hell.
    

    The cause of callback hell is when people try to write JavaScript in a way where execution happens visually from top to bottom. Lots of people make this mistake! In other languages like C, Ruby or Python there is the expectation that whatever happens on line 1 will finish before the code on line 2 starts running and so on down the file.

  24. Question 12
    Junior

    What is a Polyfill?

    • JavaScript
    Reveal answer

    A polyfill is essentially the specific code (or plugin) that would allow you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in. Polyfills are not part of the HTML5 standard Polyfilling is not limited to Javascript

  25. Question 13
    Junior

    What is the difference between == and === ?

    • JavaScript
    Reveal answer

    == is the abstract equality operator while === is the strict equality operator. The == operator will compare for equality after doing any necessary type conversions. The === operator will not do type conversion, so if two values are not the same type === will simply return false . When using == , funky things can happen, such as:

    1 == '1';
    // true
    1 == [1];
    // true
    1 == true;
    // true
    0 == '';
    // true
    
    0 == '0';
    // true
    0 == false;
    // true
    My advice is never to use the == operator, except for convenience when comparing against null or undefined ,
    where a == null will return true if a is null or undefined .
    var a = null;
    console.log(a == null);
    // true
    console.log(a == undefined);
    // true
    
  26. Question 13
    Junior

    How to check if an object is an array or not? Provide some code.

    • JavaScript
    Reveal answer

    The best way to find whether an object is instance of a particular class or not using toString method from Object.prototype

    var arrayList = [1 , 2, 3];
    

    One of the best use cases of type checking of an object is when we do method overloading in JavaScript. For understanding this let say we have a method called greet which take one single string and also a list of string, so making our greet method workable in both situation we need to know what kind of parameter is being passed, is it single value or list of value?

    function greet(param) {
      if() {
    
        // here have to check whether param is array or not
      }
    else {
    }
    }
    

    However, in above implementation it might not necessary to check type for array, we can check for single value string and put array logic code in else block, let see below code for the same.

    function greet(param) {
      if(typeof param === 'string') {
      }
    else {
      // If param is of type array then this block of code would execute
    }
    }
    

    Now it's fine we can go with above two implementations, but when we have a situation like a parameter can be single value , array , and object type then we will be in trouble. Coming back to checking type of object, As we mentioned that we can use Object.prototype.toString

    if(Object.prototype.toString.call(arrayList) === '[object Array]') {
      console.log('Array!');
    }
    

    If you are using jQuery then you can also used jQuery isArray method:

    if($.isArray(arrayList)) {
      console.log('Array');
    } else {
      console.log('Not an array');
    }
    

    FYI jQuery uses Object.prototype.toString.call internally to check whether an object is an array or not. In modern browser, you can also use:

    Array.isArray(arrayList);
    

    Array.isArray is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5

  27. Question 13
    Junior

    Explain Null and Undefined in JavaScript

    • JavaScript
    Reveal answer

    JavaScript (and by extension TypeScript) has two bottom types: null and undefined . They are intended to mean different things: Something hasn't been initialised : undefined . Something is currently unavailable: null .

  28. Question 14
    Junior

    Explain the same-origin policy with regards to JavaScript.

    • JavaScript
    Reveal answer

    The same-origin policy prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model.

  29. Question 15
    Junior

    What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?

    • JavaScript
    Reveal answer

    Some examples of languages that compile to JavaScript include CoffeeScript, Elm, ClojureScript, PureScript, and TypeScript. Advantages: Fixes some of the longstanding problems in JavaScript and discourages JavaScript anti-patterns. Enables you to write shorter code, by providing some syntactic sugar on top of JavaScript, which I think ES5 lacks, but ES2015 is awesome. Static types are awesome (in the case of TypeScript) for large projects that need to be maintained over time. Disadvantages: Require a build/compile process as browsers only run JavaScript and your code will need to be compiled into JavaScript before being served to browsers. Debugging can be a pain if your source maps do not map nicely to your pre-compiled source. Most developers are not familiar with these languages and will need to learn it. There's a ramp up cost involved for your team if you use it for your projects. Smaller community (depends on the language), which means resources, tutorials, libraries, and tooling would be harder to find. IDE/editor support might be lacking. These languages will always be behind the latest JavaScript standard. Developers should be cognizant of what their code is being compiled to — because that is what would actually be running, and that is what matters in the end.

    Practically, ES2015 has vastly improved JavaScript and made it much nicer to write. I don't really see the need for CoffeeScript these days.

  30. Question 16
    Junior

    Explain the same-origin policy with regards to JavaScript.

    • JavaScript
    Reveal answer

    The same-origin policy prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model.

  31. Question 16
    Junior

    Write a function that would allow you to do this?

    • JavaScript
    Reveal answer

    Problem

    var addSix = createBase(6);
    addSix(10);
    // returns 16
    addSix(21);
    // returns 27
    
    ### Solution
    

    You can create a closure to keep the value passed to the function createBase even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a closure, and it has access to the variables within the outer function, in this case the variable baseNumber .

    function createBase(baseNumber) {
      return function(N) {
        // we are referencing baseNumber here even though it was declared
        // outside of this function. Closures allow us to do this in JavaScript
        return baseNumber + N;
      }
    }
    var addSix = createBase(6);
    addSix(10);
    addSix(21);
    
  32. Question 16
    Junior

    Explain event bubbling and how one may prevent it

    • JavaScript
    Reveal answer

    Event bubbling is the concept in which an event triggers at the deepest possible element, and triggers on parent elements in nesting order. As a result, when clicking on a child element one may exhibit the handler of the parent activating. One way to prevent event bubbling is using event.stopPropagation() or event.cancelBubble on IE < 9.

  33. Question 17
    Junior

    What is the difference between == and === ?

    • JavaScript
    Reveal answer

    == is the abstract equality operator while === is the strict equality operator. The == operator will compare for equality after doing any necessary type conversions. The === operator will not do type conversion, so if two values are not the same type === will simply return false . When using == , funky things can happen, such as:

    1 == '1';
    // true
    1 == [1];
    // true
    1 == true;
    // true
    0 == '';
    // true
    0 == '0';
    // true
    0 == false;
    // true
    My advice is never to use the == operator, except for convenience when comparing against null or undefined ,
    where a == null will return true if a is null or undefined .
    var a = null;
    console.log(a == null);
    // true
    console.log(a == undefined);
    // true
    
  34. Question 17
    Junior

    Write a "mul" function which will properly when invoked as below syntax

    • JavaScript
    Reveal answer

    Problem

    console.log(mul(2)(3)(4));
    // output : 24
    console.log(mul(4)(3)(4));
    // output : 48
    
    ### Solution
    function mul (x) {
      return function (y) {
        // anonymous function
        return function (z) {
          // anonymous function
          return x * y * z;
        };
    };
    }
    

    Here mul function accept the first argument and return anonymous function which take the second parameter and return anonymous function which take the third parameter and return multiplication of arguments which is being passed in successive In JavaScript function defined inside has access to outer function variable and function is the first class object so it can be returned by function as well and passed as argument in another function. A function is an instance of the Object type A function can have properties and has a link back to its constructor method Function can be stored as variable Function can be pass as a parameter to another function Function can be returned from function

  35. Question 17
    Junior

    Implement enqueue and dequeue using only two stacks

    • JavaScript
    Reveal answer

    Enqueue means to add an element, dequeue to remove an element.

    var inputStack = [];
    // First stack
    var outputStack = [];
    // Second stack
    // For enqueue, just push the item into the first stack
    function enqueue(stackInput, item) {
      return stackInput.push(item);
    }
    function dequeue(stackInput, stackOutput) {
      // Reverse the stack such that the first element of the output stack is the
      // last element of the input stack. After that, pop the top of the output to
      // get the first element that was ever pushed into the input stack
      if (stackOutput.length <= 0) {
        while(stackInput.length > 0) {
          var elementToOutput = stackInput.pop();
          stackOutput.push(elementToOutput);
        }
    }
    return stackOutput.pop();
    }
    
  36. Question 18
    Junior

    What's the difference between Host objects and Native objects?

    • JavaScript
    Reveal answer

    Native objects are objects that are part of the JavaScript language defined by the ECMAScript specification, such as String , Math , RegExp , Object , Function , etc. Host objects are provided by the runtime environment (browser or Node), such as window , XMLHTTPRequest , etc.

  37. Question 18
    Junior

    Given a string, reverse each word in the sentence

    • JavaScript
    Reveal answer

    Problem

    For example Welcome to this Javascript Guide! should be become emocleW ot siht tpircsavaJ !ediuG

    Solution

    var string = "Welcome to this Javascript Guide!";// Output becomes !ediuG tpircsavaJ siht ot emocleW
    var reverseEntireSentence = reverseBySeparator(string, "");// Output becomes emocleW ot siht tpircsavaJ !ediuG
    var reverseEachWord = reverseBySeparator(reverseEntireSentence, " ");
    function reverseBySeparator(string, separator) {
      return string.split(separator).reverse().join(separator);
    }
    
  38. Question 19
    Junior

    What is strict mode ?

    • JavaScript
    Reveal answer

    Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.

    // Non-strict code...
    (function(){
      "use strict";// Define your library strictly...
    })();// Non-strict code...
    
  39. Question 20
    Junior

    What is strict mode ?

    • JavaScript
    Reveal answer

    Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.

    // Non-strict code...
    (function(){
      "use strict";// Define your library strictly...
    })();// Non-strict code...
    
  40. Question 20
    Junior

    Explain Values and Types in JavaScript

    • JavaScript
    Reveal answer

    JavaScript has typed values, not typed variables. The following built-in types are available: string number boolean null and undefined object

    symbol (new to ES6)
    

Mid questions

71 questions
  1. Question 1
    Mid

    Write a function that would allow you to do this

    • JavaScript
    Reveal answer

    Problem

    multiply(5)(6);
    
    ### Solution
    You can create a
    

    closure to keep the value of a even after the inner function is returned. The inner function that is being returned is created within an outer function, making it a closure, and it has access to the variables within the outer function, in this case the variable a .

    function multiply(a) {
      return function(b) {
        return a * b;
      }
    }
    multiply(5)(6);
    
  2. Question 1
    Mid

    What is the difference between document load event and document DOMContentLoaded event?

    • JavaScript
    Reveal answer

    The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. window 's load event is only fired after the DOM and all dependent resources and assets have loaded.

  3. Question 1
    Mid

    What is the drawback of creating true private in JavaScript?

    • JavaScript
    Reveal answer

    One of the drawback of creating a true private method in JavaScript is that they are very memory inefficient because a new copy of the method would be created for each instance.

    var Employee = function (name, company, salary) {
      this.name = name || "";
      //Public attribute default value is null
      this.company = company || "";
      //Public attribute default value is null
      this.salary = salary || 5000;
      //Public attribute default value is null
      // Private method
      var increaseSalary = function () {
        this.salary = this.salary + 1000;
      };// Public method
    this.dispalyIncreasedSalary = function() {
      increaseSalary();
      console.log(this.salary);
    };
    };// Create Employee class object
    var emp1 = new Employee("John","Pluto",3000);
    // Create Employee class object
    var emp2 = new Employee("Merry","Pluto",2000);
    // Create Employee class object
    var emp3 = new Employee("Ren","Pluto",2500);
    

    Here each instance variable emp1 , emp2 , emp3 has own copy of increaseSalary private method. So as recommendation don't go for a private method unless it's necessary.

  4. Question 2
    Mid

    What is export default in JavaScript?

    • Node.js JavaScript
    Reveal answer

    As the name says, it's used to export functions, objects, classes or expressions from script files or modules Utiliites.js

    export function cube(x) {
      return x * x * x;
    }
    export const foo = Math.PI + Math.SQRT2;
    

    This can be imported and used as App.js

    import { cube, foo } from 'Utilities';
    console.log(cube(3));
    // 27
    console.log(foo);
    // 4.555806215962888
    

    Or

    import * as utilities from 'Utilities';
    console.log(utilities.cube(3));
    // 27
    console.log(utilities.foo);
    // 4.555806215962888
    

    When export default is used, this is much simpler. Script files just exports one thing. cube.js

    export default function cube(x) {
      return x * x * x;
    };
    and used as
    App.js
    import Cube from 'cube';
    console.log(Cube(3));
    // 27
    
  5. Question 2
    Mid

    When should we use generators in ES6?

    • JavaScript
    Reveal answer

    To put it simple, generator has two features: one can choose to jump out of a function and let outer code to determine when to jump back into the function. the control of asynchronous call can be done outside of your code The most important feature in generators — we can get the next value in only when we really need it, not all the values at once. And in some situations it can be very convenient.

  6. Question 2
    Mid

    How would you read files in sequence in Node.js? Provide a code example

    • Node.js JavaScript
    Reveal answer

    If you want to read the files in sequence, just use a modern for … of loop, in which await will work as expected:

    async function printFiles () {
      const files = await getFilePaths();
      for (const file of files) {
        const contents = await fs.readFile(file, 'utf8');
        console.log(contents);
      }
    }
    
  7. Question 2
    Mid

    What's the difference between .call and .apply ?

    • JavaScript
    Reveal answer

    Both .call and .apply are used to invoke functions and the first parameter will be used as the value of this within the function. However, .call takes in comma-separated arguments as the next arguments while .apply takes in an array of arguments as the next argument. An easy way to remember this is C for call and comma- separated and A for apply and an array of arguments.

    function add(a, b) {
      return a + b;
    }
    
    console.log(add.call(null, 1, 2));
    // 3
    console.log(add.apply(null, [1, 2]));
    // 3
    
  8. Question 3
    Mid

    Explain the difference between Object.freeze() vs const

    • JavaScript
    Reveal answer

    const and Object.freeze are two completely different things.

    const applies to bindings ("variables"). It creates an immutable binding, i.e. you cannot assign a new value
    

    to the binding.

    const person = {
      name: "Leonardo"
    };
    let animal = {
      species: "snake"
    };
    person = animal;
    // ERROR "person" is read-only
    

    Object.freeze works on values, and more specifically, object values. It makes an object immutable, i.e. you cannot change its properties.

    let person = {
      name: "Leonardo"
    };
    let animal = {
      species: "snake"
    };
    Object.freeze(person);
    person.name = "Lima";
    //TypeError: Cannot assign to read only property 'name' of object
    console.log(person);
    
  9. Question 3
    Mid

    Explain how Heap Sort works

    • Heaps and Maps Sorting Data Structures JavaScript
    Reveal answer

    Heapsort is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort: like that algorithm, it divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. The improvement consists of the use of a heap data structure rather than a linear-time search to find the maximum. A heap is a complete binary tree (every level filled as much as possible beginning at the left side of the tree) that follows this condition: the value of a parent element is always greater than the values of its left and right child elements. So, by taking advantage of this property, we can pop off the max of the heap repeatedly and establish a sorted array. In an array representation of a heap binary tree, this essentially means that for a parent element with an index of i , its value must be greater than its left child [2i+1] and right child [2i+2] (if it has one). The HeapSort steps are: Create a max heap from the unsorted list Swap the max element, located at the root, with the last element Re- heapify or rebalance the array again to establish the max heap order. The new root is likely not in its correct place. Repeat Steps 2–3 until complete (when the list size is 1)

    Visualisation: Complexity: Complexity Analysis: Time Complexity: O(n log n) Space Complexity: O(n log n) Best:

    O(
    n log n)
    Average:
    O(
    n log n)
    Worst:
    O(
    n log n)
    Implementation:
    JS
    var a = [ 9, 10, 2, 1, 5, 4, 3, 6, 8, 7, 13 ];
    function swap(a, i, j) {
      var tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }
    function max_heapify(a, i, length) {
      while (true) {
        var left = i*2 + 1;
    
        var right = i*2 + 2;
        var largest = i;
        if (left < length && a[left] > a[largest]) {
          largest = left;
        }
      if (right < length && a[right] > a[largest]) {
        largest = right;
      }
    if (i == largest) {
      break;
    }
    swap(a, i, largest);
    i = largest;
    }
    }
    function heapify(a, length) {
      for (var i = Math.floor(length/2); i >= 0; i--) {
        max_heapify(a, i, length);
      }
    }
    function heapsort(a) {
      heapify(a, a.length);
      for (var i = a.length - 1; i > 0; i--) {
        swap(a, i, 0);
        max_heapify(a, 0, i-1);
      }
    }
    heapsort(a);
    PY
    def heapsort(lst):
    """
    

    Sorts list in-place with a heap. """

    last_element = len(lst) - 1
    lst = heapify(lst)
    while last_element >= 0:
    # swap the max element with the last element
    # like popping off the max
    swap(lst, 0, last_element)
    # rebalance the remaining heap, from index 0 to last_element exclusive
    balance(lst, 0, last_element)
    last_element -= 1
    

    return lst def heapify(lst): """ Turns list into a max heap in-place, in linear time. Begins process at 1 depth before leaves. """# initiliazes cur at halfway point based on length of list

    if len(lst) % 2 == 0:
    cur = len(lst) / 2 - 2
    else:
    cur = len(lst) / 2 - 1
    
    # rebalance until reached beginning of list
    while cur >= 0:
    balance(lst, cur)
    cur -= 1
    

    return lst def swap(lst, i, last_element): """ Swaps two elments of a list - the current and last in this case. """ lst[i], lst[last_element] = lst[last_element], lst[i] def balance(lst, cur, last_element=None): """ Rebalances heap. Keyword arg for last_element allows for re-use in both heapify and heapsort. """ if last_element is None:

    last_element = len(lst)
    while cur < last_element:
    left_child = 2*cur + 1
    right_child = 2*cur + 2
    # check to see if we're out of bounds for the children
    # this is necessary for even length heaps
    if left_child >= last_element:
    

    return

    if right_child >= last_element:
    # since left child is in bounds, check for swap
    if lst[cur] < lst[left_child]:
    swap(lst, cur, left_child)
    

    return

    if we're in bounds for both children, find the max

    max_child = find_max_child(lst, left_child, right_child)

    check to see if swap needed

    if lst[cur] < lst[max_child]:
    swap(lst, cur, max_child)
    cur = max_child
    
  10. Question 3
    Mid

    Check if parentheses are balanced using Stack

    • Stacks Java Python JavaScript
    Reveal answer

    One of the most important applications of stacks is to check if the parentheses are balanced in a given expression. The compiler generates an error if the parentheses are not matched. Here are some of the balanced and unbalanced expressions: balanced parentheses Algorithm

    1. Declare a character stack which will hold an array of all the opening parenthesis.

    2. Now traverse the expression string exp.

    3. If the current character is a starting bracket ( ( or { or [ ) then push it to stack.

    4. If the current character is a closing bracket ( ) or } or ] ) then pop from stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced.

    5. After complete traversal, if there is some starting bracket left in stack then “not balanced” Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n) We are traversing through each character of string, Time complexity

    O(
    n) .
    

    We are storing the opposite parentheses characters in the stack, in the worst case there can be all the opposite characters in the string, Space complexity

    O(
    n) .
    Implementation:
    JS
    let isMatchingBrackets = function (str) {
      let stack = [];
      let map = {
        '(': ')',
        '[': ']',
        '{': '}'
      }
    for (let i = 0; i < str.length; i++) {
      // If character is an opening brace add it to a stack
      if (str[i] === '(' || str[i] === '{' || str[i] === '[' ) {
          stack.push(str[i]);
        }
      // If that character is a closing brace, pop from the stack, which will also reduce the length
    

    of the stack each time a closing bracket is encountered.

    else {
      let last = stack.pop();
      //If the popped element from the stack, which is the last opening brace doesn’t match the
    

    corresponding closing brace in the map, then return false

    if (str[i] !== map[last]) {return false};
    }
    }
    // By the completion of the for loop after checking all the brackets of the str, at the end, if the
    

    stack is not empty then fail

    if (stack.length !== 0) {return false};
    return true;
    }
    Java
    public static boolean balancedParenthensies(String s) {
      Stack<Character> stack = new Stack<Character>();
      for(int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if(c == '[' || c == '(' || c == '{' ) {
            stack.push(c);
          } else if(c == ']') {
            if(stack.isEmpty() || stack.pop() != '[') {
              return false;
            }
        } else if(c == ')') {
          if(stack.isEmpty() || stack.pop() != '(') {
            return false;
          }
      } else if(c == '}') {
    
    if(stack.isEmpty() || stack.pop() != '{') {
        return false;
      }
    }
    }
    return stack.isEmpty();
    }
    PY
    open_list = ["[","{","("]
      close_list = ["]","}",")"]# Function to check parentheses
    def check(myStr):
    stack = []
    for i in myStr:
    if i in open_list:
    stack.append(i)
    elif i in close_list:
    pos = close_list.index(i)
    if ((len(stack) > 0) and
    (open_list[pos] == stack[len(stack)-1])):
    stack.pop()
    else:
    

    return "Unbalanced"

    if len(stack) == 0:
    

    return "Balanced" else: return "Unbalanced"

  11. Question 3
    Mid

    What is export default in JavaScript?

    • Node.js JavaScript
    Reveal answer

    As the name says, it's used to export functions, objects, classes or expressions from script files or modules Utiliites.js

    export function cube(x) {
      return x * x * x;
    }
    export const foo = Math.PI + Math.SQRT2;
    

    This can be imported and used as App.js

    import { cube, foo } from 'Utilities';
    console.log(cube(3));
    // 27
    console.log(foo);
    // 4.555806215962888
    

    Or

    import * as utilities from 'Utilities';
    console.log(utilities.cube(3));
    // 27
    console.log(utilities.foo);
    // 4.555806215962888
    

    When export default is used, this is much simpler. Script files just exports one thing. cube.js

    export default function cube(x) {
      return x * x * x;
    };
    and used as
    App.js
    import Cube from 'cube';
    console.log(Cube(3));
    // 27
    
  12. Question 4
    Mid

    Why should we use ES6 classes?

    • JavaScript
    Reveal answer

    Some reasons you might choose to use Classes: The syntax is simpler and less error-prone. It's much easier (and again, less error-prone) to set up inheritance hierarchies using the new syntax than with the old. class defends you from the common error of failing to use new with the constructor function (by having the constructor throw an exception if this isn't a valid object for the constructor).

    Calling the parent prototype's version of a method is much simpler with the new syntax than the old ( super.method() instead of ParentConstructor.prototype.method.call(this) or

    Object.getPrototypeOf(Object.getPrototypeOf(this)).method.call(this) ).
    

    Consider:

    // **ES5**
    var Person = function(first, last) {
      if (!(this instanceof Person)) {
        throw new Error("Person is a constructor function, use new with it");
      }
    this.first = first;
    this.last = last;
    };
    Person.prototype.personMethod = function() {
      return "Result from personMethod: this.first = " + this.first + ", this.last = " + this.last;
    };
    var Employee = function(first, last, position) {
      if (!(this instanceof Employee)) {
        throw new Error("Employee is a constructor function, use new with it");
      }
    Person.call(this, first, last);
    this.position = position;
    };
    Employee.prototype = Object.create(Person.prototype);
    Employee.prototype.constructor = Employee;
    Employee.prototype.personMethod = function() {
      var result = Person.prototype.personMethod.call(this);
      return result + ", this.position = " + this.position;
    };
    Employee.prototype.employeeMethod = function() {
      // ...
    };
    

    And the same with ES6 classes:

    // ***ES2015+**
    class Person {
      constructor(first, last) {
        this.first = first;
        this.last = last;
      }
    personMethod() {
      // ...
    }
    }
    class Employee extends Person {
      constructor(first, last, position) {
        super(first, last);
        this.position = position;
      }
    employeeMethod() {
      // ...
    }
    }
    
  13. Question 4
    Mid

    Explain the difference between Object.freeze() vs const

    • JavaScript
    Reveal answer

    const and Object.freeze are two completely different things.

    const applies to bindings ("variables"). It creates an immutable binding, i.e. you cannot assign a new value
    

    to the binding.

    const person = {
      name: "Leonardo"
    };
    let animal = {
      species: "snake"
    };
    person = animal;
    // ERROR "person" is read-only
    

    Object.freeze works on values, and more specifically, object values. It makes an object immutable, i.e. you cannot change its properties.

    let person = {
      name: "Leonardo"
    };
    let animal = {
      species: "snake"
    };
    Object.freeze(person);
    person.name = "Lima";
    //TypeError: Cannot assign to read only property 'name' of object
    console.log(person);
    
  14. Question 4
    Mid

    Write a program for Recursive Binary Search

    • Searching Java Python JavaScript
    Reveal answer

    The first difference is that the while loop from iterative approach is replaced by a recursive call back to the same method with the new values of low and high passed to the next recursive invocation along with Array and key or target element. The second difference is that instead of returning false when the while loop exits in the iterative version, in case of the recursive version, the condition of low > high is checked at the beginning of the next level of recursion and acts as the boundary condition for stopping further recursive calls by returning false. Also, note that the recursive invocations of binarySearch() return back the search result up the recursive call stack so that true or false return value is passed back up the call stack without any further processing. To further optimize the solution, in term of running time, we could consider implement the tail-recursive solution, where the stack trace of the algorithm would not pile up, which leads to a less memory footprint during the running time. To have the tail-recursive solution, the trick is to simply return the result from the next recursive function instead of further processing. Implementation: JS

    function binarySearch(sortedArray, searchValue, minIndex, maxIndex) {
      var currentIndex;
      var currentElement;
    
      while (minIndex <= maxIndex) {
        // Find the value of the middle of the array
        var middleIndex = (minIndex + maxIndex) / 2 | 0;
        currentElement = sortedArray[middleIndex];
        // It's the same as the value in the middle - we can return!
        if (currentElement === searchValue)
        {
          return middleIndex;
        }
      // Is the value less than the value in the middle of the array
      if (currentElement < searchValue) {
        return binarySearch(sortedArray, searchValue, middleIndex + 1, maxIndex);
      }
    // Is the value greater than the value in the middle of the array
    if (currentElement > searchValue) {
      return binarySearch(sortedArray, searchValue, minIndex, middleIndex - 1);
    }
    }
    return -1;
    }
    Java
    // Find out if a key x exists in the sorted array
    // A[low..high] or not using binary search algorithm
    public static int binarySearch(int[] A, int low, int high, int x) {
      // Base condition (search space is exhausted)
      if (low > high) {
        return -1;
      }// we find the mid value in the search space and
    // compares it with key value
    int mid = (low + high) / 2;// overflow can happen. Use beleft
    // int mid = low + (high - low) / 2;
    // Base condition (key value is found)
    if (x == A[mid]) {
      return mid;
    }// discard all elements in the right search space
    // including the mid element
    else if (x < A[mid]) {
      return binarySearch(A, low, mid - 1, x);
    }// discard all elements in the left search space
    // including the mid element
    else {
      return binarySearch(A, mid + 1, high, x);
    }
    }
    PY
    class Solution:
    def searchInsert(self, nums, target):
    return self.tail_recursive_searchInsert(0, nums, target)
    def tail_recursive_searchInsert(self, start, nums, target):
    
    """
    :type nums: List[int]
    :type target: int
    :rtype: int
    

    return the position to insert a new element into the sorted list. Note: the solution can be implemented in a recursive way. """

    size = len(nums)
    if (size == 0):
    # empty input list, early exit
    

    return start

    mid_index = int(size/2)
    if (nums[mid_index] == target):
    

    return start + mid_index

    elif (nums[mid_index] > target):
    return self.tail_recursive_searchInsert(
    start, nums[0:mid_index], target)
    else:
    return self.tail_recursive_searchInsert(
    start+mid_index+1, nums[mid_index+1:], target)
    
  15. Question 4
    Mid

    Explain how Merge Sort works

    • Divide & Conquer Sorting JavaScript
    Reveal answer

    Merge sort is a divide-and-conquer, comparison-based sorting algorithm based on the idea of breaking down a list into several sub-lists until each sublist consists of a single element and merging those sublists in a manner that results into a sorted list. Most implementations produce a stable sort, which means that the order of equal elements is the same in the input and output. Can be used as external sorting (when the data to be sorted is too large to fit into memory). There are two methods for implementing a Merge Sort algorithm: The Top-Down (recursive) approach. Given an array of size N, the algorithm recursively breaks the array in half and then merges the results together. The Bottom-Up (iterative) approach. Rather than breaking the overall array into distinct pieces, bottum-up mergesort loops over the array using intervals of varying sizes. Each interval is sorted and merged together; subsequent loops over the array have larger intervals, effectively merging our previously sorted (smaller) intervals together. Complexity Analysis: Time Complexity: O(n log n) Space Complexity: O(n log n) The list of size n is divided into a max of log n parts (the height of the conquer step tree is log n + 1 for a given n ), and the merging of all sublists into a single list takes O(n) time, the worst case run time of this algorithm is O(n log n) .

    Space complexity is always Ω(n) as you have to store the elements somewhere. Additional space complexity can be O(n) in an implementation using arrays and O(1) in linked list implementations. In practice implementations using lists need additional space for list pointers, so unless you already have the list in memory it shouldn't matter. Implementation: JS

    The Top-Down (recursive) approach
    function mergeSort(arr) {
      if (arr.length < 2) {
        return arr;
      }
    let midpoint = Math.floor(arr.length / 2);
    let leftHalf = arr.slice(0, midpoint);
    //slice an array of left-half items
    let rightHalf = arr.slice(midpoint);
    //slice an array of right-half items
    //recurse into each half until arrays are 1 item each
    //then merge() the sorted arrays on each layer of the stack
    return merge(mergeSort(leftHalf), mergeSort(rightHalf));
    }//first time this merge() gets called, the arr's are both 1 element long
    //on each layer of the stack the arrs will be doubled and always be sorted
    function merge(arrA, arrB) {
      let a = 0;
      let b = 0;
      let result = [];
      while (a < arrA.length && b < arrB.length) {
        if (arrA[a] < arrB[b]) {
          result.push(arrA[a]);
          a++;
        } else {
          result.push(arrB[b]);
          b++;
        }
    }//using slice to concat remaining items left in either arrA or arrB
    return result.concat(arrA.slice(a)).concat(arrB.slice(b));
    }
    
    //usage:
    mergeSort([4,2,8,3,6,9,1]);
    //=> [1,2,3,4,6,8,9]
    The Bottom-Up (iterative) approach
    function mergeSort(arr) {
      var sorted = arr.slice(),
      n = sorted.length,
      buffer = new Array(n);
      for (var size = 1; size < n; size *= 2) {
        for (var leftStart = 0; leftStart < n; leftStart += 2 * size) {
          var left = leftStart,
          right = Math.min(left + size, n),
          leftLimit = right,
          rightLimit = Math.min(right + size, n),
          i = left;
          while (left < leftLimit && right < rightLimit) {
            if (sorted[left] <= sorted[right]) {
              buffer[i++] = sorted[left++];
            } else {
              buffer[i++] = sorted[right++];
            }
        }
      while (left < leftLimit) {
        buffer[i++] = sorted[left++];
      }
    while (right < rightLimit) {
      buffer[i++] = sorted[right++];
    }
    }
    var temp = sorted,
    sorted = buffer,
    buffer = temp;
    }
    return sorted;
    }
    PY
    The Top-Down (recursive) approach
    def merge_lists(left_sublist,right_sublist):
    i,j = 0,0
    result = []
    

    #iterate through both left and right sublist

    while i<len(left_sublist) and j<len(right_sublist):
    

    #if left value is lower than right then append it to the result

    if left_sublist[i] <= right_sublist[j]:
    result.append(left_sublist[i])
    i += 1
    else:
    

    #if right value is lower than left then append it to the result

    result.append(right_sublist[j])
    j += 1
    

    #concatenate the rest of the left and right sublists

    result += left_sublist[i:]
    result += right_sublist[j:]
    

    #return the result return result def merge_sort(input_list): #if list contains only 1 element return it

    if len(input_list) <= 1:
    

    return input_list else:

    #split the lists into two sublists and recursively split sublists

    midpoint = int(len(input_list)/2)
    left_sublist = merge_sort(input_list[:midpoint])
    right_sublist = merge_sort(input_list[midpoint:])
    

    #return the merged list using the merge_list function above return merge_lists(left_sublist,right_sublist) #test run

    number_list = [3,1,5,3,2,5,8,2,9,6,12,53,75,22,83,123,12123]
    print merge_sort(number_list)
    The Bottom-Up (iterative) approach
    def merge_sort_iterative(data):
    for j in range(1, len(data)):
    j *= 2
    for i in range(0,len(data),j):
    data_1 = data[i:i+(j/2)]
    data_2 = data[i+(j/2):j-i]
    l = m = 0
    while l < len(data_1) and m < len(data_2):
    if data_1[l] < data_2[m]:
    m += 1
    elif data_1[l] > data_2[m]:
    data_1[l], data_2[m] = data_2[m], data_1[l]
    l += 1
    data[i:i+(j/2)], data[i+(j/2):j-i] = data_1, data_2
    

    return data

  16. Question 4
    Mid

    Explain the differences on the usage of foo between function foo() {} and var foo = function() {}

    • JavaScript
    Reveal answer

    The former is a function declaration while the latter is a function expression. The key difference is that function declarations have its body hoisted but the bodies of function expressions are not (they have the same hoisting behavior as variables). If you try to invoke a function expression before it is defined, you will get an Uncaught TypeError: XXX is not a function error. Function Declaration

    foo();
    // 'FOOOOO'
    function foo() {
      console.log('FOOOOO');
    }
    Function Expression
    
    foo();
    // Uncaught TypeError: foo is not a function
    var foo = function() {
      console.log('FOOOOO');
    };
    
  17. Question 5
    Mid

    Suggest one simple way of removing duplicates from an array using ES6

    • JavaScript
    Reveal answer

    Let's use the Set() object. Sets are a new object type with ES6 (ES2015) that allow to create collections of unique values. The values in a set can be either simple primitives like strings or integers, but more complex object types like object literals or arrays can also be part of a set. Consider:

    const array = [1, 4, 99, 3, 1, 4, 15];
    const noDups = Array.from(new Set(array));
    console.log(noDups);
    //[1, 4, 99, 3, 15]
    
  18. Question 5
    Mid

    What is the preferred syntax for defining enums in JavaScript?

    • JavaScript
    Reveal answer

    Since 1.8.5 it's possible to seal and freeze the object, so define the above as:

    var DaysEnum = Object.freeze({
      "monday": 1,
      "tuesday": 2,
      "wednesday": 3,
      ...
    })
    

    or

    var DaysEnum = {
      "monday": 1,
      "tuesday": 2,
      "wednesday": 3,
      ...
    }
    Object.freeze(DaysEnum)
    

    and voila! JS enums. However, this doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:

    let day = DaysEnum.tuesday
    day = 298832342
    // goes through without any errors
    
  19. Question 5
    Mid

    Explain what is Interpolation Search

    • Searching Python JavaScript
    Reveal answer

    Interpolation Search is an algorithm similar to Binary Search for searching for a given target value in a sorted array. It is an improvement over Binary Search for instances, where the values in a sorted array areuniformly distributed. The binary search always chooses the middle of the remaining search space. On a contrast Interpolation search, at each search step, calculates (using interpolation formula) where in the remaining search space the targetmight be present, based on the low and high values of the search space and the value of the target. For example, if the value of the key is closer to the last element, interpolation search is likely to start search toward the end side. The value actually found at this estimated position is then compared to the target value. If it is not equal, then depending on the comparison, the remaining search space is reduced to the part before or after the estimated position. The idea of the** interpolation formula** or partitioning logic is to return higher value of pos when element to be searched is closer to arr[hi] . And smaller value when closer to arr[low].

    arr[] ==> Array where elements need to be searched
    x ==> Element to be searched
    low ==> Starting index in arr[]
    hi ==> Ending index in arr[]
    pos = low + [ (x-arr[low])*(hi-low) / (arr[hi]-arr[Low]) ]
    Complexity Analysis:
    Time Complexity: O(log log n) Space Complexity: O(log log n)
    

    In the interpolation search algorithm, the midpoint is computed in such a way that it gives a higher probability of obtaining our search term faster. The worst case complexity of interpolation search is

    O(
    n) . However, its
    average case complexity, under the assumption that the keys are uniformly distributed, is _ O(log log N) .
    

    It can be proven that Interpolation Search repeatedly reducing the problem to a subproblem of size that is the square root of the original problem size, and algorithm will terminate after

    O(log log n) steps (see proof
    here). When the values are equally dispersed into the interval this search algorithm can be extremely useful –
    way faster than the binary search (that divides searching space
    by half).
    Implementation:
    JS
    const interpolationSearch = (array, key) => {// if array is empty.
      if (!array.length) {
        return -1;
      }
    let low = 0;
    let high = array.length - 1;
    while (low <= high && key >= array[low] && x <= array[high]) {// calculate position with
      let pos = low + Math.floor(((high - low) * (key - array[low])) / (array[high] - array[low]));// if all elements are same then we'll have divide by 0 or 0/0
      // which may cause NaN
      pos = Number.isNaN(pos) ? low : pos;
      if (array[pos] === key) {
        return pos;
      }
    if (array[pos] > key) {
      high = pos - 1;
    } else {
      low = pos + 1;
    }
    }// not found.
    return -1;
    };
    PY
    
    def InterpolationSearch(data, key):
    left = 0
    right = len(data) - 1
    while left < right:
    idx = int( (right - left) * (key - data[left]) / (data[right] - data[left]) ) + left
    if data[idx] is key:
    

    return idx elif data[idx] < key:

    left = idx + 1
    else:
    right = idx - 1
    

    return -1

  20. Question 5
    Mid

    Explain how Heap Sort works

    • Heaps and Maps Sorting Data Structures JavaScript
    Reveal answer

    Heapsort is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort: like that algorithm, it divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. The improvement consists of the use of a heap data structure rather than a linear-time search to find the maximum. A heap is a complete binary tree (every level filled as much as possible beginning at the left side of the tree) that follows this condition: the value of a parent element is always greater than the values of its left and right child elements. So, by taking advantage of this property, we can pop off the max of the heap repeatedly and establish a sorted array. In an array representation of a heap binary tree, this essentially means that for a parent element with an index of i , its value must be greater than its left child [2i+1] and right child [2i+2] (if it has one). The HeapSort steps are: Create a max heap from the unsorted list Swap the max element, located at the root, with the last element Re- heapify or rebalance the array again to establish the max heap order. The new root is likely not in its correct place. Repeat Steps 2–3 until complete (when the list size is 1)

    Visualisation: Complexity: Complexity Analysis: Time Complexity: O(n log n) Space Complexity: O(n log n) Best:

    O(
    n log n)
    Average:
    O(
    n log n)
    Worst:
    O(
    n log n)
    Implementation:
    JS
    var a = [ 9, 10, 2, 1, 5, 4, 3, 6, 8, 7, 13 ];
    function swap(a, i, j) {
      var tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
    }
    function max_heapify(a, i, length) {
      while (true) {
        var left = i*2 + 1;
    
        var right = i*2 + 2;
        var largest = i;
        if (left < length && a[left] > a[largest]) {
          largest = left;
        }
      if (right < length && a[right] > a[largest]) {
        largest = right;
      }
    if (i == largest) {
      break;
    }
    swap(a, i, largest);
    i = largest;
    }
    }
    function heapify(a, length) {
      for (var i = Math.floor(length/2); i >= 0; i--) {
        max_heapify(a, i, length);
      }
    }
    function heapsort(a) {
      heapify(a, a.length);
      for (var i = a.length - 1; i > 0; i--) {
        swap(a, i, 0);
        max_heapify(a, 0, i-1);
      }
    }
    heapsort(a);
    PY
    def heapsort(lst):
    """
    

    Sorts list in-place with a heap. """

    last_element = len(lst) - 1
    lst = heapify(lst)
    while last_element >= 0:
    # swap the max element with the last element
    # like popping off the max
    swap(lst, 0, last_element)
    # rebalance the remaining heap, from index 0 to last_element exclusive
    balance(lst, 0, last_element)
    last_element -= 1
    

    return lst def heapify(lst): """ Turns list into a max heap in-place, in linear time. Begins process at 1 depth before leaves. """# initiliazes cur at halfway point based on length of list

    if len(lst) % 2 == 0:
    cur = len(lst) / 2 - 2
    else:
    cur = len(lst) / 2 - 1
    
    # rebalance until reached beginning of list
    while cur >= 0:
    balance(lst, cur)
    cur -= 1
    

    return lst def swap(lst, i, last_element): """ Swaps two elments of a list - the current and last in this case. """ lst[i], lst[last_element] = lst[last_element], lst[i] def balance(lst, cur, last_element=None): """ Rebalances heap. Keyword arg for last_element allows for re-use in both heapify and heapsort. """ if last_element is None:

    last_element = len(lst)
    while cur < last_element:
    left_child = 2*cur + 1
    right_child = 2*cur + 2
    # check to see if we're out of bounds for the children
    # this is necessary for even length heaps
    if left_child >= last_element:
    

    return

    if right_child >= last_element:
    # since left child is in bounds, check for swap
    if lst[cur] < lst[left_child]:
    swap(lst, cur, left_child)
    

    return

    if we're in bounds for both children, find the max

    max_child = find_max_child(lst, left_child, right_child)

    check to see if swap needed

    if lst[cur] < lst[max_child]:
    swap(lst, cur, max_child)
    cur = max_child
    
  21. Question 6
    Mid

    What is a closure, and how/why would you use one?

    • JavaScript
    Reveal answer

    A closure is the combination of a function and the lexical environment within which that function was declared. The word "lexical" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Closures are functions that have access to the outer (enclosing) function's variables—scope chain even after the outer function has returned. Why would you use one? Data privacy / emulating private methods with closures. Commonly used in the module pattern. Partial applications or currying.

  22. Question 6
    Mid

    Suggest one simple way of removing duplicates from an array using ES6

    • JavaScript
    Reveal answer

    Let's use the Set() object. Sets are a new object type with ES6 (ES2015) that allow to create collections of unique values. The values in a set can be either simple primitives like strings or integers, but more complex object types like object literals or arrays can also be part of a set. Consider:

    const array = [1, 4, 99, 3, 1, 4, 15];
    const noDups = Array.from(new Set(array));
    console.log(noDups);
    //[1, 4, 99, 3, 15]
    
  23. Question 6
    Mid

    What is a Jump (or Block) Search?

    • Searching Python JavaScript
    Reveal answer
    **Jump Search **(also referred to as Block Search) is an algorithm used to search for the position of a target
    element on a
    sorted data collection or structure.
    

    The fundamental idea behind this searching technique is to search fewer number of elements compared to linear search algorithm (which scans every element in the array to check if it matches with the element being searched or not). This can be done by skipping some fixed number of array elements or jumping ahead by fixed number of steps in every iteration. Lets consider a sorted array A[] of size n , with indexing ranging between 0 and n-1, and element x that needs to be searched in the array A[] . For implementing this algorithm, a block of size m is also required, that can be skipped or jumped in every iteration. Thus, the algorithm works as follows: Iteration 1: if ( x==A[0] ), then success, else, if ( x > A[0] ), then jump to the next block. Iteration 2: if ( x==A[m] ), then success, else, if ( x > A[m] ), then jump to the next block. Iteration 3: if ( x==A[2m] ), then success, else, if ( x > A[2m] ), then jump to the next block. At any point in time, if ( x < A[km] ), then a linear search is performed from index A[(k-1)m] to A[km] Consider the following inputs:

    A[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 77, 89, 101, 201, 256, 780}
    item = 77
    

    The single most important advantage of jump search when compared to binary search is that it does not rely on the division operator ( / ). Jump Search is highly efficient for searching arrays especially when its only-seeks-forward behavior is favorable - its average performance makes it sit somewhere between Binary Search with its

    O(
    log n)
    

    complexity and Linear Search with an

    O(
    n) complexity.
    
    Complexity Analysis:
    Time Complexity: O(sqrt n) Space Complexity: O(sqrt n)
    

    Jump Search would consecutively jump to its very last block searching for the target element, in turn causing an n/m number of jumps. Additionally, if the last element’s value of this block was greater than the target element, Jump Search would perform a linear search with m-1 iterations. This causes Jump Search to make (n/m) jumps with additional m-1 iterations. This value is minimum at m = √n . Therefore, the optimum block size is √n . Accordingly, Jump Search maintains a worst and average case efficiency of O(√n) complexity. The space complexity of this algorithm is

    O(
    1) since it does not require any additional temporary variables
    

    or data structures for its implementation. Implementation: JS

    function jumpSearch(arrayToSearch, valueToSearch){
      var length = arrayToSearch.length;
      var step = Math.floor(Math.sqrt(length));
      var index = Math.min(step, length)-1;
      var lowerBound = 0;
      while (arrayToSearch[Math.min(step, length)-1] < valueToSearch)
      {
        lowerBound = step;
        step += step;
        if (lowerBound >= length){
          return -1;
        }
    }
    var upperBound = Math.min(step, length);
    while (arrayToSearch[lowerBound] < valueToSearch)
    {
      lowerBound++;
      if (lowerBound == upperBound){
        return -1;
      }
    }
    if (arrayToSearch[lowerBound] == valueToSearch){
      return lowerBound;
    }
    return -1;
    }
    Java
    package Searches;
    public class JumpSearch implements SearchAlgorithm {
      public static void main(String[] args) {
        JumpSearch jumpSearch = new JumpSearch();
        Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int i = 0; i < array.length; i++) {
          assert jumpSearch.find(array, i) == i;
        }
      assert jumpSearch.find(array, -1) == -1;
      assert jumpSearch.find(array, 11) == -1;
    }/**
    * Jump Search algorithm implements
    *
    
    * @param array the array contains elements
    * @param key to be searched
    * @return index of {@code key} if found, otherwise <tt>-1</tt>
    */
    @Override
    public <T extends Comparable<T>> int find(T[] array, T key) {
      int length = array.length;
      /* length of array */
      int blockSize = (int) Math.sqrt(length);
      /* block size to be jumped */
      int limit = blockSize;
      while (key.compareTo(array[limit]) > 0 && limit < array.length - 1) {
        limit = Math.min(limit + blockSize, array.length - 1);
      }
    for (int i = limit - blockSize; i <= limit; i++) {
      if (array[i] == key) {
        /* execute linear search */
        return i;
      }
    }
    return -1;
    /* not found */
    }
    }
    PY
    import math
    def jump_search(arr,search):
    low = 0
    interval = int(math.sqrt(len(arr)))
    for i in range(0,len(arr),interval):
    if arr[i] < search:
    low = i
    elif arr[i] == search:
    

    return i else: break

    bigger number is found

    c=low
    for j in arr[low:]:
    if j==search:
    

    return c

    c+=1
    

    return "Not found" arr = [ i for i in range(1,200,15)]

    res = jump_search(arr, 196)
    print(res)
    # prints 13
    
  24. Question 6
    Mid

    Get the N-th Fibonacci number with O(n) time and O(1) space complexity

    • Fibonacci Series JavaScript
    Reveal answer

    Consider:

    function fibs(n){
      let [a, b] = [0, 1]
      while (n > 0){
        [a, b] = [b, a + b]
        n -= 1
      }
    

    return a

    }
    
    This solution is in linear O(n) time complexity, and constant O(1) space complexity. The number of loops it
    

    takes to calculate the nth fib number will still increase at a linear rate as n increases, but we are overriding the previous numbers in the sequence as we build it out, making the space complexity constant for any input n. It's also called Iterative Top-Down Approach. Implementation: JS

    function fibs(n){
      let [a, b] = [0, 1]
      while (n > 0){
        [a, b] = [b, a + b]
        n -= 1
      }
    

    return a

    }
    PY
    def fib_iterative(n):
    a, b = 0, 1
    while n > 0:
    a, b = b, a + b
    n -= 1
    

    return a

  25. Question 7
    Mid

    What's a typical use case for anonymous functions?

    • JavaScript
    Reveal answer

    They can be used in IIFEs to encapsulate some code within a local scope so that variables declared in it do not leak to the global scope.

    (function() {
      // Some code here.
    })();
    

    As a callback that is used once and does not need to be used anywhere else. The code will seem more self- contained and readable when handlers are defined right inside the code calling them, rather than having to search elsewhere to find the function body.

    setTimeout(function() {
      console.log('Hello world!');
    }, 1000);
    Arguments to functional programming constructs or Lodash (similar to callbacks).
    
    const arr = [1, 2, 3];
    const double = arr.map(function(el) {
      return el * 2;
    });
    console.log(double);
    // [2, 4, 6]
    
  26. Question 7
    Mid

    Explain Function.prototype.bind .

    • JavaScript
    Reveal answer

    Taken word-for-word from MDN: The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. In my experience, it is most useful for binding the value of this in methods of classes that you want to pass into other functions. This is frequently done in React components.

  27. Question 7
    Mid

    Find all the Permutations of a String

    • Backtracking Strings Data Structures Java Python JavaScript
    Reveal answer

    A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself (or in simple english: permutation is each of several possible ways in which a set or number of things can be ordered or arranged). A string of length n has n! permutation: ABC

    // original string (3)
    

    ABC ACB BAC BCA CBA CAB

    // permutations 3! = 6
    

    To print all permutations of a string use backtracking implemented via recursion: Try each of the letters in turn as the first letter and then find all the permutations of the remaining letters using a recursive call. The base case is when the input is an empty string the only permutation is the empty string. In other words, you simply traverse the tree, and when you reach the leaf you print the permutation. Then you backtrack one level up, and try another option. Moving one level up the tree is what we call the backtracking in this case. Complexity Analysis: Time Complexity: O(n!) Space Complexity: O(n!) For any given string of length n there are n! possible permutations, and we need to print all of them so Time complexity is O(n * n!) . The function will be called recursively and will be stored in call stack for all n! permutations, so Space complexity is O(n!) . Implementation: JS

    // using backtracking
    let permute = (str, left = 0, right = str.length - 1) => {
      //If left index is equal to right index
      //Print the string permutation
      if(left == right){
        console.log(str);
      }else{
        for(let i = left; i <= right; i++){
          //Swap the letters of the string
          str = swap(str, left, i);
          //Generate the permutation with swapped letters
          permute(str, left+1, right);
          //Restore the letters back to their position, e.q. backtrack to prev state of the string
          str = swap(str, left, i);
        }
    }
    }//Function to swap the letters of the string
    let swap = (str, left, right) => {
      let arr = str.split('');
      [arr[left], arr[right]] = [arr[right], arr[left]];
      return arr.join('');
    }
    Java
    
    public static void permutation(String str) {
      permutation("", str);
    }
    private static void permutation(String prefix, String str) {
      int n = str.length();
      if (n == 0) System.out.println(prefix);
      else {
        for (int i = 0; i < n; i++)
        // take new prefix from string[i], put it as a first element and construct the rest of the
        string
        permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
      }
    }
    PY
    # using backtracking
    def permute(a, l, r):
    if l==r:
    print toString(a)
    else:
    for i in xrange(l,r+1):
    a[l], a[i] = a[i], a[l]
    permute(a, l+1, r)
    a[l], a[i] = a[i], a[l]
    # backtrack
    # Driver program to test the above function
    string = "ABC"
    n = len(string)
    a = list(string)
    permute(a, 0, n-1)
    
  28. Question 7
    Mid

    What is the preferred syntax for defining enums in JavaScript?

    • JavaScript
    Reveal answer

    Since 1.8.5 it's possible to seal and freeze the object, so define the above as:

    var DaysEnum = Object.freeze({
      "monday": 1,
      "tuesday": 2,
      "wednesday": 3,
      ...
    })
    

    or

    var DaysEnum = {
      "monday": 1,
      "tuesday": 2,
      "wednesday": 3,
      ...
    }
    Object.freeze(DaysEnum)
    

    and voila! JS enums.

    However, this doesn't prevent you from assigning an undesired value to a variable, which is often the main goal of enums:

    let day = DaysEnum.tuesday
    day = 298832342
    // goes through without any errors
    
  29. Question 8
    Mid

    What are the advantages and disadvantages of using use strict ?

    • JavaScript
    Reveal answer

    'use strict' is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaScript. Advantages: Makes it impossible to accidentally create global variables. Makes assignments which would otherwise silently fail to throw an exception. Makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect). Requires that function parameter names be unique. this is undefined in the global context. It catches some common coding bloopers, throwing exceptions. It disables features that are confusing or poorly thought out. Disadvantages: Many missing features that some developers might be used to. No more access to function.caller and function.arguments . Concatenation of scripts written in different strict modes might cause issues. Overall, I think the benefits outweigh the disadvantages, and I never had to rely on the features that strict mode blocks. I would recommend using strict mode.

  30. Question 8
    Mid

    What are the differences between ES6 class and ES5 function constructors?

    • JavaScript
    Reveal answer

    Let's first look at example of each:

    // ES5 Function Constructor
    function Person(name) {
      this.name = name;
    }// ES6 Class
    class Person {
      constructor(name) {
        this.name = name;
      }
    }
    

    For simple constructors, they look pretty similar. The main difference in the constructor comes when using inheritance. If we want to create a Student class that subclasses Person and add a studentId field, this is what we have to do in addition to the above.

    // ES5 Function Constructor
    function Student(name, studentId) {
      // Call constructor of superclass to initialize superclass-derived members.
      Person.call(this, name);
    
      // Initialize subclass's own members.
      this.studentId = studentId;
    }
    Student.prototype = Object.create(Person.prototype);
    Student.prototype.constructor = Student;// ES6 Class
    class Student extends Person {
      constructor(name, studentId) {
        super(name);
        this.studentId = studentId;
      }
    }
    

    It's much more verbose to use inheritance in ES5 and the ES6 version is easier to understand and remember.

  31. Question 8
    Mid

    How to merge two sorted Arrays into a Sorted Array?

    • Arrays Data Structures Java JavaScript Python
    Reveal answer

    Let's look at the merge principle: Given two separate lists A and B ordered from least to greatest, construct a list C by: repeatedly comparing the least value of A to the least value of B, removing (or moving a pointer) the lesser value, and appending it onto C. when one list is exhausted, append the remaining items in the other list onto C in order. The list C is then also a sorted list.

    Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n) This problem will have O(n) complexity at best. Implementation: JS

    function merge(a, b) {
      var result = [];
      var ai = 0;
      var bi = 0;
      while (true) {
        if ( ai < a.length && bi < b.length) {
          if (a[ai] < b[bi]) {
            result.push(a[ai]);
            ai++;
          } else if (a[ai] > b[bi]) {
            result.push(b[bi]);
            bi++;
          } else {
            result.push(a[ai]);
            result.push(b[bi]);
            ai++;
            bi++;
          }
      } else if (ai < a.length) {
        result.push.apply(result, a.slice(ai, a.length));
        break;
      } else if (bi < b.length) {
        result.push.apply(result, b.slice(bi, b.length));
        break;
      } else {
        break;
      }
    
    }
    return result;
    }
    Java
    public static int[] merge(int[] a, int[] b) {
      int[] answer = new int[a.length + b.length];
      int i = 0, j = 0, k = 0;
      while (i < a.length && j < b.length)
      answer[k++] = a[i] < b[j] ? a[i++] : b[j++];
      while (i < a.length)
      answer[k++] = a[i++];
      while (j < b.length)
      answer[k++] = b[j++];
      return answer;
    }
    PY
    def merge(left, right):
    result = []
    i ,j = 0, 0
    while i < len(left) and j < len(right):
    print('left[i]: {} right[j]: {}'.format(left[i],right[j]))
    if left[i] <= right[j]:
    print('Appending {} to the result'.format(left[i]))
    result.append(left[i])
    print('result now is {}'.format(result))
    i += 1
    print('i now is {}'.format(i))
    else:
    print('Appending {} to the result'.format(right[j]))
    result.append(right[j])
    print('result now is {}'.format(result))
    j += 1
    print('j now is {}'.format(j))
    print('One of the list is exhausted. Adding the rest of one of the lists.')
    result += left[i:]
    result += right[j:]
    print('result now is {}'.format(result))
    

    return result

  32. Question 8
    Mid

    Explain Function.prototype.bind .

    • JavaScript
    Reveal answer

    Taken word-for-word from MDN: The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. In my experience, it is most useful for binding the value of this in methods of classes that you want to pass into other functions. This is frequently done in React components.

  33. Question 9
    Mid

    What are the differences between ES6 class and ES5 function constructors?

    • JavaScript
    Reveal answer

    Let's first look at example of each:

    // ES5 Function Constructor
    function Person(name) {
      this.name = name;
    }// ES6 Class
    class Person {
      constructor(name) {
        this.name = name;
    
      }
    }
    

    For simple constructors, they look pretty similar. The main difference in the constructor comes when using inheritance. If we want to create a Student class that subclasses Person and add a studentId field, this is what we have to do in addition to the above.

    // ES5 Function Constructor
    function Student(name, studentId) {
      // Call constructor of superclass to initialize superclass-derived members.
      Person.call(this, name);// Initialize subclass's own members.
      this.studentId = studentId;
    }
    Student.prototype = Object.create(Person.prototype);
    Student.prototype.constructor = Student;// ES6 Class
    class Student extends Person {
      constructor(name, studentId) {
        super(name);
        this.studentId = studentId;
      }
    }
    

    It's much more verbose to use inheritance in ES5 and the ES6 version is easier to understand and remember.

  34. Question 9
    Mid

    What are the benefits of using spread syntax in ES6 and how is it different from rest syntax?

    • JavaScript
    Reveal answer

    ES6's spread syntax is very useful when coding in a functional paradigm as we can easily create copies of arrays or objects without resorting to Object.create , slice , or a library function. This language feature is used often in Redux and rx.js projects.

    function putDookieInAnyArray(arr) {
      return [...arr, 'dookie'];
    }
    const result = putDookieInAnyArray(['I', 'really', "don't", 'like']);
    // ["I", "really", "don't", "like",
    "dookie"]
    const person = {
      name: 'Todd',
      age: 29,
    };
    const copyOfTodd = { ...person };
    

    ES6's rest syntax offers a shorthand for including an arbitrary number of arguments to be passed to a function. It is like an inverse of the spread syntax, taking data and stuffing it into an array rather than unpacking an array of data, and it works in function arguments, as well as in array and object destructuring assignments.

    function addFiveToABunchOfNumbers(...numbers) {
      return numbers.map(x => x + 5);
    }
    const result = addFiveToABunchOfNumbers(4, 5, 6, 7, 8, 9, 10);
    // [9, 10, 11, 12, 13, 14, 15]
    const [a, b, ...rest] = [1, 2, 3, 4];
    // a: 1, b: 2, rest: [3, 4]
    const { e, f, ...others } = {
      e: 1,
      f: 2,
      g: 3,
      h: 4,
    };
    // e: 1, f: 2, others: { g: 3, h: 4 }
    
  35. Question 9
    Mid

    What are the benefits of using spread syntax in ES6 and how is it different from rest syntax?

    • JavaScript
    Reveal answer

    ES6's spread syntax is very useful when coding in a functional paradigm as we can easily create copies of arrays or objects without resorting to Object.create , slice , or a library function. This language feature is used often in Redux and rx.js projects.

    function putDookieInAnyArray(arr) {
      return [...arr, 'dookie'];
    }
    const result = putDookieInAnyArray(['I', 'really', "don't", 'like']);
    // ["I", "really", "don't", "like",
    "dookie"]
    const person = {
      name: 'Todd',
      age: 29,
    };
    const copyOfTodd = { ...person };
    

    ES6's rest syntax offers a shorthand for including an arbitrary number of arguments to be passed to a function. It is like an inverse of the spread syntax, taking data and stuffing it into an array rather than unpacking an array of data, and it works in function arguments, as well as in array and object destructuring assignments.

    function addFiveToABunchOfNumbers(...numbers) {
      return numbers.map(x => x + 5);
    }
    const result = addFiveToABunchOfNumbers(4, 5, 6, 7, 8, 9, 10);
    // [9, 10, 11, 12, 13, 14, 15]
    const [a, b, ...rest] = [1, 2, 3, 4];
    // a: 1, b: 2, rest: [3, 4]
    
    const { e, f, ...others } = {
      e: 1,
      f: 2,
      g: 3,
      h: 4,
    };
    // e: 1, f: 2, others: { g: 3, h: 4 }
    
  36. Question 10
    Mid

    What is Currying?

    • JavaScript
    Reveal answer

    Currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments. Here's an example in JavaScript:

    function add (a, b) {
      return a + b;
    }
    add(3, 4);
    // returns 7
    

    This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:

    function add (a) {
      return function (b) {
        return a + b;
      }
    }
    In an algebra of functions, dealing with functions that take multiple arguments (or equivalent one argument
    that's an N-tuple) is somewhat inelegant. So how do you deal with something you'd naturally express as, say,
    f(x,y) ? Well, you take that as equivalent to f(x)(y) - f(x) , call it g , is a function, and you apply that function
    

    to y . In other words, you only have functions that take one argument - but some of those functions return other

    functions (which ALSO take one argument).
    
  37. Question 10
    Mid

    What do you think of AMD vs CommonJS?

    • JavaScript
    Reveal answer

    Both are ways to implement a module system, which was not natively present in JavaScript until ES2015 came along. CommonJS is synchronous while AMD (Asynchronous Module Definition) is obviously asynchronous.

    CommonJS is designed with server-side development in mind while AMD, with its support for asynchronous loading of modules, is more intended for browsers. I find AMD syntax to be quite verbose and CommonJS is closer to the style you would write import statements in other languages. Most of the time, I find AMD unnecessary, because if you served all your JavaScript into one concatenated bundle file, you wouldn't benefit from the async loading properties. Also, CommonJS syntax is closer to Node style of writing modules and there is less context-switching overhead when switching between client side and server side JavaScript development. I'm glad that with ES2015 modules, that has support for both synchronous and asynchronous loading, we can finally just stick to one approach. Although it hasn't been fully rolled out in browsers and in Node, we can always use transpilers to convert our code.

  38. Question 10
    Mid

    What's the difference between using let and var to declare a variable in ES6?

    • JavaScript
    Reveal answer

    The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block. Also, variables declared with let are not accessible before they are declared in their enclosing block. This will throw a ReferenceError exception.

  39. Question 10
    Mid

    When should I use Arrow Functions in ES6?

    • JavaScript
    Reveal answer

    I'm now using the following rule of thumb for functions in ES6 and beyond: Use function in the global scope and for Object.prototype properties. Use class for object constructors.

    Use => everywhere else.
    

    Why use arrow functions almost everywhere? Scope safety: When arrow functions are used consistently, everything is guaranteed to use the same thisObject as the root. If even a single standard function callback is mixed in with a bunch of arrow functions there's a chance the scope will become messed up. Compactness: Arrow functions are easier to read and write. (This may seem opinionated so I will give a few examples further on). Clarity: When almost everything is an arrow function, any regular function immediately sticks out for defining the scope. A developer can always look up the next-higher function statement to see what the thisObject is.

  40. Question 11
    Mid

    How to compare two objects in JavaScript?

    • JavaScript
    Reveal answer

    Two non-primitive values, like objects (including function and array) held by reference, so both == and === comparisons will simply check whether the references match, not anything about the underlying values. For example, arrays are by default coerced to strings by simply joining all the values with commas ( , ) in between. So two arrays with the same contents would not be == equal:

    var a = [1,2,3];
    var b = [1,2,3];
    var c = "1,2,3";
    a == c;
    // true
    b == c;
    // true
    a == b;
    // false
    

    For deep object comparison use external libs like deep-equal or implement your own recursive equality algorithm.

  41. Question 11
    Mid

    What is Coercion in JavaScript?

    • JavaScript
    Reveal answer

    In JavaScript conversion between different two build-in types called coercion . Coercion comes in two forms in JavaScript: explicit and implicit. Here's an example of explicit coercion:

    var a = "42";
    var b = Number( a );
    a;
    // "42"
    b;
    // 42 -- the number!
    

    And here's an example of implicit coercion:

    var a = "42";
    var b = a * 1;
    // "42" implicitly coerced to 42 here
    a;
    // "42"
    b;
    // 42 -- the number!
    
  42. Question 11
    Mid

    What is Coercion in JavaScript?

    • JavaScript
    Reveal answer

    In JavaScript conversion between different two build-in types called coercion . Coercion comes in two forms in JavaScript: explicit and implicit. Here's an example of explicit coercion:

    var a = "42";
    var b = Number( a );
    a;
    // "42"
    b;
    // 42 -- the number!
    

    And here's an example of implicit coercion:

    var a = "42";
    var b = a * 1;
    // "42" implicitly coerced to 42 here
    a;
    // "42"
    b;
    // 42 -- the number!
    
  43. Question 11
    Mid

    Describe Closure concept in JavaScript as best as you could

    • JavaScript
    Reveal answer

    Consider:

    function makeAdder(x) {
      // parameter `x` is an inner variable
      // inner function `add()` uses `x`, so
      // it has a "closure" over `x`
      function add(y) {
        return y + x;
      };
    return add;
    }
    

    Reference to inner add function returned is able to remember what x value was passed to makeAdder function call.

    var plusOne = makeAdder( 1 );
    // x is 1, plusOne has a reference to add(y)
    var plusTen = makeAdder( 10 );
    // x is 10
    plusOne(3);
    // 1 (x) + 3 (y) = 4
    plusTen(13);
    // 10 (x) + 13 (y) = 23
    

    In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables can remain accessible after returning from the function you called. A closure is a stack frame which is allocated when a function starts its execution, and not freed after the function returns (as if a 'stack frame' were allocated on the heap rather than the stack!). In JavaScript, you can think of a function reference variable as having both a pointer to a function as well as a hidden pointer to a closure.

  44. Question 12
    Mid

    How would you use a closure to create a private counter?

    • JavaScript
    Reveal answer

    You can create a function within an outer function (a closure) that allows you to update a private variable but the variable wouldn't be accessible from outside the function without the use of a helper function.

    function counter() {
      var _counter = 0;
      // return an object with several functions that allow you
      // to modify the private _counter variable
      return {
        add: function(increment) { _counter += increment; },
        retrieve: function() { return 'The counter is currently at: ' + _counter; }
      }
    }// error if we try to access the private variable like below
    // _counter;
    // usage of our counter function
    var c = counter();
    c.add(5);
    c.add(9);// now we can access the private variable in the following way
    c.retrieve();
    // => The counter is currently at: 14
    
  45. Question 12
    Mid

    What is the definition of a Higher-Order Function?

    • JavaScript
    Reveal answer

    A higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a result. Higher-order functions are meant to abstract some operation that is performed repeatedly. The classic example of this is map , which takes an array and a function as arguments. map then uses this function to transform each item in the array, returning a new array with the transformed data. Other popular examples in JavaScript are forEach , filter , and reduce . A higher-order function doesn't just need to be manipulating arrays as there are many use cases for returning a function from another function. Function.prototype.bind is one such example in JavaScript. Map

    Let say we have an array of names which we need to transform each string to uppercase.

    const names = ['irish', 'daisy', 'anna'];
    

    The imperative way will be as such:

    const transformNamesToUppercase = function(names) {
      const results = [];
      for (let i = 0; i < names.length; i++) {
        results.push(names[i].toUpperCase());
      }
    return results;
    };
    transformNamesToUppercase(names);
    // ['IRISH', 'DAISY', 'ANNA']
    Use .map(transformerFn) makes the code shorter and more declarative.
    const transformNamesToUppercase = function(names) {
      return names.map(name => name.toUpperCase());
    };
    transformNamesToUppercase(names);
    // ['IRISH', 'DAISY', 'ANNA']
    
  46. Question 12
    Mid

    Quickly calculate the cube root of 6 digit numbers

    • JavaScript
    Reveal answer

    Problem

    For example, if the input is 636056 then your program should output 86 .

    Solution

    The general algorithm is as follows:

    1. Store the first 10 cube roots, their cubes, and the last digit in the number.
    var cubes_10 = {
      '0': 0,
      '1': 1,
      '8': 8,
      '27': 7,
      '64': 4,
      '125': 5,
      '216': 6,
      '343': 3,
      '512': 2,
      '729': 9
    };
    
    1. Ignore the last 3 digits of the input number, and for the remaining numbers, find the cube in the table that is less than or equal to the remaining number, and take the corresponding cube root to be the first number in your answer.
    2. For the last 3 digits that you previously ignored, loop through the table and when you get to the ith index, where i equals the last digit of the remaining 3 numbers, take the corresponding number in the right column as your answer.
    3. These numbers combined are the cube root answer.
    function fastCubeRoot(num) {
      var cubes_10 = {
        '0': 0,
        '1': 1,
        '8': 8,
        '27': 7,
        '64': 4,
        '125': 5,
        '216': 6,
        '343': 3,
        '512': 2,
        '729': 9
      };// get last 3 numbers and the remaining numbers
    var arr = num.toString().split('');
    var last = arr.slice(-3);
    var first = parseInt(arr.slice(0, -3).join(''));// answer will be stored here
    var lastDigit = 0, firstDigit = 0, index = 0;// get last digit of cube root
    for (var i in cubes_10) {
      if (index === parseInt(last[last.length-1])) { lastDigit = cubes_10[i]; }
      index++;
    }// get first digit of cube root
    index = 0;
    for (var i in cubes_10) {
      if (parseInt(i) <= first) { firstDigit = index; }
      index++;
    }// return cube root answer
    return firstDigit + '' + lastDigit;
    }
    fastCubeRoot(830584);
    
  47. Question 13
    Mid

    Find all string combinations consisting only of 0, 1 and ?

    • JavaScript
    Reveal answer

    Problem

    The input will be a string consisting only of the characters 0 , 1 and ? , where the ? acts as a wildcard that can be either a 0 or 1 , and your goal is to print all possible combinations of the string. For example, if the string is "011?0" then your program should output a set of all strings, which are: ["01100", "01110"] .

    Solution

    The general algorithm we will write a solution for is:

    1. Call the function with the string and an empty set where we begin pushing 0 and 1 's.
    2. Once we reach a ? make a copy of each string set, and for half append a 0 and for the other half append a 1 .
    3. Recursively call the function with a smaller string until the string is empty.
    function patterns(str, all) {// if the string is empty, return all the string sets
      if (str.length === 0) { return all; }// if character is 0 or 1 then add the character to each
      // string set we currently have so far
      if (str[0] === '0' || str[0] === '1') {
        for (var i = 0; i < all.length; i++) {
          all[i].push(str[0]);
        }
    }// for a wildcard, we make a copy of each string set
    // and for half of them we append a 0 to the string
    // and for the other half we append a 1 to the string
    if (str[0] === '?') {
      var len = all.length;
      for (var i = 0; i < len; i++) {
        var temp = all[i].slice(0);
        all.push(temp);
      }
    for (var i = 0; i < all.length; i++) {
      (i < all.length/2) ? all[i].push('0') : all[i].push('1');
    }
    }// recursively calculate all string sets
    return patterns(str.substring(1), all);
    }
    patterns('10?1?', [[]]);
    
  48. Question 14
    Mid

    What's the difference between using let and var to declare a variable in ES6?

    • JavaScript
    Reveal answer

    The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block. Also, variables declared with let are not accessible before they are declared in their enclosing block. This will throw a ReferenceError exception.

  49. Question 14
    Mid

    Implement a queue using a linked list

    • JavaScript
    Reveal answer

    We will store a reference to the front and back of the queue in order to make enqueuing and dequeuing run in O(1) constant time. Every time we want to insert into the queue, we add the new element to the end of the linked list and update the back pointer. When we want to dequeue we return the first node in the linked list and update the front pointer.

    // queue is initially empty
    var Queue = {front: null, back: null};// we will use a node to keep track of the elements
    // in the queue which is represented by a linked list
    function Node(data, next) {
      this.data = data;
    
      this.next = next;
    }// add elements to queue in O(1) time
    function Enqueue(element) {
      var N = new Node(element, null);
      if (Queue.back === null) {
        Queue.front = N;
        Queue.back = N;
      } else {
        Queue.back.next = N;
        Queue.back = Queue.back.next;
      }
    }// remove first element from queue in O(1) time
    function Dequeue() {
      if (Queue.front !== null) {
        var first = Queue.front;
        Queue.front = Queue.front.next;
        return first.data;
      } else {
        if (Queue.back !== null) { Queue.back = null; }
        return 'Cannot dequeue because queue is empty';
      }
    }
    Enqueue('a');
    Enqueue('b');
    Enqueue('c');
    Dequeue();
    
  50. Question 14
    Mid

    All Permutations (Anagrams) of a String

    • JavaScript
    Reveal answer

    Problem

    Generate all permutations of a given string. (Note: also known as the generating anagrams problem).

    Solution

    Remove the first character and recurse to get all permutations of length N-1 , then insert that first character into N-1 length strings and obtain all permutations of length N . The complexity is O(N!) because there are N! possible permutations of a string with length N , so it’s optimal.

    module.exports = function (string) {
      var result = {};// Using an immediately invoked named function for recursion.
      (function makeWord (word, remaining) {
        // If there are no more remaining characters, break and set to true
        // in the result object.
        if (!remaining) { return result[word] = true; }// Loop through all the remaining letters and recurse slicing the character
        // out of the remaining stack and into the solution word.
        for (var i = 0; i < remaining.length; i++) {
          makeWord(
          word + remaining[i],
          remaining.substr(0, i) + remaining.substr(i + 1)
        );
      }
    })('', string);// Using the ES5 Object.keys to grab the all the keys as an array.
    return Object.keys(result);
    };
    
  51. Question 15
    Mid

    What is the motivation for bringing Symbol to ES6?

    • JavaScript
    Reveal answer

    Symbols are a new, special kind of object that can be used as a unique property name in objects. Using Symbol instead of string 's allows different modules to create properties that don't conflict with one another. Symbols can also be made private, so that their properties can't be accessed by anyone who doesn't already have direct access to the Symbol . Symbols are a new primitive. Just like the number , string , and boolean primitives, Symbol have a function which can be used to create them. Unlike the other primitives, Symbols do not have a literal syntax (e.g how string have '' ) - the only way to create them is with the Symbol constructor in the following way:

    let symbol = Symbol();
    

    In reality, Symbol 's are just a slightly different way to attach properties to an object - you could easily provide the well-known Symbols as standard methods, just like Object.prototype.hasOwnProperty which appears in everything that inherits from Object .

  52. Question 15
    Mid

    Find Word Positions in Text

    • JavaScript
    Reveal answer

    Problem

    Given a text file and a word, find the positions that the word occurs in the file. We’ll be asked to find the positions of many words in the same file.

    Solution

    Since we’ll have to answer multiple queries, precomputation would be useful. We’ll build a data structure that stores the positions of all the words in the text file. This is known as inverted index.

    module.exports = function (text) {
      var trie = {},
      pos = 0,
      active = trie;
      // Start the active structure as the root trie structure
      // Suffix a space after the text to make life easier
      text += ' ';// Loop through the input text adding it to the trie structure
      for (var i = 0; i < text.length; i++) {
        // When the character is a space, restart
        if (text[i] === ' ') {
          // If the current active doesn't equal the root, set the position
          if (active !== trie) {
            (active.positions = active.positions || []).push(pos);
          }
        // Reset the positions and the active part of the data structure
        pos = i;
        active = trie;
        continue;
    
      }// Set the next character in the structure up
    active[text[i]] = (active[text[i]] || {});
    active = active[text[i]];
    }// Return a function that accepts a word and looks it up in the trie structure
    return function (word) {
      var i = -1,
      active = trie;
      while (word[++i]) {
        if (!active[word[i]]) { return []; }
        active = active[word[i]];
      }
    return active.positions;
    };
    };
    
  53. Question 15
    Mid

    Implement a queue using two stacks

    • JavaScript
    Reveal answer

    Suppose we push a , b , c to a stack. If we are trying to implement a queue and we call the dequeue method 3 times, we actually want the elements to come out in the order: a , b , c , which is in the opposite order they would come out if we popped from the stack. So, basically, we need to access the elements in the reverse order that they exist in the stack. Algorithm for queue using two stacks:

    1. When calling the enqueue method, simply push the elements into the stack 1.
    2. If the dequeue method is called, push all the elements from stack 1 into stack 2, which reverses the order of the elements. Now pop from stack 2. The worst case running time for implementing these operations using stacks is O(n) because you need to transfer n elements from stack 1 to stack 2 when a dequeue method is called. Pushing to stack 1 is simply O(1) .
    // implement stacks using plain arrays with push and pop functions
    var Stack1 = [];
    var Stack2 = [];// implement enqueue method by using only stacks
    // and the push and pop functions
    function Enqueue(element) {
      Stack1.push(element);
    }// implement dequeue method by pushing all elements
    // from stack 1 into stack 2, which reverses the order
    // and then popping from stack 2
    function Dequeue() {
      if (Stack2.length === 0) {
        if (Stack1.length === 0) { return 'Cannot dequeue because queue is empty'; }
        while (Stack1.length > 0) {
          var p = Stack1.pop();
          Stack2.push(p);
        }
    }
    return Stack2.pop();
    }
    Enqueue('a');
    Enqueue('b');
    Enqueue('c');
    Dequeue();
    
  54. Question 16
    Mid

    Explain the difference between undefined and not defined in JavaScript

    • JavaScript
    Reveal answer

    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 execute thereafter. But If you use typeof undeclared_variable then it will return undefined . Before starting further discussion let's understand the difference between declaration and definition. var x is a declaration because you are not defining what value it holds yet, but you are declaring its existence and the need of memory allocation.

    var x;
    // declaring x
    console.log(x);
    //output: undefined
    
    var x = 1 is both declaration and definition (also we can say we are doing initialisation), Here declaration and
    

    assignment of value happen inline for variable x, In JavaScript every variable declaration and function declaration brings to the top of its current scope in which it's declared then assignment happen in order this term is called hoisting . A variable that is declared but not define and when we try to access it, It will result undefined .

    var x;
    // Declaration
    if(typeof x === 'undefined')
    // Will return true
    

    A variable that neither declared nor defined when we try to reference such variable then It result not defined .

    console.log(y);
    // Output: ReferenceError: y is not defined
    
  55. Question 16
    Mid

    What is the drawback of creating true private in JavaScript?

    • JavaScript
    Reveal answer

    One of the drawback of creating a true private method in JavaScript is that they are very memory inefficient because a new copy of the method would be created for each instance.

    var Employee = function (name, company, salary) {
      this.name = name || "";
      //Public attribute default value is null
      this.company = company || "";
      //Public attribute default value is null
      this.salary = salary || 5000;
      //Public attribute default value is null
      // Private method
      var increaseSalary = function () {
        this.salary = this.salary + 1000;
      };// Public method
    this.dispalyIncreasedSalary = function() {
      increaseSalary();
      console.log(this.salary);
    };
    };// Create Employee class object
    var emp1 = new Employee("John","Pluto",3000);
    // Create Employee class object
    var emp2 = new Employee("Merry","Pluto",2000);
    // Create Employee class object
    var emp3 = new Employee("Ren","Pluto",2500);
    

    Here each instance variable emp1 , emp2 , emp3 has own copy of increaseSalary private method. So as recommendation don't go for a private method unless it's necessary.

  56. Question 17
    Mid

    Why is extending built-in JavaScript objects not a good idea?

    • JavaScript
    Reveal answer

    Extending a built-in/native JavaScript object means adding properties/functions to its prototype . While this may seem like a good idea at first, it is dangerous in practice. Imagine your code uses a few libraries that both extend the Array.prototype by adding the same contains method, the implementations will overwrite each other and your code will break if the behavior of these two methods is not the same. The only time you may want to extend a native object is when you want to create a polyfill, essentially providing your own implementation for a method that is part of the JavaScript specification but might not exist in the user's browser due to it being an older browser.

  57. Question 17
    Mid

    Write a recursive function that returns the binary string of a given decimal number

    • JavaScript
    Reveal answer

    Given 4 as the decimal input, the function should return 100.

    decimalToBinary(3);
    // 11
    decimalToBinary(8);
    // 1000
    decimalToBinary(1000);
    // 1111101000
    function decimalToBinary(digit) {
      if(digit >= 1) {
        // If digit is not divisible by 2 then recursively return proceeding
        // binary of the digit minus 1, 1 is added for the leftover 1 digit
        if (digit % 2) {
          return decimalToBinary((digit - 1) / 2) + 1;
        } else {
          // Recursively return proceeding binary digits
          return decimalToBinary(digit / 2) + 0;
        }
    } else {
      // Exit condition
      return '';
    }
    }
    
  58. Question 17
    Mid

    Given an array of integers, find the largest difference between two elements such that the element of lesser value must come before the greater element

    • JavaScript
    Reveal answer
    var array = [7, 8, 4, 9, 9, 15, 3, 1, 10];
    // [7, 8, 4, 9, 9, 15, 3, 1, 10] would return `11` based on the difference between `4` and `15`
    // Notice: It is not `14` from the difference between `15` and `1` because 15 comes before 1.
    findLargestDifference(array);
    function findLargestDifference(array) {
      // If there is only one element, there is no difference
      if (array.length <= 1) return -1;// currentMin will keep track of the current lowest
      var currentMin = array[0];
      var currentMaxDifference = 0;// We will iterate through the array and keep track of the current max difference
      // If we find a greater max difference, we will set the current max difference to that variable
      // Keep track of the current min as we iterate through the array, since we know the greatest
      // difference is yield from `largest value in future` - `smallest value before it`
      for (var i = 1; i < array.length; i++) {
        if (array[i] > currentMin && (array[i] - currentMin > currentMaxDifference)) {
          currentMaxDifference = array[i] - currentMin;
        } else if (array[i] <= currentMin) {
          currentMin = array[i];
        }
    }// If negative or 0, there is no largest difference
    if (currentMaxDifference <= 0) return -1;
    return currentMaxDifference;
    }
    
  59. Question 17
    Mid

    Given two strings, return true if they are anagrams of one another

    • JavaScript
    Reveal answer

    Problem

    For example: Mary is an anagram of Army

    Solution

    var firstWord = "Mary";
    var secondWord = "Army";
    isAnagram(firstWord, secondWord);
    // true
    function isAnagram(first, second) {
      // For case insensitivity, change both words to lowercase.
      var a = first.toLowerCase();
      var b = second.toLowerCase();// Sort the strings, and join the resulting array to a string. Compare the results
      a = a.split("").sort().join("");
      b = b.split("").sort().join("");
      return a === b;
    }
    
  60. Question 18
    Mid

    What is generator in JS?

    • JavaScript
    Reveal answer

    Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances. Generator functions are written using the function* syntax. When called initially, generator functions do not execute any of their code, instead returning a type of iterator called a Generator. When a value is consumed by calling the generator's next method, the Generator function executes until it encounters the yield keyword. The function can be called as many times as desired and returns a new Generator each time, however each Generator may only be iterated once.

    function* makeRangeIterator(start = 0, end = Infinity, step = 1) {
      let iterationCount = 0;
      for (let i = start; i < end; i += step) {
        iterationCount++;
        yield i;
      }
    return iterationCount;
    }
    
  61. Question 18
    Mid

    What is the difference between a shim and a polyfill?

    • JavaScript
    Reveal answer

    A shim is any piece of code that performs interception of an API call and provides a layer of abstraction. It isn't necessarily restricted to a web application or HTML5/CSS3. A polyfill is a type of shim that retrofits legacy browsers with modern HTML5/CSS3 features usually using Javascript or Flash. A shim is a library that brings a new API to an older environment, using only the means of that environment. Thus, a polyfill is a shim for a browser API.

  62. Question 18
    Mid

    Describe Closure concept in JavaScript as best as you could

    • JavaScript
    Reveal answer

    Consider:

    function makeAdder(x) {
      // parameter `x` is an inner variable
      // inner function `add()` uses `x`, so
      // it has a "closure" over `x`
      function add(y) {
        return y + x;
      };
    return add;
    }
    

    Reference to inner add function returned is able to remember what x value was passed to makeAdder function call.

    var plusOne = makeAdder( 1 );
    // x is 1, plusOne has a reference to add(y)
    var plusTen = makeAdder( 10 );
    // x is 10
    plusOne(3);
    // 1 (x) + 3 (y) = 4
    plusTen(13);
    // 10 (x) + 13 (y) = 23
    

    In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed.

    In JavaScript, if you declare a function within another function, then the local variables can remain accessible after returning from the function you called. A closure is a stack frame which is allocated when a function starts its execution, and not freed after the function returns (as if a 'stack frame' were allocated on the heap rather than the stack!). In JavaScript, you can think of a function reference variable as having both a pointer to a function as well as a hidden pointer to a closure.

  63. Question 19
    Mid

    What advantages are using arrow functions?

    • JavaScript
    Reveal answer

    Scope safety: Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). An arrow function does not create its own this, the this value of the enclosing execution context is used. Compactness: Arrow functions are easier to read and write. Clarity: When almost everything is an arrow function, any regular function immediately sticks out for defining the scope. A developer can always look up the next-higher function statement to see what the thisObject is.

  64. Question 19
    Mid

    What is IIFEs (Immediately Invoked Function Expressions)?

    • JavaScript
    Reveal answer

    It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created:

    (function IIFE(){
      console.log( "Hello!" );
    })();
    // "Hello!"
    

    This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

  65. Question 19
    Mid

    What is the difference between Anonymous and Named functions?

    • JavaScript
    Reveal answer

    Consider:

    var foo = function() {
      // anonymous function assigned to variable foo
      // ..
    };
    var x = function bar(){
      // named function (bar) assigned to variable x
      // ..
    };
    foo();
    // actual function execution
    x();
    
  66. Question 19
    Mid

    Given an array of integers, find the largest product yielded from three of the integers

    • JavaScript
    Reveal answer
    var unsortedArray = [-10, 7, 29, 30, 5, -10, -70];
    computeProduct(unsortedArray);
    // 21000
    function sortIntegers(a, b) {
      return a - b;
    }// Greatest product is either (min1 * min2 * max1 || max1 * max2 * max3)
    function computeProduct(unsorted) {
      var sortedArray = unsorted.sort(sortIntegers),
      product1 = 1,
      product2 = 1,
      array_n_element = sortedArray.length - 1;// Get the product of three largest integers in sorted array
      for (var x = array_n_element; x > array_n_element - 3; x--) {
        product1 = product1 * sortedArray[x];
      }
    product2 = sortedArray[0] * sortedArray[1] * sortedArray[array_n_element];
    if (product1 > product2) return product1;
    return product2;
    }
    
  67. Question 20
    Mid

    Check if a given string is a palindrome. Case sensitivity should be taken into account.

    • JavaScript
    Reveal answer

    A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.

    isPalindrome("racecar");
    // true
    isPalindrome("race Car");
    // true
    function isPalindrome(word) {
      // Replace all non-letter chars with "" and change to lowercase
      var lettersOnly = word.toLowerCase().replace(/\s/g, "");// Compare the string with the reversed version of the string
      return lettersOnly === lettersOnly.split("").reverse().join("");
    }
    

    Or 25x faster than the standard answer

    function isPalindrome(s,i) {
      return (i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);
    }
    
  68. Question 20
    Mid

    What is the difference between Anonymous and Named functions?

    • JavaScript
    Reveal answer

    Consider:

    var foo = function() {
      // anonymous function assigned to variable foo
      // ..
    };
    var x = function bar(){
      // named function (bar) assigned to variable x
      // ..
    };
    foo();
    // actual function execution
    x();
    
  69. Question 20
    Mid

    Provide some examples of non-bulean value coercion to a boolean one

    • JavaScript
    Reveal answer

    The question is when a non-boolean value is coerced to a boolean, does it become true or false , respectively? The specific list of "falsy" values in JavaScript is as follows:

    "" (empty string)
    0 , -0 , NaN (invalid number)
    null , undefined
    false
    

    Any value that's not on this "falsy" list is "truthy." Here are some examples of those: "hello" 42 true

    [ ] , [ 1, "2", 3 ] (arrays)
    { } , { a: 42 } (objects)
    
    function foo() { .. } (functions)
    
  70. Question 20
    Mid

    Could you explain the difference between ES5 and ES6

    • JavaScript
    Reveal answer

    ECMAScript 5 (ES5): The 5th edition of ECMAScript, standardized in 2009. This standard has been implemented fairly completely in all modern browsers ECMAScript 6 (ES6)/ ECMAScript 2015 (ES2015): The 6th edition of ECMAScript, standardized in 2015. This standard has been partially implemented in most modern browsers. Here are some key differences between ES5 and ES6: Arrow functions & string interpolation: Consider:

    const greetings = (name) => {
      return `hello ${name}`;
    }
    

    and even:

    const greetings = name => `hello ${name}`;
    Const.
    

    Const works like a constant in other languages in many ways but there are some caveats. Const stands for ‘constant reference’ to a value. So with const, you can actually mutate the properties of an object being referenced by the variable. You just can’t change the reference itself.

    const NAMES = [];
    NAMES.push("Jim");
    console.log(NAMES.length === 1);
    // true
    NAMES = ["Steve", "John"];
    // error
    Block-scoped variables.
    

    The new ES6 keyword let allows developers to scope variables at the block level. Let doesn’t hoist in the same way var does. Default parameter values Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined — meaning null is a valid value.

    // Basic syntax
    function multiply (a, b = 2) {
      return a * b;
    }
    multiply(5);
    // 10
    ** Class Definition and Inheritance**
    ES6 introduces language support for classes ( class keyword), constructors ( constructor keyword), and the
    

    extend keyword for inheritance. for-of operator The for...of statement creates a loop iterating over iterable objects. Spread Operator For objects merging

    const obj1 = { a: 1, b: 2 }
    const obj2 = { a: 2, c: 3, d: 4}
    const obj3 = {...obj1, ...obj2}
    Promises
    

    Promises provide a mechanism to handle the results and errors from asynchronous operations. You can accomplish the same thing with callbacks, but promises provide improved readability via method chaining and succinct error handling.

    const isGreater = (a, b) => {
      return new Promise ((resolve, reject) => {
        if(a > b) {
          resolve(true)
        } else {
          reject(false)
        }
    })
    }
    isGreater(1, 2)
    .then(result => {
    
      console.log('greater')
    })
    .catch(result => {
      console.log('smaller')
    })
    

    Modules exporting & importing Consider module exporting:

    const myModule = { x: 1, y: () => { console.log('This is ES5') }}
    export default myModule;
    

    and importing:

    import myModule from './myModule';
    
  71. Question 20
    Mid

    Provide some examples of non-bulean value coercion to a boolean one

    • JavaScript
    Reveal answer

    The question is when a non-boolean value is coerced to a boolean, does it become true or false , respectively? The specific list of "falsy" values in JavaScript is as follows:

    "" (empty string)
    0 , -0 , NaN (invalid number)
    null , undefined
    false
    

    Any value that's not on this "falsy" list is "truthy." Here are some examples of those: "hello" 42 true

    [ ] , [ 1, "2", 3 ] (arrays)
    { } , { a: 42 } (objects)
    function foo() { .. } (functions)
    

Senior questions

43 questions
  1. Question 1
    Senior

    How does the this keyword work? Provide some code examples

    • JavaScript
    Reveal answer

    In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. Consider:

    function foo() {
      console.log( this.bar );
    }
    var bar = "global";
    var obj1 = {
      bar: "obj1",
      foo: foo
    };
    var obj2 = {
      bar: "obj2"
    };
    foo();
    // "global"
    obj1.foo();
    // "obj1"
    foo.call( obj2 );
    // "obj2"
    new foo();
    // undefined
    
  2. Question 1
    Senior

    Can you describe the main difference between a .forEach loop and a .map() loop and why you would pick one versus the other?

    • JavaScript
    Reveal answer

    To understand the differences between the two, let's look at what each function does. forEach Iterates through the elements in an array. Executes a callback for each element. Does not return a value.

    const a = [1, 2, 3];
    const doubled = a.forEach((num, index) => {
      // Do something with num and/or index.
    });// doubled = undefined
    map
    

    Iterates through the elements in an array. "Maps" each element to a new element by calling the function on each element, creating a new array as a result.

    const a = [1, 2, 3];
    const doubled = a.map(num => {
      return num * 2;
    });// doubled = [2, 4, 6]
    The main difference between .forEach and .map() is that .map() returns a new array. If you need the result,
    but do not wish to mutate the original array, .map() is the clear choice. If you simply need to iterate over an
    

    array, forEach is a fine choice.

  3. Question 1
    Senior

    How does the this keyword work? Provide some code examples

    • JavaScript
    Reveal answer

    In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. Consider:

    function foo() {
      console.log( this.bar );
    }
    var bar = "global";
    var obj1 = {
      bar: "obj1",
      foo: foo
    };
    var obj2 = {
      bar: "obj2"
    };
    foo();
    // "global"
    obj1.foo();
    // "obj1"
    foo.call( obj2 );
    // "obj2"
    new foo();
    // undefined
    
  4. Question 2
    Senior

    Explain what is Fibonacci Search technique?

    • Divide & Conquer Fibonacci Series Searching Data Structures C# JavaScript
    Reveal answer

    Fibonacci search is a search algorithm based on divide and conquer principle that can find an element in the given sorted array with the help of Fibonacci series in

    O(
    log n) time complexity.
    

    Compared to binary search where the sorted array is divided into two equal-sized parts, one of which is examined further, Fibonacci search divides the array into two unequal parts that have sizes that are consecutive Fibonacci numbers. Some facts to note: Fibonacci search has the advantage that one only needs addition and subtraction to calculate the indices of the accessed array elements, while classical binary search needs bit-shift, division or multiplication, operations that were less common at the time Fibonacci search was first published Binary search works by dividing the seek area in equal parts 1:1 . Fibonacci search can divide it into parts approaching 1:1.618 while using the simpler operations. On average, Fibonacci search requires 4% more comparisons than binary search Fibonacci Search examines relatively closer elements in subsequent steps. So when input array is big that cannot fit in CPU cache or even in RAM, Fibonacci Search can be useful. Thus Fibonacci search may have the advantage over binary search in slightly reducing the average time needed to access a non-uniform access memory storage. Let the length of given array be length and the element to be searched be key . Steps of Fibonacci Search:

    1. Find the smallest Fibonacci number F(n) that F(n) - 1 >= length
    2. F(n) = F(n-1) + F(n-2) => F(n) - 1 = [ F(n-1) - 1 ] + (1) + [ F(n-2) - 1 ] , where (1) here is for the
    middle item (the m in below figure).
    // |<--------- p: F(n) - 1 --------->|
    // |<--- q: F(n-1) - 1 --->| |<-- r: F(n-2) - 1 -->|
    // +----+---+--------------------+---+---+---+---+
    // | | k | | m | | k | |
    // +----+---+--------------------+---+---+---+---+
    // ^
    3. If key < m , then search key in q = F(n-1) - 1 :
    // |<--- p: F(n-1) - 1 --->|
    // |<----- q ----->| |<-- r -->|
    // +----+---+------+---+---------+
    // | | k | | m | |
    // +----+---+------+---+---------+
    for that set p = F(n-1) - 1, q = F(n-2) - 1, r = F(n-3) - 1 and repeat the process. Here Fibonacci numbers
    go
    

    backward once. These indicate elimination of approximately one-third of the remaining array. 4. If key > m , then repeat then search key in r = F(n-2) - 1 :

    // |<-- p: F(n-2) - 1 -->|
    // |<--- q --->| |<- r ->|
    // +---+---+---+
    // | | k | | m
    // +---+---+---+
    // ^
    For that, set p = F(n-2) - 1, q = F(n-3) - 1, r = F(n-4) - 1 and repeat the process. Here Fibonacci
    numbers go
    

    backward twice, indicating elimination of approximately two-third of the remaining array.

    Complexity Analysis: Time Complexity: O(log n) Space Complexity: O(log n) Fibonacci search has an average- and worst-case complexity of

    O(
    log n) . The worst case will occur when we
    have our target in the larger (2/3) fraction of the array, as we proceed to find it. In other words, we are
    eliminating the smaller (1/3) fraction of the array every time. We call once for n, then for (2/3) n, then for (4/9) n
    

    and henceforth. Implementation: CS #include #include #include "search.h" typedef struct FibonacciValues

    {
      // Fibonacci number: F(n) = F(n-1) + F(n-2)
      int Fn_2; // F(n-2)
      int Fn_1; // F(n-1)
      int Fn; // F(n)
      FibonacciValues(int fn_2, int fn_1, int fn)
      : Fn_2(fn_2)
      , Fn_1(fn_1)
      , Fn(fn)
      {
        assert(Fn == Fn_1 + Fn_2);
      }
    ~FibonacciValues()
    {
    }
    void forward()
    {
      Fn_2 = Fn_1;
      Fn_1 = Fn;
      Fn = Fn_1 + Fn_2;
      assert(Fn == Fn_1 + Fn_2);
    }
    void backward()
    {
      Fn = Fn_1;
      Fn_1 = Fn_2;
      Fn_2 = Fn - Fn_1;
      assert(Fn == Fn_1 + Fn_2);
    }
    } FibonacciValues;
    // Returns the smallest Fibonacci number that is greater than or equal to k.
    FibonacciValues GetFibonacci(int k)
    {
      FibonacciValues fib(0, 1, 1);
      while (fib.Fn < k) {
    
        fib.forward();
      }
    return fib;
    }
    // Notice that the current middle might exceed the array!
    int fibonacciSearch(int list[], const unsigned int length, int key)
    {
      assert(list && length);
      int left = 0, right = length - 1, middle;
      // Find a fibonacci number F(n) that F(n) - 1 >= length
      FibonacciValues fib = GetFibonacci(length + 1);
      while (left <= right) {
        // Avoid the middle is over the array.
        middle = std::min(left + (fib.Fn_1 - 1), right);
        if (list[middle] == key) {
          return middle;
        } else if (list[middle] > key) {
          right = middle - 1;
          fib.backward();
        } else { // list[middle] < key
        left = middle + 1;
        fib.backward(); fib.backward();
      }
    }
    return NOT_FOUND;
    }
    JS
    function fib(n) {
      if (n <= 0)
      return 0;
      if (n <= 2)
      return 1;
      return fib(n-1) + fib(n-2);
    }
    function smallest_greater_eq_fib(n) {
      let f = fib(0),
      cu = 0;
      while (f < n)
      f = fib(++cu);
      return cu;
    }
    async function fibonacciSearch(a, k, l, r, display) {
      let f = smallest_greater_eq_fib(r-l+1);
      while (f >= 0) {
        i = Math.min(l+fib(f-1), r-1);
        i = Math.max(0, i);
        refresh(glob_comp, a[i]);
        display(a, i, l, r);
        await sleep(glob_sleep_time);
        if (a[i]==k) {
          glob_comp++;
          refresh(glob_comp, a[i]);
          return new Promise(resolve => resolve(i));
        } else if (k < a[l+fib(f-1)]) {
          glob_comp+=2;
    
          refresh(glob_comp, a[i]);
          r = i;
          f-=1;
        } else {
          glob_comp+=2;
          refresh(glob_comp, a[i]);
          l = i;
          f-=2;
        }
    }
    return new Promise(resolve => resolve(-1));
    }
    Java
    public class Fibonacci_Search
    {
      static int kk = -1, nn = -1;
      static int fib[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,
        377, 610, 98, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368,
        75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309,
        3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986,
        102334155, 165580141 };
      static int fibsearch(int a[], int n, long x)
      {
        int inf = 0, pos, k;
        if (nn != n)
        {
          k = 0;
          while (fib[k] < n)
          k++;
          kk = k;
          nn = n;
        }
      else
      k = kk;
      while (k > 0)
      {
        pos = inf + fib[--k];
        if ((pos >= n) || (x < a[pos]))
        ;
        else if (x > a[pos])
        {
          inf = pos + 1;
          k--;
        }
      else
      return pos;
    }
    return -1;
    }
    }
    PY
    def FibonacciSearch(lys, val):
    fibM_minus_2 = 0
    fibM_minus_1 = 1
    fibM = fibM_minus_1 + fibM_minus_2
    while (fibM < len(lys)):
    fibM_minus_2 = fibM_minus_1
    fibM_minus_1 = fibM
    
    fibM = fibM_minus_1 + fibM_minus_2
    index = -1;
    while (fibM > 1):
    i = min(index + fibM_minus_2, (len(lys)-1))
    if (lys[i] < val):
    fibM = fibM_minus_1
    fibM_minus_1 = fibM_minus_2
    fibM_minus_2 = fibM - fibM_minus_1
    index = i
    elif (lys[i] > val):
    fibM = fibM_minus_2
    fibM_minus_1 = fibM_minus_1 - fibM_minus_2
    fibM_minus_2 = fibM - fibM_minus_1
    else :
    

    return i

    if(fibM_minus_1 and index < (len(lys)-1) and lys[index+1] == val):
    return index+1;
    

    return -1

  5. Question 2
    Senior

    Explain Prototype Inheritance in JavaScript?

    • JavaScript
    Reveal answer

    In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects - and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class. In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. Every object in Javascript has a prototype. JavaScript's inheritance system is prototypical, and not class-based. When a messages reaches an object, JavaScript will attempt to find a property in that object first, if it cannot find it then the message will be sent to the object’s prototype and so on. That behavior called prototype chain or prototype inheritance. Constructor functions are the most used way in JavaScript to construct prototype chains. When we use new , JavaScript injects an implicit reference to the new object being created in the form of the this keyword. It also returns this reference implicitly at the end of the function.

    function Foo() {
      this.kind = ‘foo’
    }
    var foo = new Foo();
    foo.kind
    //=> ‘foo’
    
  6. Question 3
    Senior

    Explain when and how to use Exponential (aka Doubling or Galloping) Search?

    • Searching JavaScript
    Reveal answer

    Exponential Search (also called Doubling Search or Galloping Search or Struzik Search) is explicitly designed for sorted, unbounded lists (infinite arrays or arrays with unknown size) whereas binary search deals with bounded lists (size is known). It has two steps:

    1. Search for a position of first element greater or equal than the target value. Assuming that the list is sorted in ascending order, the algorithm looks for the first exponent, j , where the value arr(2j) is greater than the search key (target value). If the element at the current index is smaller than the search key, the algorithm repeats, skipping to the next search index by doubling it, calculating the next power of 2.
    2. Do the binary search from the beginning to the found end Complexity Analysis: Time Complexity: O(log n) Space Complexity: O(log n) The first stage of the algorithm takes O(log i) time, where i is the index where the search key would be in the list. The second part of the algorithm also takes
    O(log i) time. As the second stage is simply a binary search, it
    takes
    O(
    log n) where n is the size of the interval being searched. This gives the algorithm a total runtime,
    

    calculated by summing the runtimes of the two stages, of

    O(log i) +_ O(log i) _ =
    2 O(log i) =
    O(log i) .
    Implementation:
    JS
    function exponentialSearch(arrayToSearch, valueToSearch){
      if (arrayToSearch[0] == valueToSearch){
        return 0;
      }
    var i = 1;
    while (i < arrayToSearch.length && arrayToSearch[i] <= valueToSearch){
      i = i*2;
    
    }
    return binarySearch(arrayToSearch, valueToSearch);
    }
    PY
    def exponential_search(arr, p):
    i = 0
    while (arr[2 ** i] < p):
    i += 1
    binary_search(arr, p, i)
    
  7. Question 3
    Senior

    Check if a given string is a isomorphic

    • JavaScript
    Reveal answer

    For two strings to be isomorphic, all occurrences of a character in string A can be replaced with another character to get string B. The order of the characters must be preserved. There must be one-to-one mapping for ever char of string A to every char of string B. paper and title would return true. egg and sad would return false. dgg and add would return true.

    isIsomorphic("egg", 'add');
    // true
    isIsomorphic("paper", 'title');
    // true
    isIsomorphic("kick", 'side');
    // false
    function isIsomorphic(firstString, secondString) {// Check if the same lenght. If not, they cannot be isomorphic
      if (firstString.length !== secondString.length) return false
      var letterMap = {};
      for (var i = 0; i < firstString.length; i++) {
        var letterA = firstString[i],
        letterB = secondString[i];// If the letter does not exist, create a map and map it to the value
        // of the second letter
        if (letterMap[letterA] === undefined) {
          letterMap[letterA] = letterB;
        } else if (letterMap[letterA] !== letterB) {
          // Eles if letterA already exists in the map, but it does not map to
          // letterB, that means that A is mapping to more than one letter.
          return false;
        }
    }
    // If after iterating through and conditions are satisfied, return true.
    // They are isomorphic
    return true;
    }
    
  8. Question 3
    Senior

    What is Hoisting in JavaScript?

    • JavaScript
    Reveal answer

    Hoisting is the JavaScript interpreter's action of moving all variable and function declarations to the top of the current scope. There are two types of hoisting: variable hoisting - rare function hoisting - more common Wherever a var (or function declaration) appears inside a scope, that declaration is taken to belong to the entire scope and accessible everywhere throughout.

    var a = 2;
    foo();
    // works because `foo()`
    // declaration is "hoisted"
    function foo() {
      a = 3;
      console.log( a );
      // 3
      var a;
      // declaration is "hoisted"
      // to the top of `foo()`
    }
    console.log( a );
    // 2
    
  9. Question 4
    Senior

    Explain how QuickSort works

    • Divide & Conquer Sorting Data Structures JavaScript
    Reveal answer

    Quick Sort is a divide and conquer, comparison, in-place algorithm. Efficient implementations of Quicksort are not a stable sort. When implemented well, it can be about two or three times faster than its main competitors, merge sort and heapsort. Quicksort determines something called a pivot, which is a somewhat arbitrary element in the collection. Using the pivot point, quicksort partitions (or divides) the larger unsorted collection into two, smaller lists. It moves all the elements smaller than the pivot to the left (before) the pivot element, and moves all the elements larger than the pivot to the right (after) the pivot element. Even though the list isn’t completely sorted yet, we know that the items are in the correct order in relation to the pivot. This means that we never have to compare elements on the left side of the partition to elements on the right side of the partition. We already know they are in their correct spots in relation to the pivot. The sub-lists are then sorted recursively. Ideally, partitioning would use the median of the given values (in the array), but the median can only be found by scanning the whole array and this would slow the algorithm down. In that case the two partitions would be of equal size; In the simplest versions of quick sort an arbitrary element, typically the

    last (rightmost) element is
    used as an estimate (guess) of the median.
    Complexity Analysis:
    Time Complexity: O(n log n) Space Complexity: O(n log n)
    

    Overall time complexity of Quick Sort is

    O(
    n log n) . In the worst case, it makes
    O(
    n2) comparisons (all elements
    are same or array is already sorted).
    The partition step used in quicksort ideally is an in-place operation (without creating any additional arrays). But
    since quicksort calls itself on the order of log(n) times (in the average case), worst case number of calls isO(
    n) , at each recursive call a new stack frame of constant size must be allocated. Hence the
    O(
    log n) space
    complexity.
    Implementation:
    JS
    With additional memory (naive):
    
    function quickSort (arr) {
      if(arr.length <= 1) return arr;// find middle point of array (effectively random pivot)
      var swapPosition = Math.floor((arr.length -1) / 2);
      var pivot = arr.splice(swapPosition, 1);
      var left = [];
      var right = [];
      for(var i = 0; i < arr.length; i++) {
        if(arr[i] < pivot) {
          left.push(arr[i]);
        } else {
          right.push(arr[i])
        }
    }
    return quickSort(left).concat(pivot, quickSort(right));
    }
    

    In-place:

    var quickSort = function(array, left, right) {
      var leftIndex = partition(array, left, right);
      if (left < leftIndex - 1) {
        quickSort(array, left, leftIndex - 1);
      }
    if (right > leftIndex) {
      quickSort(array, leftIndex, right);
    }
    return array;
    }
    var swap = function(array, left, right) {
      var temp;
      temp = array[leftIndex];
      array[leftIndex] = array[rightIndex];
      array[rightIndex] = temp;
    }
    var partition = function(array, left, right) {
      var pivotIndex = Math.floor((left + right) / 2);
      var pivot = array[pivotIndex];
      leftIndex = left;
      rightIndex = right;
      while (leftIndex <= rightIndex) {
        while (array[leftIndex] < pivot) {
          leftIndex++;
        }
      while (array[rightIndex] > pivot) {
        rightIndex--;
      }
    if (leftIndex <= rightIndex) {
      swap(array, left, right);
      leftIndex++;
      rightIndex--;
    }
    }
    return leftIndex;
    }
    
    PY
    With additional memory (naive):
    def quick_sort(collection):
    length = len(collection)
    if length <= 1:
    

    return collection else:

    Use the last element as the first pivot

    pivot = collection.pop()
    # Put elements greater than pivot in greater list
    # Put elements lesser than pivot in lesser list
    greater, lesser = [], []
    for element in collection:
    if element > pivot:
    greater.append(element)
    else:
    lesser.append(element)
    return quick_sort(lesser) + [pivot] + quick_sort(greater)
    Quick sort without additional memory (in place):
    def partition(array, begin, end):
    pivot = begin
    for i in xrange(begin+1, end+1):
    if array[i] <= array[begin]:
    pivot += 1
    array[i], array[pivot] = array[pivot], array[i]
    array[pivot], array[begin] = array[begin], array[pivot]
    

    return pivot def quicksort(array, begin=0, end=None): if end is None:

    end = len(array) - 1
    def _quicksort(array, begin, end):
    if begin >= end:
    

    return

    pivot = partition(array, begin, end)
    _quicksort(array, begin, pivot-1)
    _quicksort(array, pivot+1, end)
    return _quicksort(array, begin, end)
    
  10. Question 4
    Senior

    What will be the output of the following code?

    • JavaScript
    Reveal answer

    Problem

    var Employee = {
      company: 'xyz'
    
    }
    var emp1 = Object.create(Employee);
    delete emp1.company
    console.log(emp1.company);
    
    ### Solution
    

    Above code will output xyz as output. Here emp1 object got company as prototype property. delete operator doesn't delete prototype property. emp1 object doesn't have company as its own property. You can test it like:

    console.log(emp1.hasOwnProperty('company'));
    //output : false
    

    However, we can delete company property directly from Employee object using delete Employee.company or we can also delete from emp1 object using proto property delete emp1.proto.company .

  11. Question 5
    Senior

    How would you create a private variable in JavaScript?

    • JavaScript
    Reveal answer

    To create a private variable in JavaScript that cannot be changed you need to create it as a local variable within a function. Even if the function is executed the variable cannot be accessed outside of the function. For example:

    function func() {
      var priv = "secret code";
    }
    console.log(priv);
    // throws error
    

    To access the variable, a helper function would need to be created that returns the private variable.

    function func() {
      var priv = "secret code";
      return function() {
        return priv;
      }
    }
    var getPriv = func();
    console.log(getPriv());
    // => secret code
    
  12. Question 5
    Senior

    Explain how Radix Sort works

    • Sorting Python JavaScript
    Reveal answer

    Radix sort is a sorting technique that sorts the elements by first grouping the individual digits of the same place value. Then, sort the elements according to their increasing/decreasing order. Radix sort uses counting sort as a subroutine to sort an array of numbers. Because integers can be used to represent strings (by hashing the strings to integers), radix sort works on data types other than just integers. Radix sort is a non-comparative sorting algorithm. It avoids comparison by creating and distributing elements into buckets according to their radix. For example, a binary system (using numbers 0 and 1) has a radix of 2 and a decimal system (using numbers 0 to 9) has a radix of 10. Radix sorts can be implemented to start at either the most significant digit (MSD) or least significant digit (LSD). For example, with 1234 , one could start with 1 (MSD) or 4 (LSD).

    Assume the input array is [123, 2, 999, 609, 111] :

    1. Based on the algorithm, we will sort the input array according to the one's digit (least significant digit, LSD): [0]:
    [1]: 111
    [2]: 002
    [3]: 123
    [4]:
    [5]:
    [6]:
    [7]:
    [8]:
    [9]: 999, 609
    // Note that we placed 999 before 609 because it appeared first.
    
    1. Now, we'll sort according to the ten's digit:
    [0]: 609, 002
    [1]: 111
    [2]: 123
    [3]:
    [4]:
    [5]:
    [6]:
    [7]:
    [8]:
    [9]: 999
    3. Finally , we sort according to the hundred's digit (most significant digit):
    [0]: 002
    [1]: 111, 123
    [2]:
    [3]:
    [4]:
    [5]:
    [6]: 609
    [7]:
    [8]:
    [9]: 999
    Complexity Analysis:
    Time Complexity: O(n) Space Complexity: O(n)
    
    Radix sort will operate on n d-digit numbers where each digit can be one of at most b different values (since b
    

    is the base (or radix) being used). For example, in base 10, a digit can be 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 or 9 . Radix sort uses counting sort on each digit. Each pass over n d -digit numbers will take O(n + b) time, and there are d passes total. Therefore, the total running time of radix sort is O(d(n+b)) . When d is a constant and b isn't much larger than n (in other words, b=O(n) ), then radix sort takes linear time. The space complexity comes from counting sort, which requires O(n+b) space to hold the counts, indices, and output lists. Implementation: JS

    /* Radix Sort implementation in JavaScript */
    function radixSort(arr) {
      var maxDigit = getMaxDigitLen(arr);//Looping for every digit index from leftmost digits to rightmost digits
      for (var i = 1; i <= maxDigit; i++) {
        // rebuild the digit buckets according to this digit
        var digitBuckets = [];
        for (var j = 0; j < arr.length; j++) {
          var digit = getDigit(arr[j], i);
          //get the i-th digit of the j-th element of the array
          digitBuckets[digit] = digitBuckets[digit] || [];
          //If empty initialize with empty array
          digitBuckets[digit].push(arr[j]);
          //Add the number in it's respective digits bucket
        }
      // rebuild the array according to this digit
      var index = 0;
      for (var k = 0; k < digitBuckets.length; k++) {
        if (digitBuckets[k] && digitBuckets[k].length > 0) {
          for (j = 0; j < digitBuckets[k].length; j++) {
            arr[index++] = digitBuckets[k][j];
          }
      }
    }
    }
    return arr;
    }// helper function to get the last n-th(position) digit of a number
    var getDigit = function(num, position) {
      var num_length = num.toString().length;
      if (num_length < position)
      return 0;
      var radixPosition = Math.pow(10, position - 1);
      //number with the positions-th power of 10
      /*
    

    Logic: To find the 2nd digit of the number 123 we can divide it by 10, which is 12 and the using the modulus operator(%) we can find 12 % 10 = 2

    */
    var digit = (Math.floor(num / radixPosition)) % 10;
    return digit;
    };// helper function get the length of digits of the max value in this array
    var getMaxDigitLen = function(arr) {
      var maxVal = Math.max.apply(Math, arr);
      //Finding max value from the array
      return Math.ceil(Math.log10(maxVal));
    };
    
    PY
    import math
    def counting_sort(A, digit, radix):
    

    #"A" is a list to be sorted, radix is the base of the number system, digit is the digit #we want to sort by #create a list B which will be the sorted list

    B = [0]*len(A)
    C = [0]*int(radix)
    

    #counts the number of occurences of each digit in A

    for i in range(0, len(A)):
    digit_of_Ai = (A[i]/radix**digit)%radix
    C[digit_of_Ai] = C[digit_of_Ai] +1
    #now C[i] is the value of the number of elements in A equal to i
    

    #this FOR loop changes C to show the cumulative # of digits up to that index of C

    for j in range(1,radix):
    C[j] = C[j] + C[j-1]
    #here C is modifed to have the number of elements <= i
    for m in range(len(A)-1, -1, -1):
    #to count down (go through A backwards)
    digit_of_Ai = (A[m]/radix**digit)%radix
    C[digit_of_Ai] = C[digit_of_Ai] -1
    B[C[digit_of_Ai]] = A[m]
    

    return B def radix_sort(A, radix): #radix is the base of the number system #k is the largest number in the list

    k = max(A)
    

    #output is the result list we will build output = A #compute the number of digits needed to represent k

    digits = int(math.floor(math.log(k, radix)+1))
    for i in range(digits):
    output = counting_sort(output,i,radix)
    

    return output

  13. Question 5
    Senior

    What will the following code output?

    • JavaScript
    Reveal answer

    Problem

    0.1 + 0.2 === 0.3
    
    ### Solution
    

    This will surprisingly output false because of floating point errors in internally representing certain numbers. 0.1 + 0.2 does not nicely come out to 0.3 but instead the result is actually 0.30000000000000004 because the computer cannot internally represent the correct number. One solution to get around this problem is to round the results when doing arithmetic with decimal numbers.

  14. Question 6
    Senior

    How would you prevent Callback Hell without using promises, async or generators?

    • Node.js JavaScript
    Reveal answer
    1. Don't nest functions. Give them names and place them at the top level of your program. Keep your code shallow.
    2. Use function hoisting to your advantage to move functions 'below the fold'
    3. Handle every single error in every one of your callbacks. Use a linter like standard to help you with this.
    4. Modularize. Create reusable functions and place them in a module to reduce the cognitive load required to understand your code. Splitting your code into small pieces like this also helps you handle errors, write tests, forces you to create a stable and documented public API for your code, and helps with refactoring. The most important aspect of avoiding callback hell is moving functions out of the way so that the flow of the program can be more easily understood without newcomers having to wade through all the detail of the functions to get to the meat of what the program is trying to do.
  15. Question 6
    Senior

    Binet's formula: How to calculate Fibonacci numbers without Recursion or Iteration?

    • Fibonacci Series Data Structures C# JavaScript
    Reveal answer

    There is actually a simple mathematical formula called Binet's formula for computing the nth Fibonacci number, which does not require the calculation of the preceding numbers: It features the Golden Ratio (φ):

    φ = (1+sqrt(5))/2
    

    or The iterative approach scales linearly, while the formula approach is basically constant time. Complexity Analysis: Time Complexity: O(log n) Space Complexity: O(log n) Assuming that the primitive mathematical operations (+, -, * and /) are O(1) you can use this result to compute the n th Fibonacci number in O(log n) time ( O(log n) because of the exponentiation in the formula). Implementation: CS

    static double inverseSqrt5 = 1 / Math.Sqrt(5);
    static double phi = (1 + Math.Sqrt(5)) / 2;
    /* should use
    const double inverseSqrt5 = 0.44721359549995793928183473374626
    const double phi = 1.6180339887498948482045868343656
    */
    static int Fibonacci(int n) {
      return (int)Math.Floor(Math.Pow(phi, n) * inverseSqrt5 + 0.5);
    }
    JS
    const sqrt = Math.sqrt;
    const pow = Math.pow;
    const fibCalc = n => Math.round(
    (1 / sqrt(5)) *
    (
    pow(((1 + sqrt(5)) / 2), n) -
    pow(((1 - sqrt(5)) / 2), n)
    )
    );
    Java
    private static long fibonacci(int n) {
      double pha = pow(1 + sqrt(5), n);
      double phb = pow(1 - sqrt(5), n);
      double div = pow(2, n) * sqrt(5);
      return (long)((pha - phb) / div);
    }
    PY
    
    def fib_formula(n):
    golden_ratio = (1 + math.sqrt(5)) / 2
    val = (golden_ratio**n - (1 - golden_ratio)**n) / math.sqrt(5)
    return int(round(val))
    
  16. Question 6
    Senior

    Calculate n-th Fibonacci number using Tail Recursion

    • Fibonacci Series JavaScript
    Reveal answer

    In traditional recursion, you perform the recursive call, take the return value of that call and calculate the results. You get the results of your calculation only until you’ve returned from every recursive call, requiring a lot of space on the call stack:

    function fib(n){
      if (n === 1) return 0;
      if (n === 2) return 1;
      return fib(n — 1) + fib(n — 2);
    }
    

    In tail recursion, you calculate the results first, and pass the results of your current call onto the next recursive call:

    function fib(n, a = 0, b = 1){
      if (n > 0) {
        return fib(n - 1, b, a + b)
      }
    

    return a

    }
    

    Now, when you are ready to calculate the next call, you don’t need the current stack frame. You are calculating the results and passing them as parameters to your next call. No more worries about stack overflow! This tail recursive solution is constant O(n) time and constant O(n) space complexity. Implementation: JS

    function fib(n, a = 0, b = 1){
      if (n > 0) {
        return fib(n - 1, b, a + b)
      }
    

    return a

    }
    Java
    private static final int FIB_0 = 0;
    private static final int FIB_1 = 1;
    private int calcFibonacci(final int target) {
      if (target == 0) { return FIB_0; }
      if (target == 1) { return FIB_1; }
      return calcFibonacci(target, 1, FIB_1, FIB_0);
    }
    private int calcFibonacci(final int target, final int previous, final int fibPrevious, final int
    fibPreviousMinusOne) {
      final int current = previous + 1;
      final int fibCurrent = fibPrevious + fibPreviousMinusOne;
      // If you want, print here / memoize for future calls
      if (target == current) { return fibCurrent; }
      return calcFibonacci(target, current, fibCurrent, fibPrevious);
    }
    
  17. Question 6
    Senior

    What are the actual uses of ES6 WeakMap?

    • JavaScript
    Reveal answer

    WeakMaps provide a way to extend objects from the outside without interfering with garbage collection. Whenever you want to extend an object but can't because it is sealed - or from an external source - a WeakMap can be applied. WeakMap is only available for ES6 and above. A WeakMap is a collection of key and value pairs where the key must be an object.

    var map = new WeakMap();
    var pavloHero = {
      first: "Pavlo",
      last: "Hero"
    };
    var gabrielFranco = {
      first: "Gabriel",
      last: "Franco"
    };
    map.set(pavloHero, "This is Hero");
    map.set(gabrielFranco, "This is Franco");
    console.log(map.get(pavloHero));
    //This is Hero
    

    The interesting aspect of the WeakMaps is the fact that it holds a weak reference to the key inside the map. A weak reference means that if the object is destroyed, the garbage collector will remove the entire entry from the WeakMap, thus freeing up memory.

  18. Question 7
    Senior

    When would you use import * as X from 'X' ?

    • Node.js JavaScript
    Reveal answer

    Modules with multiple (and even single) exports which do not define a default export will need to have all exports assigned to a named variable, like:

    import * as whatever from 'package';
    
  19. Question 7
    Senior

    Calculate n-th Fibonacci number using Tail Recursion

    • Fibonacci Series JavaScript
    Reveal answer

    In traditional recursion, you perform the recursive call, take the return value of that call and calculate the results. You get the results of your calculation only until you’ve returned from every recursive call, requiring a lot of space on the call stack:

    function fib(n){
      if (n === 1) return 0;
      if (n === 2) return 1;
      return fib(n — 1) + fib(n — 2);
    }
    

    In tail recursion, you calculate the results first, and pass the results of your current call onto the next recursive call:

    function fib(n, a = 0, b = 1){
      if (n > 0) {
        return fib(n - 1, b, a + b)
      }
    

    return a

    }
    

    Now, when you are ready to calculate the next call, you don’t need the current stack frame. You are calculating the results and passing them as parameters to your next call. No more worries about stack overflow! This tail recursive solution is constant O(n) time and constant O(n) space complexity. Implementation: JS

    function fib(n, a = 0, b = 1){
      if (n > 0) {
        return fib(n - 1, b, a + b)
      }
    

    return a

    }
    Java
    private static final int FIB_0 = 0;
    private static final int FIB_1 = 1;
    private int calcFibonacci(final int target) {
      if (target == 0) { return FIB_0; }
      if (target == 1) { return FIB_1; }
    
      return calcFibonacci(target, 1, FIB_1, FIB_0);
    }
    private int calcFibonacci(final int target, final int previous, final int fibPrevious, final int
    fibPreviousMinusOne) {
      final int current = previous + 1;
      final int fibCurrent = fibPrevious + fibPreviousMinusOne;
      // If you want, print here / memoize for future calls
      if (target == current) { return fibCurrent; }
      return calcFibonacci(target, current, fibCurrent, fibPrevious);
    }
    
  20. Question 7
    Senior

    Explain when and how to use Exponential (aka Doubling or Galloping) Search?

    • Searching JavaScript
    Reveal answer

    Exponential Search (also called Doubling Search or Galloping Search or Struzik Search) is explicitly designed for sorted, unbounded lists (infinite arrays or arrays with unknown size) whereas binary search deals with bounded lists (size is known). It has two steps:

    1. Search for a position of first element greater or equal than the target value. Assuming that the list is sorted in ascending order, the algorithm looks for the first exponent, j , where the value arr(2j) is greater than the search key (target value). If the element at the current index is smaller than the search key, the algorithm repeats, skipping to the next search index by doubling it, calculating the next power of 2.
    2. Do the binary search from the beginning to the found end Complexity Analysis: Time Complexity: O(log n) Space Complexity: O(log n) The first stage of the algorithm takes O(log i) time, where i is the index where the search key would be in the list. The second part of the algorithm also takes
    O(log i) time. As the second stage is simply a binary search, it
    takes
    O(
    log n) where n is the size of the interval being searched. This gives the algorithm a total runtime,
    

    calculated by summing the runtimes of the two stages, of

    O(log i) +_ O(log i) _ =
    2 O(log i) =
    O(log i) .
    Implementation:
    JS
    function exponentialSearch(arrayToSearch, valueToSearch){
      if (arrayToSearch[0] == valueToSearch){
        return 0;
      }
    var i = 1;
    while (i < arrayToSearch.length && arrayToSearch[i] <= valueToSearch){
      i = i*2;
    }
    return binarySearch(arrayToSearch, valueToSearch);
    }
    PY
    def exponential_search(arr, p):
    i = 0
    while (arr[2 ** i] < p):
    i += 1
    binary_search(arr, p, i)
    
  21. Question 7
    Senior

    How can you share code between files?

    • JavaScript
    Reveal answer

    This depends on the JavaScript environment. On the client (browser environment), as long as the variables/functions are declared in the global scope ( window ), all scripts can refer to them. Alternatively, adopt the Asynchronous Module Definition (AMD) via RequireJS for a more modular approach. On the server (Node.js), the common way has been to use CommonJS. Each file is treated as a module and it can export variables and functions by attaching them to the module.exports object. ES2015 defines a module syntax which aims to replace both AMD and CommonJS. This will eventually be supported in both browser and Node environments.

  22. Question 8
    Senior

    Does JavaScript have a map function to iterate over an object properties?

    • Node.js JavaScript
    Reveal answer

    Consider solution that returns a new object and leaves the original object as it is

    var myObject = { 'a': 1, 'b': 2, 'c': 3 };// returns a new object with the values at each key mapped using mapFn(value)
    function objectMap(object, mapFn) {
      return Object.keys(object).reduce(function(result, key) {
        result[key] = mapFn(object[key])
    

    return result

    }, {})
    }
    var newObject = objectMap(myObject, function(value) {
    

    return value * 2

    })
    console.log(newObject);
    // => { 'a': 2, 'b': 4, 'c': 6 }
    console.log(myObject);
    // => { 'a': 1, 'b': 2, 'c': 3 }
    

    Or with ES6 fromEntries , entries features:

    const objectMap = (obj, fn) =>
    Object.fromEntries(
    Object.entries(obj).map(
    ([k, v], i) => [k, fn(v, k, i)]
    )
    )
    const myObject = { a: 1, b: 2, c: 3 }
    console.log(objectMap(myObject, v => 2 * v))
    
  23. Question 9
    Senior

    Could you compare usage of Module Pattern vs Constructor/Prototype pattern?

    • JavaScript
    Reveal answer

    The module pattern is typically used for namespacing, where you'll have a single instance acting as a store to group related functions and objects. This is a different use case from what prototyping is good for. They're not really competing with each other; you can quite happily use both together (eg put a constructor-function inside a module and say new MyNamespace.MyModule.MyClass(arguments) ). Constructor-functions and prototypes are one of the reasonable ways to implement classes and instances. They don't quite correspond to that model so you typically need to choose a particular scheme or helper method to implement classes in terms of prototypes.

  24. Question 9
    Senior

    How to recursively reverse a Linked List?

    • Linked Lists Recursion JavaScript
    Reveal answer

    Start from the bottom up by asking and answering tiny questions: What is the reverse of null (the empty list)? null . What is the reverse of a one element list? the element. What is the reverse of an n element list? the reverse of the rest of the list followed by the first element. P.S.

    How to understand that part?

    head.next.next = head;
    head.next = null;
    

    Think about the origin link list: 1->2->3->4->5 Now assume that the last node has been reversed. Just like this: 1->2->3->4<-5 And this time you are at the node 3 , you want to change 3->4 to 3<-4 , means let 3->next->next = 3 (as 3-

    next is 4 and 4->next = 3 is to reverse it) Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n) Assume that n is the list's length, the time complexity is

    O(
    n) . The extra space comes from implicit stack space
    

    due to recursion. The recursion could go up to n levels deep then space complexity is

    O(
    n) .
    Implementation:
    JS
    var reverseList = function(head) {
      if (!head) {
        return head;
      }
    let pre = head.next;
    head.next = null;
    return fun(head, pre);
    function fun(cur, pre) {
      if (pre == null) {
        return cur;
      }
    let tmp = pre.next;
    pre.next = cur;
    return fun(pre, tmp);
    }
    }
    Java
    Node reverse(Node head) {
      // if head is null or only one node, it's reverse of itself.
      if ( (head == null) || (head.next == null) ) return head;// reverse the sub-list leaving the head node.
      Node reverse = reverse(head.next);// head.next still points to the last element of reversed sub-list.
    
      // so move the head to end.
      head.next.next = head;// point last node to nil, (get rid of cycles)
      head.next = null;
      return reverse;
    }
    PY
    class Solution(object):
    def reverseList(self, head):
    # Recursive
    """
    :type head: ListNode
    :rtype: ListNode
    """
    if not head or not head.next:
    

    return head

    p = self.reverseList(head.next)
    head.next.next = head
    head.next = None
    

    return p

  25. Question 10
    Senior

    What's the difference between a variable that is: null , undefined or undeclared? How would you go about checking for any of these states?

    • JavaScript
    Reveal answer

    Undeclared variables are created when you assign a value to an identifier that is not previously created using var , let or const . Undeclared variables will be defined globally, outside of the current scope. In strict mode, a ReferenceError will be thrown when you try to assign to an undeclared variable. Undeclared variables are bad just like how global variables are bad. Avoid them at all cost! To check for them, wrap its usage in a try / catch block.

    function foo() {
      x = 1;
      // Throws a ReferenceError in strict mode
    }
    foo();
    console.log(x);
    // 1
    

    A variable that is undefined is a variable that has been declared, but not assigned a value. It is of type undefined . If a function does not return any value as the result of executing it is assigned to a variable, the variable also has the value of undefined . To check for it, compare using the strict equality ( === ) operator or typeof which will give the 'undefined' string. Note that you should not be using the abstract equality operator to check, as it will also return true if the value is null .

    var foo;
    console.log(foo);
    // undefined
    console.log(foo === undefined);
    // true
    console.log(typeof foo === 'undefined');
    // true
    console.log(foo == null);
    // true. Wrong, don't use this to check!
    function bar() {}
    var baz = bar();
    console.log(baz);
    // undefined
    

    A variable that is null will have been explicitly assigned to the null value. It represents no value and is different from undefined in the sense that it has been explicitly assigned. To check for null, simply compare using the strict equality operator. Note that like the above, you should not be using the abstract equality operator ( == ) to check, as it will also return true if the value is undefined .

    var foo = null;
    console.log(foo === null);
    // true
    console.log(typeof foo === 'object');
    // true
    
    console.log(foo == undefined);
    // true. Wrong, don't use this to check!
    

    As a personal habit, I never leave my variables undeclared or unassigned. I will explicitly assign null to them after declaring if I don't intend to use it yet. If you use a linter in your workflow, it will usually also be able to check that you are not referencing undeclared variables.

  26. Question 11
    Senior

    Explain how JSONP works (and how it's not really Ajax)

    • JavaScript
    Reveal answer

    JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers because Ajax requests from the current page to a cross-origin domain is not allowed. JSONP works by making a request to a cross-origin domain via a tag and usually with a callback query parameter, for example: https://example.com?callback=printData . The server will then wrap the data within a function called printData and return it to the client.

    // File loaded from https://example.com?callback=printData printData({ name: 'Yang Shun' });

    
    The client has to have the printData function in its global scope and the function will be executed by the client
    when the response from the cross-origin domain is received.
    JSONP can be unsafe and has some security implications. As JSONP is really JavaScript, it can do everything else
    JavaScript can do, so you need to trust the provider of the JSONP data.
    These days, CORS is the recommended approach and JSONP is seen as a hack.
    
  27. Question 11
    Senior

    What is the new keyword in JavaScript?

    • JavaScript
    Reveal answer
    1. It creates a new object. The type of this object is simply object .
    2. It sets this new object's internal, inaccessible, [[prototype]] (i.e. proto ) property to be the constructor
    function's external, accessible, prototype object (every function object automatically has a prototype
    property).
    
    1. It makes the this variable point to the newly created object.
    2. It executes the constructor function, using the newly created object whenever this is mentioned.
    3. It returns the newly created object, unless the constructor function returns a non-null object reference. In this case, that object reference is returned instead. Consider:
    function New(func) {
      var res = {};
      if (func.prototype !== null) {
        res.__proto__ = func.prototype;
      }
    var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));
    if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {
      return ret;
    }
    return res;
    }
    
  28. Question 12
    Senior

    What is the Temporal Dead Zone in ES6?

    • JavaScript
    Reveal answer

    In ES6 let and const are hoisted (like var , class and function ), but there is a period between entering scope and being declared where they cannot be accessed. This period is the temporal dead zone (TDZ). Consider:

    //console.log(aLet) // would throw ReferenceError
    let aLet;
    
    console.log(aLet);
    // undefined
    aLet = 10;
    console.log(aLet);
    // 10
    

    In this example the TDZ ends when aLet is declared, rather than assigned.

  29. Question 12
    Senior

    Explain difference between: function Person(){} , var person = Person() , and var person = new Person() ?

    • JavaScript
    Reveal answer

    This question is pretty vague. My best guess at its intention is that it is asking about constructors in JavaScript. Technically speaking, function Person(){} is just a normal function declaration. The convention is to use PascalCase for functions that are intended to be used as constructors.

    var person = Person() invokes the Person as a function, and not as a constructor. Invoking as such is a common
    

    mistake if it the function is intended to be used as a constructor. Typically, the constructor does not return anything, hence invoking the constructor like a normal function will return undefined and that gets assigned to the variable intended as the instance.

    var person = new Person() creates an instance of the Person object using the new operator, which inherits from
    Person.prototype . An alternative would be to use Object.create , such as: Object.create(Person.prototype) .
    function Person(name) {
      this.name = name;
    }
    var person = Person('John');
    console.log(person);
    // undefined
    console.log(person.name);
    // Uncaught TypeError: Cannot read property 'name' of undefined
    var person = new Person('John');
    
    console.log(person);
    // Person { name: "John" }
    console.log(person.name);
    // "john"
    
  30. Question 13
    Senior

    Explain Prototype Inheritance in JavaScript?

    • JavaScript
    Reveal answer

    In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects - and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class. In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. Every object in Javascript has a prototype. JavaScript's inheritance system is prototypical, and not class-based. When a messages reaches an object, JavaScript will attempt to find a property in that object first, if it cannot find it then the message will be sent to the object’s prototype and so on. That behavior called prototype chain or prototype inheritance. Constructor functions are the most used way in JavaScript to construct prototype chains. When we use new , JavaScript injects an implicit reference to the new object being created in the form of the this keyword. It also returns this reference implicitly at the end of the function.

    function Foo() {
      this.kind = ‘foo’
    }
    var foo = new Foo();
    foo.kind
    //=> ‘foo’
    
  31. Question 13
    Senior

    Can you give an example for destructuring an object or an array in ES6?

    • JavaScript
    Reveal answer

    Destructuring is an expression available in ES6 which enables a succinct and convenient way to extract values of Objects or Arrays and place them into distinct variables. Array destructuring

    // Variable assignment.
    const foo = ['one', 'two', 'three'];
    const [one, two, three] = foo;
    console.log(one);
    // "one"
    console.log(two);
    // "two"
    console.log(three);
    // "three"
    // Swapping variables
    let a = 1;
    let b = 3;
    [a, b] = [b, a];
    console.log(a);
    // 3
    console.log(b);
    // 1
    Object destructuring
    // Variable assignment.
    const o = { p: 42, q: true };
    const { p, q } = o;
    console.log(p);
    // 42
    console.log(q);
    // true
    
  32. Question 14
    Senior

    When would you use the bind function?

    • JavaScript
    Reveal answer

    The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. A good use of the bind function is when you have a particular function that you want to call with a specific this value. You can then use bind to pass a specific object to a function that uses a this reference.

    function fullName() {
      return "Hello, this is " + this.first + " " + this.last;
    }
    console.log(fullName());
    // => Hello this is undefined undefined
    // create a person object and pass its values to the fullName function
    var person = {first: "Foo", last: "Bar"};
    console.log(fullName.bind(person)());
    // => Hello this is Foo Bar
    
  33. Question 14
    Senior

    When should you NOT use arrow functions in ES6? Name three or more cases.

    • JavaScript
    Reveal answer

    Arrow functions should NOT be used: When we want function hoisting - as arrow functions are anonymous. When we want to use this/arguments in a function - as arrow functions do not have this/arguments of their own, they depend upon their outer context. When we want to use named function - as arrow functions are anonymous.

    When we want to use function as a constructor - as arrow functions do not have their own this. When we want to add function as a property in object literal and use object in it - as we can not access this (which should be object itself).

  34. Question 15
    Senior

    Explain the Prototype Design Pattern

    • JavaScript
    Reveal answer

    The Prototype Pattern creates new objects, but rather than creating non-initialized objects it returns objects that are initialized with values it copied from a prototype - or sample - object. The Prototype pattern is also referred to as the Properties pattern. An example of where the Prototype pattern is useful is the initialization of business objects with values that match the default values in the database. The prototype object holds the default values that are copied over into a newly created business object. Classical languages rarely use the Prototype pattern, but JavaScript being a prototypal language uses this pattern in the construction of new objects and their prototypes.

  35. Question 16
    Senior

    What tools can be used to assure consistent code style?

    • JavaScript
    Reveal answer

    You have plenty of options to do so: JSLint by Douglas Crockford JSHint ESLint JSCS These tools are really helpful when developing code in teams, to enforce a given style guide and to catch common errors using static analysis.

  36. Question 16
    Senior

    Describe the JS module design pattern

    • JavaScript
    Reveal answer

    JavaScript modules are the most prevalently used design patterns for keeping particular pieces of code independent of other components. This provides loose coupling to support well-structured code. Modules should be Immediately-Invoked-Function-Expressions (IIFE) to allow for private scopes - that is, a closure that protect variables and methods (however, it will return an object instead of a function). This is what it looks like:

    (function() {
      // declare private variables and/or functions
      return {
        // declare public variables and/or functions
      }
    })();
    

    Here we instantiate the private variables and/or functions before returning our object that we want to return. Code outside of our closure is unable to access these private variables since it is not in the same scope.

  37. Question 17
    Senior

    What is Closure in JavaScript? Provide an example

    • JavaScript
    Reveal answer

    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 variable in three scopes: Variable declared in his own scope Variable declared in parent function scope Variable declared in global namespace

    var globalVar = "abc";// Parent self invoking function
    (function outerFunction (outerArg) {
      // begin of scope outerFunction
      // Variable declared in outerFunction function scope
      var outerFuncVar = 'x';
      // Closure self-invoking function
      (function innerFunction (innerArg) {
        // begin of scope innerFunction
        // variable declared in innerFunction function scope
        var innerFuncVar = "y";
        console.log(
        "outerArg = " + outerArg + "\n" +
        "outerFuncVar = " + outerFuncVar + "\n" +
        "innerArg = " + innerArg + "\n" +
        "innerFuncVar = " + innerFuncVar + "\n" +
        "globalVar = " + globalVar);
        // end of scope innerFunction
      })(5);
    // Pass 5 as parameter
    // end of scope outerFunction
    })(7);
    // Pass 7 as parameter
    

    innerFunction is closure which is defined inside outerFunction and has access to all variable which is declared and defined in outerFunction scope. In addition to this function defined inside function as closure has access to variable which is declared in global namespace . Output of above code would be:

    outerArg = 7
    outerFuncVar = x
    innerArg = 5
    innerFuncVar = y
    globalVar = abc
    
  38. Question 18
    Senior

    Explain what is Hoisting in Javascript

    • JavaScript
    Reveal answer

    Hoisting is the concept in which Javascript, by default, moves all declarations to the top of the current scope. As such, a variable can be used before it has been declared. Note that Javascript only hoists declarations and not initializations.

  39. Question 18
    Senior

    Write a recursive function that performs a binary search

    • JavaScript
    Reveal answer
    function recursiveBinarySearch(array, value, leftPosition, rightPosition) {
      // Value DNE
      if (leftPosition > rightPosition) return -1;
      var middlePivot = Math.floor((leftPosition + rightPosition) / 2);
      if (array[middlePivot] === value) {
        return middlePivot;
      } else if (array[middlePivot] > value) {
        return recursiveBinarySearch(array, value, leftPosition, middlePivot - 1);
      } else {
        return recursiveBinarySearch(array, value, middlePivot + 1, rightPosition);
      }
    }
    
  40. Question 19
    Senior

    Given an integer, determine if it is a power of 2. If so, return that number, else return -1

    • JavaScript
    Reveal answer

    Note, 0 is not a power of two.

    isPowerOfTwo(4);
    // true
    isPowerOfTwo(64);
    // true
    isPowerOfTwo(1);
    // true
    isPowerOfTwo(0);
    // false
    isPowerOfTwo(-1);
    // false
    // For the non-zero case:
    function isPowerOfTwo(number) {
      // `&` uses the bitwise n.
      // In the case of number = 4; the expression would be identical to:
      // `return (4 & 3 === 0)`
      // In bitwise, 4 is 100, and 3 is 011. Using &, if two values at the same
      // spot is 1, then result is 1, else 0. In this case, it would return 000,
      // and thus, 4 satisfies are expression.
      // In turn, if the expression is `return (5 & 4 === 0)`, it would be false
      // since it returns 101 & 100 = 100 (NOT === 0)
      return number & (number - 1) === 0;
    }// For zero-case:
    function isPowerOfTwoZeroCase(number) {
      return (number !== 0) && ((number & (number - 1)) === 0);
    }
    
  41. Question 19
    Senior

    Check if a given string is a isomorphic

    • JavaScript
    Reveal answer

    For two strings to be isomorphic, all occurrences of a character in string A can be replaced with another character to get string B. The order of the characters must be preserved. There must be one-to-one mapping for ever char of string A to every char of string B. paper and title would return true. egg and sad would return false. dgg and add would return true.

    isIsomorphic("egg", 'add');
    // true
    isIsomorphic("paper", 'title');
    // true
    isIsomorphic("kick", 'side');
    // false
    function isIsomorphic(firstString, secondString) {// Check if the same lenght. If not, they cannot be isomorphic
      if (firstString.length !== secondString.length) return false
      var letterMap = {};
      for (var i = 0; i < firstString.length; i++) {
        var letterA = firstString[i],
        letterB = secondString[i];
    
        // If the letter does not exist, create a map and map it to the value
        // of the second letter
        if (letterMap[letterA] === undefined) {
          letterMap[letterA] = letterB;
        } else if (letterMap[letterA] !== letterB) {
          // Eles if letterA already exists in the map, but it does not map to
          // letterB, that means that A is mapping to more than one letter.
          return false;
        }
    }
    // If after iterating through and conditions are satisfied, return true.
    // They are isomorphic
    return true;
    }
    
  42. Question 20
    Senior

    Create a function that will evaluate if a given expression has balanced parentheses using stacks

    • JavaScript
    Reveal answer

    In this example, we will only consider {} as valid parentheses {}{} would be considered balancing. {{{}} is not balanced.

    var expression = "{{}}{}{}"
    var expressionFalse = "{}{{}";
      isBalanced(expression);
      // true
      isBalanced(expressionFalse);
      // false
      isBalanced("");
      // true
      function isBalanced(expression) {
        var checkString = expression;
        var stack = [];// If empty, parentheses are technically balanced
        if (checkString.length <= 0) return true;
        for (var i = 0; i < checkString.length; i++) {
          if(checkString[i] === '{') {
              stack.push(checkString[i]);
            } else if (checkString[i] === '}') {
          // Pop on an empty array is undefined
          if (stack.length > 0) {
            stack.pop();
          } else {
            return false;
          }
      }
    }// If the array is not empty, it is not balanced
    
    if (stack.pop()) return false;
    return true;
    }
    
  43. Question 20
    Senior

    What does the term Transpiling stand for?

    • JavaScript
    Reveal answer

    There's no way to polyfill new syntax that has been added to the language. So the better option is to use a tool that converts your newer code into older code equivalents. This process is commonly called transpiling, a term for transforming + compiling. Typically you insert the transpiler into your build process, similar to your code linter or your minifier. There are quite a few great transpilers for you to choose from: Babel: Transpiles ES6+ into ES5 Traceur: Transpiles ES6, ES7, and beyond into ES5

Expert questions

12 questions
  1. Question 8
    Expert

    Does JavaScript pass by references or pass by values?

    • Node.js JavaScript
    Reveal answer

    Primitives are passed by value, and Objects are passed by copy of a reference. Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, and it is possible to modify the contents of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller - i.e. the reference itself is passed by value:

    function replace(ref) {
      ref = {};
      // this code does _not_ affect the object passed
    }
    function update(ref) {
      ref.key = 'newvalue';
      // this code _does_ affect the _contents_ of the object
    }
    var a = { key: 'value' };
    replace(a);
    // a still has its original value - it's unmodfied
    update(a);
    // the _contents_ of 'a' are changed
    
  2. Question 8
    Expert

    In JavaScript, why is the this operator inconsistent?

    • JavaScript
    Reveal answer

    The most important thing to understand is that a function object does not have a fixed this value -- the value of this changes depending on how the function is called. We say that a function is invoked with some a particular this value -- the this value is determined at invocation time, not definition time. If the function is called as a "raw" function (e.g., just do someFunc() ), this will be the global object ( window in a browser) (or undefined if the function runs in strict mode). If it is called as a method on an object, this will be the calling object. If you call a function with call or apply , this is specified as the first argument to call or apply . If it is called as an event listener, this will be the element that is the target of the event.

    If it is called as a constructor with new , this will be a newly-created object whose prototype is set to the prototype property of the constructor function. If the function is the result of a bind operation, the function will always and forever have this set to the first argument of the bind call that produced it. (This is the single exception to the "functions don't have a fixed this " rule -- functions produced by bind actually

    do have an immutable this .)
    
  3. Question 10
    Expert

    Generating Fibonacci Sequence using ES6 generator functions

    • Fibonacci Series JavaScript
    Reveal answer

    ES6 introduced a new way of working with functions and iterators in the form of Generators (or generator functions). A generator is a function that can stop midway and then continue from where it stopped. In short, a generator appears to be a function but it behaves like an iterator. For example:

    function * iterableObj() {
      yield 'This';
      yield 'is';
      yield 'iterable.'
    }
    for (const val of iterableObj()) {
      console.log(val);
    }
    // This
    // is
    // iterable.
    Implementation:
    JS
    // Iterative Solution for Fibonacci Numbers
    function *fibonacci(n) {
      const infinite = !n && n !== 0;
      let current = 0;
      let next = 1;
      while (infinite || n--) {
        yield current;
        [current, next] = [next, current + next];
      }
    }// Recursive Solution for Fibonacci Numbers
    function *fibonacci(n = null, current = 0, next = 1) {
      if (n === 0) {
        return current;
      }
    let m = n !== null ? n - 1 : null;
    yield current;
    yield *fibonacci(m, next, current + next);
    }
    
  4. Question 11
    Expert

    Compare Async/Await and Generators usage to achive same functionality

    • JavaScript
    Reveal answer

    Generator function are executed yield by yield i.e one yield-expression at a time by its iterator (the next method) where as Async-await, they are executed sequential await by await. Async/await makes it easier to implement a particular use case of Generators. The return value of Generator is always {value: X, done: Boolean} where as for Async function it will always be a promise that will either resolve to the value X or throw an error. Async function can be decomposed into Generator and promise implementation like:

  5. Question 12
    Expert

    Is it possible to reset an ECMAScript 6 generator to its initial state?

    • JavaScript
    Reveal answer

    Once a generator enters the "completed" state it never leaves it and its associated execution context is never resumed. Any execution state associated with generator can be discarded at this point.

  6. Question 13
    Expert

    What is the difference between the await keyword and the yield keyword?

    • JavaScript
    Reveal answer

    yield can be considered to be the building block of await . yield takes the value it's given and passes it to the caller. The caller can then do whatever it wishes with that value (1). Later the caller may give a value back to the generator (via generator.next() ) which becomes the result of the yield expression (2), or an error that will appear to be thrown by the yield expression (3).

    async - await can be considered to use yield . At (1) the caller (i.e. the async - await driver - similar to the

    function you posted) will wrap the value in a promise using a similar algorithm to new Promise(r => r(value)
    (note,
    not Promise.resolve , but that's not a big deal). It then waits for the promise to resolve. If it fulfills, it
    passes the fulfilled value back at (2). If it rejects, it throws the rejection reason as an error at (3).
    

    So the utility of async - await is this machinery that uses yield to unwrap the yielded value as a promise and pass its resolved value back, repeating until the function returns its final value.

  7. Question 14
    Expert

    In JavaScript, why is the this operator inconsistent?

    • JavaScript
    Reveal answer

    The most important thing to understand is that a function object does not have a fixed this value -- the value of this changes depending on how the function is called. We say that a function is invoked with some a particular this value -- the this value is determined at invocation time, not definition time. If the function is called as a "raw" function (e.g., just do someFunc() ), this will be the global object ( window in a browser) (or undefined if the function runs in strict mode). If it is called as a method on an object, this will be the calling object. If you call a function with call or apply , this is specified as the first argument to call or apply . If it is called as an event listener, this will be the element that is the target of the event. If it is called as a constructor with new , this will be a newly-created object whose prototype is set to the prototype property of the constructor function. If the function is the result of a bind operation, the function will always and forever have this set to the first argument of the bind call that produced it. (This is the single exception to the "functions don't have a fixed this " rule -- functions produced by bind actually

    do have an immutable this .)
    
  8. Question 15
    Expert

    How to deep-freeze object in JavaScript?

    • JavaScript
    Reveal answer

    If you want make sure the object is deep frozen you have to create a recursive function to freeze each property which is of type object: Without deep freeze:

    let person = {
      name: "Leonardo",
      profession: {
        name: "developer"
      }
    };
    Object.freeze(person);
    // make object immutable
    person.profession.name = "doctor";
    console.log(person);
    //output { name: 'Leonardo', profession: { name: 'doctor' } }
    

    With deep freeze:

    function deepFreeze(object) {
      let propNames = Object.getOwnPropertyNames(object);
      for (let name of propNames) {
        let value = object[name];
    
        object[name] = value && typeof value === "object" ?
        deepFreeze(value) : value;
      }
    return Object.freeze(object);
    }
    let person = {
      name: "Leonardo",
      profession: {
        name: "developer"
      }
    };
    deepFreeze(person);
    person.profession.name = "doctor";
    // TypeError: Cannot assign to read only property 'name' of object
    
  9. Question 16
    Expert

    Is JavaScript a pass-by-reference or pass-by-value language?

    • JavaScript
    Reveal answer

    It's always pass by value, but for objects the value of the variable is a reference. Because of this, when you pass an object and change its members, those changes persist outside of the function. This makes it look like pass by reference. But if you actually change the value of the object variable you will see that the change does not persist, proving it's really pass by value. Example:

    function changeStuff(a, b, c)
    {
      a = a * 10;
      b.item = "changed";
      c = {item: "changed"};
    }
    var num = 10;
    var obj1 = {item: "unchanged"};
    var obj2 = {item: "unchanged"};
    changeStuff(num, obj1, obj2);
    console.log(num);
    console.log(obj1.item);
    console.log(obj2.item);
    

    Output:

    10
    changed
    unchanged
    
  10. Question 17
    Expert

    Can you give an example of a curry function and why this syntax offers an advantage?

    • JavaScript
    Reveal answer

    Currying is a pattern where a function with more than one parameter is broken into multiple functions that, when called in series, will accumulate all of the required parameters one at a time. This technique can be useful for making code written in a functional style easier to read and compose. It's important to note that for a function to be curried, it needs to start out as one function, then broken out into a sequence of functions that each accepts one parameter.

    function curry(fn) {
      if (fn.length === 0) {
        return fn;
      }
    function _curried(depth, args) {
      return function(newArgument) {
        if (depth - 1 === 0) {
          return fn(...args, newArgument);
        }
      return _curried(depth - 1, [...args, newArgument]);
    };
    }
    return _curried(fn.length, []);
    }
    function add(a, b) {
      return a + b;
    }
    var curriedAdd = curry(add);
    var addFive = curriedAdd(5);
    var result = [0, 1, 2, 3, 4, 5].map(addFive);
    // [5, 6, 7, 8, 9, 10]
    
  11. Question 18
    Expert

    What's the difference between ES6 Map and WeakMap ?

    • JavaScript
    Reveal answer

    They both behave differently when a object referenced by their keys/values gets deleted. Lets take the below example code:

    var map = new Map(); var weakmap = new WeakMap();
    (function() {
      var a = {
        x: 12
      };
    var b = {
      y: 12
    };
    map.set(a, 1);
    weakmap.set(b, 2);
    })()
    The above IIFE is executed there is no way we can reference {x: 12} and {y: 12} anymore. Garbage collector
    goes ahead and deletes the key b pointer from “WeakMap” and also removes {y: 12} from memory. But in case
    of “Map”, the garbage collector doesn’t remove a pointer from “Map” and also doesn’t remove {x: 12} from
    memory.
    

    WeakMap allows garbage collector to do its task but not Map. With manually written maps, the array of keys would keep references to key objects, preventing them from being garbage collected. In native WeakMaps, references to key objects are held " weakly", which means that they do not prevent garbage collection in case there would be no other reference to the object.

  12. Question 19
    Expert

    Describe the Revealing Module Pattern design pattern

    • JavaScript
    Reveal answer

    A variation of the module pattern is called the Revealing Module Pattern. The purpose is to maintain encapsulation and reveal certain variables and methods returned in an object literal. The direct implementation looks like this:

    var Exposer = (function() {
      var privateVariable = 10;
      var privateMethod = function() {
        console.log('Inside a private method!');
        privateVariable++;
      }
    var methodToExpose = function() {
      console.log('This is a method I want to expose!');
    }
    var otherMethodIWantToExpose = function() {
      privateMethod();
    }
    return {
      first: methodToExpose,
      second: otherMethodIWantToExpose
    };
    })();
    Exposer.first();
    // Output: This is a method I want to expose!
    Exposer.second();
    // Output: Inside a private method!
    Exposer.methodToExpose;
    // undefined
    

    An obvious disadvantage of it is unable to reference the private methods