By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Eloquent JavaScript Exercise -Range and Sum Function
JavaScript

Eloquent JavaScript Exercise -Range and Sum Function

Admin
Last updated: 2023/01/16 at 6:16 AM
Admin
Share
4 Min Read
Range and Sum Function

In this article, we will talk about a JavaScript problem which is Range and Sum Function in JavaScript. This problem is in chapter 4 of Eloquent JavaScript book which very famous for JS of course. So we will understand this problem and also solve the problem with very basic logic.

Contents
Range and Sum Function ProblemRange and Sum Function SolutionRange and Sum Function Solution: AlternativeYou may also like:

Range and Sum Function Problem

The introduction of this book alluded to the following as a nice way to compute the sum of a range of numbers:console.log(sum(range(1, 10)));

Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end.

Next, write a sum function that takes an array of numbers and returns the sum of these numbers. Run the previous program and see whether it does indeed return 55.

Range and Sum Function Solution

Okay, so now let’s make a function range where we will create an array, and we assigned the value of start in the variable named cnt. So here we have used a loop so that we can assign all the values in an array. We used while loop, we can also go with for loop, here loop will run till cnt will be less or equal to end. In this we are just pushing the value of cnt in the array and incremented cnt, lastly we just return this array.

Now let’s create another function named sum to get the addition of the array’s values, here we have passed the array as a parameter in the function. Now we have a variable total with initial 0 value, and again we used while loop till the array’s length in which we are just poping the array and adding in the total variable, and we are returning total. Lastly, we are using console.log with both function calls, here we are passing range(1,10) as an argument in the sum function call. So the range function will be called first, and it will return the array which is going to be used by the sum function.

const range = function(start, end) {
            var arr = [],
                cnt = start;
                
            while(cnt<=end){
                arr.push(cnt);
                cnt++;
            }
            return arr;
        }

        const sum = function(arr){
            var total = 0;
            while(arr.length>0){
                total = total + arr.pop();
            }
            return total;
        }

        console.log(sum(range(1,10)));
Range and Sum Function Solution

Range and Sum Function Solution: Alternative

As we know, JavaScript is flexible, which means we can have multiple ways to solve one problem. So let’s talk about alternative way, here we are eliminating loop completely by using function recursion. In range function, we declared a blank array and start assigned to cnt, now we declared another function named increaseCnt which take cnt as parameter. In this, we will check where cnt is greater than end, then just push end value and return array. Otherwise, push cnt, and we will call this function again with increased cnt value. This thing works similar as loop until the array won’t return.

Now in the sum function, we applied to reduce method on the array and added a callback function with two parameters and we are just adding these both and return them.

const range = function(start, end) {
            var arr = [],
                cnt = start;
                
            function increaseCnt(cnt){
                if(cnt>=end){
                    return arr.push(end);
                }
                else{
                    arr.push(cnt);
                    increaseCnt(++cnt);
                }
            }
            increaseCnt(cnt);
            return arr;
        }

        const sum = function(arr){
            return arr.reduce(function(tot,val){
                return tot + val;
            })
        }

        console.log(sum(range(1,10)));
Range and Sum Function Solution

You may also like:

  • How to Define a Class With Properties and Methods in JavaScript?
  • How to Implement Class Inheritance in JavaScript?
  • How to Find Duplicate Elements in a Given Array?

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

TAGGED: Eloquent JavaScript, Range and Sum Function
Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Posted by Admin
Follow:
Rocoderes is a blog you can learn HTML, CSS, JavaScript, React Js and Python along with creative coding stuff and free source code files.
Previous Article Computing Fibonacci Sequence in JavaScript Computing Fibonacci Sequence in JavaScript
Next Article Extracting Numbers From a String Extracting Numbers From a String in JavaScript
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?