Skip to content

Commit 7916d6f

Browse files
committed
[guide] Add documentation for no-use-before-define rule under hoisting section
1 parent 01f046d commit 7916d6f

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

README.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1961,6 +1961,56 @@ Other Style Guides
19611961
}
19621962
```
19631963
1964+
<a name="no-use-before-define"></a>
1965+
- [14.5](#no-use-before-define) Variables, classes, and functions should be defined before they can be used. eslint: [`no-use-before-define`](https://eslint.org/docs/latest/rules/no-use-before-define)
1966+
1967+
> Why? When variables, classes, or functions are declared before being used, it can harm readability since a reader won't know what a thing that's referenced is. It's much clearer for a reader to first encounter the source of a thing (whether imported from another module, or defined in the file) before encountering a use of the thing.
1968+
1969+
```javascript
1970+
// bad
1971+
1972+
// Variable a is being used before it is being defined.
1973+
console.log(a); // this will be undefined, since while the declaration is hoisted, the initialization is not
1974+
var a = 10;
1975+
1976+
// Function fun is being called before being defined.
1977+
fun();
1978+
function fun() {}
1979+
1980+
// Class A is being used before being defined.
1981+
new A(); // ReferenceError: Cannot access 'A' before initialization
1982+
class A {
1983+
}
1984+
1985+
// `let` and `const` are hoisted, but they don't have a default initialization.
1986+
// The variables 'a' and 'b' are in a Temporal Dead Zone where JavaScript
1987+
// knows they exist (declaration is hoisted) but they are not accessible
1988+
// (as they are not yet initialized).
1989+
1990+
console.log(a); // ReferenceError: Cannot access 'a' before initialization
1991+
console.log(b); // ReferenceError: Cannot access 'b' before initialization
1992+
let a = 10;
1993+
const b = 5;
1994+
1995+
1996+
// good
1997+
1998+
var a = 10;
1999+
console.log(a); // 10
2000+
2001+
function fun() {}
2002+
fun();
2003+
2004+
class A {
2005+
}
2006+
new A();
2007+
2008+
let a = 10;
2009+
const b = 5;
2010+
console.log(a); // 10
2011+
console.log(b); // 5
2012+
```
2013+
19642014
- For more information refer to [JavaScript Scoping & Hoisting](https://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting/) by [Ben Cherry](https://www.adequatelygood.com/).
19652015
19662016
**[⬆ back to top](#table-of-contents)**

0 commit comments

Comments
 (0)