Test shadow scope

JavaScript pattern

Test shadow scope

This tests the shadows_identifier pattern by finding all cases where a variable is shadowed.


Apply with the Grit CLI
grit apply test_scope_shadow

Function variable definition

BEFORE
function shadowingExample() {
  var x = 20;
  console.log(x);
}
function notShadowingVar() {
  console.log(x);
}
shadowingExample();
AFTER
function shadowingExample() {
  var shadowed = 20;
  console.log(shadowed);
}
function notShadowingVar() {
  console.log(x);
}
shadowingExample();

If statement

BEFORE
if (true) {
  let x = 40;
  console.log(x);
}
console.log(x);
AFTER
if (true) {
  let shadowed = 40;
  console.log(shadowed);
}
console.log(x);

Arrow function

BEFORE
var x = 10;
useCallback((x) => {
  console.log(x); // 20
});
AFTER
var x = 10;
useCallback((shadowed) => {
  console.log(shadowed); // 20
});

Function params

BEFORE
function shadowingExample(x) {
  console.log(x);
}
x = 30;
shadowingExample(20);
AFTER
function shadowingExample(shadowed) {
  console.log(shadowed);
}
x = 30;
shadowingExample(20);

Arrow function params

BEFORE
var x = 10;
useCallback((x) => {
  console.log(x); // 20
});
AFTER
var x = 10;
useCallback((shadowed) => {
  console.log(shadowed); // 20
});

Catch clause

BEFORE
var x = 'global';
try {
  throw new Error();
} catch (x) {
  console.log(x);
}
console.log(x); // "global"
AFTER
var x = 'global';
try {
  throw new Error();
} catch (shadowed) {
  console.log(shadowed);
}
console.log(x); // "global"

For loop clause

BEFORE
var x = 'global';
for (var x = 0; x < 5; x++) {
  console.log(x);
}
console.log(x);
AFTER
var x = 'global';
for (var shadowed = 0; shadowed < 5; shadowed++) {
  console.log(shadowed);
}
console.log(x);

For of clause

BEFORE
var x = 'global';
for (const x of []) {
  console.log(x.baz);
}
// async loop
for await (const x of []) {
  console.log(x.baz);
}
console.log(x);
AFTER
var x = 'global';
for (const shadowed of []) {
  console.log(shadowed.baz);
}
// async loop
for await (const shadowed of []) {
  console.log(shadowed.baz);
}
console.log(x);