-1

Context: I'm creating a tbody table from a data file, and I'd like to apply a format to certain columns. It works just fine if I leave out the conditional in which I check the column number. In order to rule out other problems in that part of my code, I've stripped it way down. What I still can't figure out is why the always-true if statement just doesn't fire.

Stripping out the superfluous stuff, this code works:

Object.values(dataRow).forEach((val) => {
      let cell = row.append('td');
      cell.text(val);
    }

But this doesn't:

Object.values(dataRow).forEach((val) => {
      if (true) {
        let cell = row.append('td');
      }
      cell.text(val);
    }

To clarify, as long as I don't have the if statement in there, my td cell is populated as I expect it to be. But with the conditional included, nothing happens.

What am I missing? JavaScript isn't my first language, so maybe I'm missing something truly basic?

  • 1
    Because `let` is defined in the block. The error message in your console should clearly tell you an error. – epascarello Nov 28 '21 at 16:10
  • you have just declared a variable within the if scope, put `cell.text(val)` within the if statement, because the cell value is undefined – David Salomon Nov 28 '21 at 16:11
  • 1
    I don't see how `row.append('td')` will actually work. The string `"td"` will not create a `` element – charlietfl Nov 28 '21 at 16:14
  • more to the point is what are you trying to achieve by appending a string 'td'? Also, even if this did create a `td` element `append()` wouldn't return it to assign to `cell` – pilchard Nov 28 '21 at 16:15
  • @epascarello a better duplicate would be [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) (let/var is not the particular scope issue at play) – pilchard Nov 28 '21 at 16:19
  • @pilchard You should be able to add additional duplicates no? I'm not sure what rep is required for that. If you see an Edit link in the duplicate box then you likely have the privilege – charlietfl Nov 28 '21 at 16:45
  • Scope! Including the assignment within the if block solved my mystery. Thank you! – Fritz Knack Nov 28 '21 at 16:48

1 Answers1

-1

Should be the same in most languages, but there is something called scope.

If you declare a block-scoped variable within a conditional statement, its value will not be defined outside of it.

For example:

if (true) {
  let a = 9;
  a // 9
}
a // ReferenceError: a is not defined
let a;
a // undefined
if (true) {
  a = 9;
  a // 9
}
a // 9
skara9
  • 4,042
  • 1
  • 6
  • 21
  • If you believe this is purely a scope question then link to the 12 year old *extremely* complete duplicate [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – pilchard Nov 28 '21 at 16:17