GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Missing variable declaration — CodeQL query help documentation

Missing variable declaration¶

ID: js/missing-variable-declaration
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - quality
   - reliability
   - correctness
Query suites:
   - javascript-code-quality.qls
   - javascript-security-and-quality.qls

Click to see the query in the CodeQL repository

In JavaScript, if a variable is used in a function but not declared as a local variable, it becomes a global variable by default. This can have unintended consequences: unlike local variables, global variables can be read and modified by all functions. If different functions use the same global variable, they may end up overwriting each others values, leading to subtle and difficult to diagnose bugs.

Recommendation¶

Check whether the variable in question was meant to be local; if so, declare it by means of a var declaration. If the variable is really meant to be global, it is best to document this fact by inserting a global var declaration at the beginning of the source file.

Example¶

In the following example, both f and g use a loop counter variable i. Since neither of them declares i to be a local variable, they end up accessing the same global variable, so every time f invokes g inside the loop, g overwrites f’s value for i.

function f(a) {
	var sum = 0;
	for (i=0; i<a.length; ++i)
		sum += g(a[i]);
	return sum;
}

function g(b) {
	var prod = 1;
	for (i=0; i<b.length; ++i)
		prod *= b[i];
	return prod;
}

The example should be fixed by declaring i to be a local variable in f and g.

References¶

  • D. Crockford, JavaScript: The Good Parts, Appendix A. O’Reilly, 2008.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.