Iterate N Times

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the times() function in JavaScript which iterates over a callback a specified number of times or until it returns false. We will learn how to use this function to execute a function repeatedly, and how to pass arguments to the callback function. By the end of this lab, you will have a solid understanding of how to use the times() function to make your code more efficient and concise.


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-28453{{"`Iterate N Times`"}} javascript/data_types -.-> lab-28453{{"`Iterate N Times`"}} javascript/arith_ops -.-> lab-28453{{"`Iterate N Times`"}} javascript/comp_ops -.-> lab-28453{{"`Iterate N Times`"}} javascript/loops -.-> lab-28453{{"`Iterate N Times`"}} javascript/debugging -.-> lab-28453{{"`Iterate N Times`"}} end

Code Practice: Iterating N Times

To practice coding, open the Terminal/SSH and type node. Once you have done that, use the following function to iterate over a callback n times:

const times = (n, fn, context = undefined) => {
  let i = 0;
  while (fn.call(context, i) !== false && ++i < n) {}
};

To use this function, call times() and pass in the following arguments:

  • n: the number of times you want to iterate over the callback function
  • fn: the callback function you want to iterate over
  • context (optional): the context you want to use for the callback function (if not specified, it will use an undefined object or the global object in non-strict mode)

Here's an example of how to use the times() function:

var output = "";
times(5, (i) => (output += i));
console.log(output); // 01234

This will iterate over the callback function i => (output += i) 5 times and store the output in the output variable. The output will then be logged to the console, which will display 01234.

Summary

Congratulations! You have completed the Iterate N Times lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like