Category Archives: Javascript Exercises

Collection of JavaScript exercises for practice. Advanced and basic JavaScript experience for beginners to improve programming skills

Beginner series sum of all the numbers

Given two integers, which can be positive and negative, find the sum of all the numbers between including them too and return it. If both numbers are equal return a or b.

Note! a and b are not ordered!

Expected output is as follows:

Sum of all the numbers solution – the beginner’s way

You can play around with the code in JSFiddle

Sum of all the numbers  solution – the clever way using javascript recursion

You can play around with the code on JSfiddle

 

Find the sum of numbers in an array

This is a very simple question to ask someone to Find the sum of numbers in an array.

The expectation is that the candidate will know how to run a for loop on the array and use a variable to add the numbers and return the total.

Here is straightforward solution to this question.

You can try out this solution on Fiddle

Sum numbers in an array that has element which is an array

Now what makes this question more interesting is lets say the array has nested arrays like this

How would you return the sum of numbers of the array above?

It is not very difficult.

While running the loop on every element we need to check if the “Element of the array is Array”. If yes, than call the same function. Else continue adding the elements in the total, This concept of calling the same function by itself is called “Recursion” in Javascript.

Here is the complete solution:

You can play around with the code on fiddle

This is really tricky. Not everyone can solve this very easily.