Generating Range Values with JavaScript Generators

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to create a rangeGenerator function in JavaScript that generates all values in a given range using a specified step. We will use a while loop and the yield keyword to return each value and increment by the specified step. By the end of this lab, you will have a better understanding of how to create custom generators in JavaScript and their practical applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("JavaScript")) -.-> javascript/BasicConceptsGroup(["Basic Concepts"]) javascript(("JavaScript")) -.-> javascript/ToolsandEnvironmentGroup(["Tools and Environment"]) javascript/BasicConceptsGroup -.-> javascript/variables("Variables") javascript/BasicConceptsGroup -.-> javascript/data_types("Data Types") javascript/BasicConceptsGroup -.-> javascript/arith_ops("Arithmetic Operators") javascript/BasicConceptsGroup -.-> javascript/comp_ops("Comparison Operators") javascript/BasicConceptsGroup -.-> javascript/loops("Loops") javascript/ToolsandEnvironmentGroup -.-> javascript/debugging("Debugging") subgraph Lab Skills javascript/variables -.-> lab-28575{{"Generating Range Values with JavaScript Generators"}} javascript/data_types -.-> lab-28575{{"Generating Range Values with JavaScript Generators"}} javascript/arith_ops -.-> lab-28575{{"Generating Range Values with JavaScript Generators"}} javascript/comp_ops -.-> lab-28575{{"Generating Range Values with JavaScript Generators"}} javascript/loops -.-> lab-28575{{"Generating Range Values with JavaScript Generators"}} javascript/debugging -.-> lab-28575{{"Generating Range Values with JavaScript Generators"}} end

Range Generator

To generate a range of values using a given step, use the following rangeGenerator function. Open the Terminal/SSH and type node to start coding.

  • Use a while loop and yield to return each value, starting from start and ending at end.
  • If you want to use a default step of 1, omit the third argument.
const rangeGenerator = function* (start, end, step = 1) {
  let i = start;
  while (i < end) {
    yield i;
    i += step;
  }
};

Here's an example of how to use the rangeGenerator function:

for (let i of rangeGenerator(6, 10)) console.log(i);
// Logs 6, 7, 8, 9

Summary

Congratulations! You have completed the Range Generator lab. You can practice more labs in LabEx to improve your skills.