JavaScript Interview Questions (Coding based questions)

# Q. Reverse each word in the sentence.
Solution:

const reverseEachWord = (str) => {
    let words = str.split(' ');
    words = words.map(word => word.split('').reverse().join(''));

    return words.join(' ');
}

Q. Write a recursive function for calculating the factorial of a number.
Solution:

const factorial = (num) => {
   if(num === 1) {
       return num * 1;
   }

   return num * factorial(num - 1);
}

Q. Write a function to capitalize the last letter from a sentence.
Solution:

const capitalizeLastLetterFromSentence = (str) => {
    let words = str.split(' ');
    words = words.map(word => {
        const len = word.length -1;
        word = word.slice( 0, word.length -1) + word[word.length -1].toUpperCase();
        return word;
    });
    return words.join(' ');
}

Q. Write a function to remove duplicate characters from a sentence.
Solution:

const removeDuplicates = (str) =>[...new Set(str.split(''))].join('')

Q. Write a function to flatten a given array.
Solution:

const flattenArray = inputArray => {
    const output = [];
    while (inputArray.length) {
        let value = inputArray.shift();
        if (Array.isArray(value)) {
            inputArray = value.concat(inputArray);
        }
        else {
            output.push(value);
        }
    }

    return output;
}

Q. Write a function to return reverse of a string.
Solution:

const reverseStr = (str) => [...str].reverse().join('');

Q. Write a function to calculate the smallest number in given of digits.
e.g. 125 => In 3 digits smallest number is 100
5454 => In 4 digits smallest number is 1000
9 => smallest number is 1.
Solution:

const calculateSmallestNumber = (num) => {
    const length = String(num).match(/\d/g).length;

    return Math.pow(10, length - 1);
}

Q. Write a function to group the elements based on a given key.

Solution:

const groupBy = (input, key) => {
    const output = {};

    input.forEach( item => {
        if(output[item[key]] === undefined) {
            output[item[key]] = [];
        }
        output[item[key]].push(item);
    });

    return output;
}

Q. Write a function to compute the exponent of a number use recursion.

Solution:

const exponent = (a, n) => {
    if (n === 0) {
        return 1;
    }
    else {
        return a * exponent(a, n - 1);
    }
};

Q. Write the output of the below code snippets.
(Outputs not added)
Code:

var x = 21;
var girl = function () {
    console.log(x);
    var x = 20;
};
girl ();

Code:

(function(params) {
    console.log(1);
    setTimeout(() => {
        console.log(2);
    }, 1000);
    setTimeout(() => {
        console.log(3);
    }, 0);
    console.log(4);
})();

Code:

var foo = function bar(){
    return 7;
}

console.log(typeof bar);

Code:

var a = {};
var b = a;

a.v = 1;
b.v = 2;
console.log(a.v)

Code:

q = 1;
(function(){
    q = 2; 
    if(true){
        let q = 3;
    }
    function f1(){
       var q = 4;
    }
    f1();
    console.log('inside: ', q)
})();
console.log('q: ', q)

Code:

(function(){
    var q = 1;
    if(true){
        var q = 3;
    }
    function f1(){
       var q = 2;
    }
    f1();
    console.log('q: ', q)
})();

Code:

q = 1;
(function(){
    q = 2; 
    if(true){
        var q = 3;
    }
    function f1(){
        q = 4;
    }
    f1();
})();
console.log('q: ', q)

Code:

let a = [1, 2, 3];
a.x = 'foo';
let b = '';
for (i of a) {
    b += i;
}
console.log(b); //123

Code:

const x = {
    m: 42,
    f: function(){
        let a = [1, 2, 3];
        let str = "";
        a.forEach(function(){
            str += this.m;
        });
        return str;
    }
}
console.log(x.f());

Code:

for (var i = 0; i < 5; i++) {
    setTimeout(function () { console.log(i); }, i * 1000);
    // prints 5 after 5 times each after a second
}

Code:

var z = 1, y = z = typeof y;
console.log(y); //undefined

console.log(undefined === undefined);
console.log(null === null);
console.log(NaN === NaN);
const x = 2 + 5 + +"3"
console.log(x, typeof x);

Code:

var strA = "hi there";
var strB = strA;
strB = "bye there!";
console.log(strA);
console.log(NaN === NaN);

Code:

function add(num1, num2) {
    return
    num1 + num2;
}

Code:

for (let q = 0; q < 5; q++) {
    setTimeout(() => {
        console.log('Using let and timeout: ', q * 1000);
    }, q * 1000);
    // prints 0, 1000, 2000, 3000, 4000 after every sec
}

Code:

for (let q = 0; q < 5; q++) {
    setTimeout(() => {
        console.log('Using let: ', q);
    }, 1000);
    //prints 0, 1, 2, 3, 4, 5 after 1 sec
}

Code:

for (var q = 0; q < 5; q++) {
    setTimeout(() => {
        console.log('Using var and timeout: ', q * 1000);
    }, q * 1000);
    // prints 5000 after each sec
}

Code:

for (var q = 0; q < 5; q++) {
    setTimeout(() => {
        console.log('Using var: ', q);
    }, 1000);
    //prints 5 after a sec
}

Code:

function Teacher(name, age) {
    this.name = name;
    this.age = age;
}

function Person(name, age) {
    Teacher.call(this, name, age);
    this.name = 'person';
}
const data = new Person('name', 25);
console.log(data);
delete data.name;
console.log(data);

Code:


const obj = {
    x: 'test',
    a: function () {
        const x = 'value';
        console.log('a -- > ', this.x, x);
    },
    b: function hello() {
        function test() {
            const x = 'hello';
            console.log('b -- > ', this.x, x);
        }
        test();
    },
    c: () => {
        const x = 'temp';
        console.log('c -- > ', this.x, x);
    },
    d(){
        const x = 'temp';
        console.log('d -- > ', this.x, x);
    }
}

obj.a();
obj.b();
obj.c();
obj.d();

Code:

class Xyz {
    constructor(){
        this.m = 100
    }
    test1(){
        setTimeout((function () {
            console.log(this.m)
        }).bind(this), 0);
    }
    test2(){
        setTimeout((function () {
            console.log(this.m)
        }), 0);
    }
    test3(){
        setTimeout(function () {
            console.log(this.m)
        }, 0);
    }
    test4(){
        setTimeout(() => {
            console.log(this.m)
        }, 0);
    }
}

new Xyz().test1();
new Xyz().test2();
new Xyz().test3();
new Xyz().test4();

Code:

class Xyz {
    constructor(){
        this.m = 100
    }
    test1(){
        setTimeout((function () {
            console.log(this.m)
        }).bind(this), 0);
    }
    test2(){
        setTimeout((function () {
            console.log(this.m)
        }), 0);
    }
    test3(){
        setTimeout(function () {
            console.log(this.m)
        }, 0);
    }
    test4(){
        setTimeout(() => {
            console.log(this.m)
        }, 0);
    }
}

new Xyz().test1();
new Xyz().test2();
new Xyz().test3();
new Xyz().test4();

Code:

function promised(msg) {
    return new Promise((resolve) => {
        setTimeout(function () {
            resolve(msg);
        }, 3000);
    });
}

const async_fn = async function () {
    const p1 = await promised('first_first');
    console.log(p1);
    const p2 = await promised('seconds_first');
    console.log(p2);
    console.log('done_first');
};

async_fn();

Code:

function promised(msg) {
    return new Promise((resolve) => {
        setTimeout(function () {
            resolve(msg);
        }, 3000);
    });
}
const p1 = promised('first');
p1.then((res) => console.log(res));
const p2 = promised('seconds');
p2.then((res) => console.log(res));
console.log('done');