Get Set Kode
Get Set Kode

Reputation: 101

create a custom loop in Javascript

Making an attempt to teach coding to kids. I am trying to create a layer of abstraction over javascript just to simplify the syntax for the kids.

I think it will be a bit overwhelming for a kid to learn a typical while loop

Is there any way to convert

var i = 0 
while(i<10)
{ 
doThis(); 
doThat() 
i++
}

into something easier like this

repeat(10)
{
doThis();
doThat();
}

Thanks

Upvotes: 1

Views: 888

Answers (1)

Jacky Lam
Jacky Lam

Reputation: 77

I am not sure if it's possible to do exactly what you want, even hacking.

However, if you want to simplify it for your students, you go about with something like this?

/* you can hide this function by having it imported from external JS file */
var repeat = function(num, func){
   var i = 0;
   while(i < num){ 
      func();
      i++;
   }
};

var command = function(){
   doThis(); 
   doThat();
};

repeat(10, command);

if you're working with modern javascript

const repeat = (num, func) => {
   let i = 0;
   while(i < num){ 
      func();
      i++;
   }
};

const command = () => {
   doThis(); 
   doThat();
};

repeat(10, command);

Upvotes: 2

Related Questions