0

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?

4
  • 1
    The language is fixed and standardized, and you can't add new keywords or constructs, or change the syntax. Commented Aug 11, 2014 at 11:10
  • 1
    Why do you want to create your own loop? What is it about JS's standard loops that aren't good enough. Answering this question might go some way to help solve your problem. Commented Aug 11, 2014 at 11:12
  • I've removed the c tag. This question is about JavaScript, not C. (The C example in the question is useful to understanding what you want, though.) Commented Aug 11, 2014 at 11:18
  • 2
    Also, doing it just to localize keywords is not such a great idea either. Just look at e.g. Excel, with its localized VBA keywords and function names. Try sharing that with anyone who doesn't have your language will make the whole file unusable, as well as cause confusion for anyone trying to read your code who's not fluent in your language. Commented Aug 11, 2014 at 11:18

1 Answer 1

2

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
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.