Home > Enterprise >  Anyway to shorten code inside if statement JavaScript
Anyway to shorten code inside if statement JavaScript

Time:11-02

Is there a way to shorten the code inside the if statement in JavaScript I'm thinking for loop but I don't know how and if it's even possible. I already put the what I think the relevant code

var operators = document.querySelectorAll(".operators button");
var string = screenInput.innerHTML
var lastCharacter = string[string.length - 1]
console.log(lastCharacter)

if (lastCharacter === " ") {
  document.getElementById("subtract-operator").disabled = true
  document.getElementById("multiply-operator").disabled = true
  document.getElementById("divide-operator").disabled = true
}
<div >
  <button id="add-operator"> </button>
  <button id="subtract-operator">-</button>
  <button id="multiply-operator">*</button>
  <button id="divide-operator">/</button>
</div>

CodePudding user response:

I agree with Rory on the loop, but it looks as though the code was meant to disable the buttons not used in the current operation. So if the button is pressed, the other buttons are disabled and the button is left enabled.

If this is the case, you can assign the disabled property based on the condition. And if you are looping through the buttons, you can just grab the innerText property to compare against your lastCharacter variable.

let lastCharacter = screenInput.innerHTML.substr(-1)
document.querySelectorAll(".operators button").forEach(b => {
  b.disabled = (b.innerText !== lastCharacter)
})

CodePudding user response:

we can do the inverse logic like this:
"select all except this one."

maybe using a CSS solution :not() will be useful https://developer.mozilla.org/en-US/docs/Web/CSS/:not

to not repeat always the same button ids, but just the ones you don't want to use.

document.querySelectorAll(".operators button")
      .querySelectorAll(":not(#add-operator)") // filtering the ids: ❌ #add-operator, ✅ #subtract-operator, ✅ #multiply-operator, ✅ #divide-operator
      .forEach((elem) => elem.disabled = true);
  • Related