10 JS Interview Prep Coding Problems with solution
Q1. Write a function called sumRange
. It will take a number and return the sum of all numbers from 1 up to the number passed in.
output expected - sumRange(3) returns 6 = 1+2+3
Q2. Write a function called power
which takes in a base and an exponent. If the exponent is 0, return 1.
output expected -
console.log(power(2, 2)); // 4 console.log(power(2, 1)); // 2 console.log(power(2, 0)); // 1
Q3. Write a function that returns the factorial
of a number. As a quick refresher, a factorial of a number is the result of that number multiplied by the number before it, and the number before that number, and so on, until you reach 1. The factorial of 1 is just 1.
output expected -
factorial(5); // 5 * 4 * 3 * 2 * 1 === 120
Q4. Write a function called all
which accepts an array and a callback and returns true if every value in the array returns true when passed as parameter to the callback function
output expected -
output expected -
var six = productOfArray([1,2,3]) // 6 var sixty = productOfArray([1,2,3,10]) // 60
Q6. Write a function called contains
that searches for a value in a nested object. It returns true if the object contains that value.
output expected -
var nestedObject = { data: { info: { stuff: { thing: { moreStuff: { magicNumber: 44, something: 'foo2' } } } } } }
let hasIt = contains(nestedObject, 44); // true let doesntHaveIt = contains(nestedObject, "foo"); // false
Q7. Given a multi-dimensional integer array, return the total number of integers stored inside this array
output expected -
var seven = totalIntegers([[[5], 3], 0, 2, ['foo'], [], [4, [5, 6]]]); // 7
Q8. Write a function that sums squares of numbers in list that may contain more lists
output expected -
var l = [1,2,3]; console.log(SumSquares(l)); // 1 + 4 + 9 = 14 l = [[1,2],3]; console.log(SumSquares(l)); // 1 + 4 + 9 = 14 l = [[[[[[[[[1]]]]]]]]] console.log(SumSquares(l)); // 1 = 1 l = [10,[[10],10],[10]] console.log(SumSquares(l)); // 100 + 100 + 100 + 100 = 400
Q9. The function should return an array containing repetitions of the number argument. For instance, replicate(3, 5) should return [5,5,5]. If the times argument is negative, return an empty array.
output expected -
console.log(replicate(3, 5)) // [5, 5, 5] console.log(replicate(1, 69)) // [69] console.log(replicate(-2, 6)) // []
Q10. find the largest value inside an object with objects
output expected -
const myObject = {
obj1: {value: 254},
obj2: {value: 21},
obj3: {value: 525},
obj4: {value: 10}
};
console.log(maxValue); //525
NOTE: Here's one way to tackle the aforementioned javascript coding problems. To get the intended result, there are multiple approaches.
Comments
Post a Comment