user2875404
user2875404

Reputation: 3218

JavaScript: if let / if-scoped let

I cannot seem to find anything similar to if let from other programming languages in JavaScript.

If I want to get the logo text of Stack Overflow I need to do

let text = document.querySelector('[class="-img _glyph"]')
if(text) {
    result = text.innerText
    //do some other work
}

So after declaring, I have to check for it to not be undefined first before using it. Now what would be much more logical is the following:

if let text = document.querySelector('[class="-img _glyph"]') {
    result = text.innerText
    //do some other work
}

which however doesn't work in JavaScript. Is there another syntax that I can use to avoid having to use the extra line just for the undefined-check?

I found this 10 year old thread https://esdiscuss.org/topic/if-scoped-let but since there were no further responses, I don't know if there is already anything that solves this.

Upvotes: 1

Views: 291

Answers (2)

James
James

Reputation: 22247

You can't declare a variable within the if, but you can do an assignment and check that it's not undefined pretty easily:

let text, result;
if (text = document.querySelector('[class="-img _glyph"]')) {
  result = text.innerText
  //do some other work
} else {
  result = "not found";
}

Upvotes: 0

Carsten Massmann
Carsten Massmann

Reputation: 28196

Well, then the answer could be to use a for loop:

for (let text = document.querySelector('[class="-img _glyph"]'); text; text = false) {
  result = text.innerText;
  console.log(result);
}
console.log("done");

Alternatively - and more in line with a maintainable code - you could do

{
  let text = document.querySelector('[class="-img _glyph"]');
  if (text) {
    result = text.innerText;
    console.log(result);
  }
  console.log("text:", text);
}
console.log(text) // will throw an error!

Upvotes: 1

Related Questions