CodeQL documentation

Variable not declared before use

ID: js/use-before-declaration
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - quality
   - maintainability
   - readability
Query suites:
   - javascript-security-and-quality.qls

Click to see the query in the CodeQL repository

JavaScript allows local variables to be used before they are declared. However, this is confusing for readers of the code, since it may not be clear whether the use refers to the local variable or to a global variable of the same name.

Recommendation

Move local variable declarations to the beginning of the enclosing function, or (for global variables) to the beginning of the source file.

Example

In the following example, the local variable x declared in function f shadows the global variable of the same name. However, the first use of the local variable precedes its declaration, so a developer unfamiliar with the code might assume that this use refers to the global variable instead of the local variable.

var x = 23;

function f() {
	x = 42;
	var x;
}

References

  • D. Crockford, JavaScript: The Good Parts, Section 4.9. O’Reilly, 2008.

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy