Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Another method of writing code

I write code to JavaScript. I need to handle multiple keys when pressed. The result of such a code.

var key = event.keyCode;
if (key === 39 {
      //some code
    }

if (key === 40) {
      //some code
    }

if (key === 38) {
      //some code
    }

if (key === 13) {
     //some code
}

I do not like this method, if there is another beautiful way? in the style of object-oriented programming? Thanks

like image 515
Nikitc Avatar asked Feb 03 '26 00:02

Nikitc


1 Answers

JavaScript is not an object oriented language per se.

What you could do is make a mapped object.

const obj = {
    "39" : () => { //do this },
    "40" : () => { //do this },
    "38" : () => { //do this },
    "13" : () => { //do this }
}

Then, when your event code comes in... use const whatever = obj[event.keyCode]();

I also believe that some form of destructuring can make this even fancier, but I'd have to brush up on it.

like image 54
Sterling Archer Avatar answered Feb 05 '26 13:02

Sterling Archer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!