justanotherprogrammer
justanotherprogrammer

Reputation: 21

How to define a loop in javascript

I want to define my own loop in javascript. Already existing loops are:- for and while. I have tried using define(during,while); but that didn't work. For example, it might be easier for someone who speaks spanish to use mientras instead of while. In C, I know you can write
#define mientras while, but I can't find a way to do this in JavaScript.

do {
  //code goes here
} mientras (/*condition*/);

and it would work. I also tried

var during = while;

I also tried

function during(e) {
  while(e){

  }
}

Is this even possible?

Upvotes: 0

Views: 114

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074158

You can't create new keywords or statements in JavaScript, and JavaScript doesn't have a standard preprocessor, so you can't use things like C's #define.

A couple of options:

  1. Create a preprocessor that converts mientras to while, but debugging will require understanding the standard names. There are lots of projects out there that let you create parsers these days in various languages (including PEG.js for JavaScript, if you wanted to create a Node app to do it or similar).

  2. Create a function that does much the same thing, for instance:

    function mientras(test, body) {
        while (test()) {
            body();
        }
    }
    

    It'd be a bit clunky to use:

    var i = 10;
    mientras(
        function() {
            return --i >= 0;
        },
        function() {
            console.log(i);
        }
    );
    

    As of ES6 (the next version of JavaScript), it'll be a bit less clunky with the new arrow syntax:

    var i = 10;
    mientras(() => --i >= 0, () => { console.log(i);} );
    //       ^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^
    //       test function   body function
    

Upvotes: 2

Related Questions