DEV Community

Halil Can Ozcelik
Halil Can Ozcelik

Posted on • Updated on

JavaScript Interview Coding Questions - 3

I am trying to explain some possible coding questions in software developer interviews. I will mention recursion and array mutation in this third article. These two topics are important in functional programming paradigm. Also, the last example is about prototypal inheritance which is crucial to understand inheritance in JavaScript.

  1. Write a recursive function to calculate the total of numbers between 1 to n?
    n will be the parameter of our function. So we should call this calculator function until reaching to 1 which is our end point. So, one of the possible effective solutions will be below code:

    function calculateTotal(number, total = 1) {
      return number > 1 ?
        calculateTotal(number - 1, total + number) :
        total;
    }
    
    console.log(calculateTotal(10));
    

    You can examine the code in below:

  2. Write a recursive factorial calculator function.
    We can easily adapt same logic to factorial calculation as below:

    function factorial(number, product = 1) {
      return number > 0 ?
        factorial(number - 1, product * number) :
        product;
    }
    
    console.log(factorial(5));
    

    !! The recursive functions above will cause stack overflow error for large inputs. In order to prevent it, Trampoline Pattern can be used as below:

    // recursive optimization to prevent stack overflow error
    function trampoline(fn) {
      return (...args) => {
        let result = fn(...args);
        while (typeof result === 'function') {
          result = result();
        }
        return result;
      };
    }
    
    // Write a recursive function to calculate the total of numbers between 1 to n?
    function calculateTotal(number, total = 1) {
      return number > 1 ?
        () => calculateTotal(number - 1, total + number) :
        total;
    }
    
    const totalCalculator = trampoline(calculateTotal);
    console.log(totalCalculator(100000));
    
    // Write a recursive factorial calculator function
    function factorial(number, product = 1) {
      return number > 0 ?
        () => factorial(number - 1, product * number) :
        product;
    }
    
    const factorialCalculator = trampoline(factorial);
    console.log(factorialCalculator(100));
    

    You can examine the code in below:

  3. This one is about mutator methods in JavaScript arrays. Immutability of variables is an important topic in functional programming.

    var arr = [1, 2, 3, 7, 4];
    // Which of the followings will mutate variables?
    // Find a functional alternative for mutator ones.
    arr.push(5);          => mutator
    arr.shift();          => mutator
    arr.concat(6, 7);     => non-mutator
    arr.map(a => a * a);  => non-mutator
    arr.sort();           => mutator
    

    And these can be alternative solutions for mutator ones.

    var arr = [1, 2, 3, 7, 4];
    // Which of the followings will mutate variables?
    // Find a functional alternative for mutator ones.
    arr.push(5);          => arr.concat(5);
    arr.shift();          => arr.slice(1);
    arr.concat(6, 7);     => non-mutator
    arr.map(a => a * a);  => non-mutator
    arr.sort();           => arr.concat().sort()
    

    You can examine the code in below:

  4. This one is to examine your understanding about Prototypal Inheritance.

    function Person() {}
    
    // 1st definition for 'sayHi' method
    Person.prototype.sayHi = function () {
      console.log('Hi!');
    };
    
    var person = new Person();
    
    // What will be the printed message?
    person.sayHi();
    
    // 2nd definition for 'sayHi' method
    Person.prototype.sayHi = function () {
      console.log('Hello!');
    };
    
    // What will be the printed message?
    person.sayHi();
    
    // What will be returned?
    person.hasOwnProperty('sayHi');
    

    The output will be below:

    Hi!
    Hello!
    false
    

    person object doesn't have own sayHi() method because Person function doesn't have any method. When we instantiate an object with new keyword, it inherits all prototype methods of the function as its __proto__ property. So, in first execution of sayHi() the defined one is logging Hi! so it is executed. But after second definition of sayHi() the newer one will be called. Because, person.sayHi() points to the same function due to prototypal inheritance. Finally, person.hasOwnProperty('sayHi') returns false because this is not a property of person object, it is inherited by prototype chain.

    You can examine the code in below:

My some other articles:



Top comments (2)

Collapse
 
suggy75 profile image
Matt Sugden

Question 1 can be very inefficient, and you'll exceed the call stack size if you enter a big enough number.

The trampoline pattern is a more efficient way to do recursion.

blog.logrocket.com/using-trampolin...

Collapse
 
halilcanozcelik profile image
Halil Can Ozcelik

Great! I am adding it to article. Thanks.