2

Say I have the following construct appearing frequently in my code,

if (e.which==13){ ... }

...and I would like to make the code look a bit cleaner by writing instead:

ifEnterPressed{ ... }

Is there a way of defining an operator such as ifEnterPressed in Javascript?

Update

I have figured out that the basic issue is that Javascript does not support syntactic macros.

0

3 Answers 3

3

No you can't define a custom operator like that.

You can of course write a helper method though:

function enterPressed(e) {
    return e.which==13;
}

And then:

if(enterPressed(e)) {
    // yay!
}
Sign up to request clarification or add additional context in comments.

Comments

2

No, you can't do that in Javascript, but you can use a function:

function isEnter (e) {
  return e.which === 13;
}

Then

if (isEnter(e)) {
  // do something!
}

Comments

1

Beside the solution with a function, you can use an object for grouping and keeping the keycodes, like

KEY = {
    enter: 13
}

Usage:

if (e.which === KEY.enter){ ... }

Comments

Your Answer

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