1

I know that variable redeclaration leads us to syntax error and it is illegal but JavaScript has it's own weird concept about redeclaration. please I need guidance about this stuff.

1).I am trying to understand this when we use var variable in JavaScript it can be redeclared. 2).The last assigned value will get updated to var identifier. 3).I went through some resources, i got that v8engine is not redeclaring var it is just assigning the latest value to same var identifier, ok up to know this is perfect. 4).If it so why the same flexibility of redeclaring not given to let and const keywords in JavaScript. 5).What is happening behind this complex stuff please explain me

  • The flexibility is simply deemed not useful. – Bergi May 12 '21 at 03:15
  • Re-declaring a `var` variable is, at best, sloppy and at worst a bug. `let` and `const` aimed to prevent that sloppiness or accidental bugs by preventing the re-declaration. Also, by definition, `const` is `const`. It can't get a new value assigned to it ever so re-declaration for `const` would never ever be an option. – jfriend00 May 12 '21 at 03:30

1 Answers1

1

The ability to re-declare a variable of the same name in the same scope is confusing to someone reading a script who's trying to understand it. If you declare a variable at a certain line in the code, and then later declare it again, it's very likely a typo or accident, since it doesn't make sense - if you want to reassign the variable, just reassign the variable without re-declaring it.

function getName(name) {
  // What did the script-writer mean to do here?
  // Did they forget that there's an argument called name already?
  var name = prompt('What is your name?');
  console.log('hi', name);
}
getName();

Re-declaring in the same scope is technically permitted with var, but that's only because that's how things have always worked since the very beginning; changing it to be illegal now would break backwards compatibility, which is not done.

let and const were intentionally designed to not be re-declarable in order to avoid this sort of confusion. Less confusing code is arguably more important than flexibility. When language rules are too flexible, coding can become a lot harder. (see == for an example...)

Even if it were possible, re-declaring a const variable in particular doesn't make any sense, because a const is, by definition, not reassignable.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320