what is the purpose of tslint no-var-keyword - "forbidden 'var' keyword"?
Asked Answered
B

2

5

What is the purpose of tslint no-var-keyword ("forbidden 'var' keyword")? tslint appears to log an error for every occurence of the var keyword in my code. Is tslint stating that the var keyword should unconditionally be excluded in ng2? If so then why?

Beuthen answered 12/10, 2017 at 0:0 Comment(3)
github.com/Microsoft/tslint-microsoft-contrib/issues/78Yes
Possible duplicate of TSLint: Unused var keywordParthenope
You might be a victim of hoisting bugs with var if you don't know what you are doing :-)Moulden
J
10

The rule and its rationale are documented here https://palantir.github.io/tslint/rules/no-var-keyword/

Declaring variables using var has several edge case behaviors that make var unsuitable for modern code. Variables declared by var have their parent function block as their scope, ignoring other control flow statements. vars have declaration “hoisting” (similar to functions) and can appear to be used before declaration.

Variables declared by const and let instead have as their scope the block in which they are defined, and are not allowed to used before declaration or be re-declared with another const or let.

In response to your second question, this has nothing to do with Angular, ng2 or any other version. It's a Typescript issue.And yes, they're trying to get you to abandon var altogether, in favour of let and const.

The difference between let and var is scope. You have to put declarations before use, and you can redeclare in a nested scope. In TS you could also take the opportunity to declare a different type, although I wouldn't endorse this as a programming style.

Jodiejodo answered 14/5, 2019 at 3:47 Comment(0)
C
-2

'var' has been deprecated in favor of 'let'.

The former creates a global variable, which is generally considered bad practice, while the latter creates a scoped variable.

So, lint is, by default, enforcing the use of scoped variables.

Calabash answered 12/10, 2017 at 0:5 Comment(2)
Not exactly, var creates a function-scoped variable (which is unusual compared to many other programming languages with block-scoped variables, hence the introduction of let with a possibly more familiar visibility).Orle
Yes, you are correct - var is not global, but function scoped. See also "variable hoisting"Calabash

© 2022 - 2024 — McMap. All rights reserved.