Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix code scanning alert - Missing variable declaration #208

Open
1 task
slowy07 opened this issue May 10, 2023 · 0 comments
Open
1 task

Fix code scanning alert - Missing variable declaration #208

slowy07 opened this issue May 10, 2023 · 0 comments

Comments

@slowy07
Copy link
Member

slowy07 commented May 10, 2023

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.

Recomendation

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.

Tracking issue for:

slowy07@googlebot.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant