Asperger Asperger - 3 months ago 6
Javascript Question

Using var and let variables of the same name?

Ever since let came out it allowed me to follow stricter naming conventions.However, lets consider the below scenario, would it be valid or is it hacky to do something like this? I am very well aware that the first has function scope and the other block scope.

var sample = 'sample';

function fooBar() {
let sample = 'This is a sample';

console.log(sample);
}

fooBar();

console.log(sample)

Answer

What you are trying to do here is perfectly valid and is called shadowing. As the name suggests - You have shadowed the global scoped variable sample with the function scoped variable sample. And by doing that you have restricted yourself to access the global variable without using some special tricks. You can still access global variable of the same name inside the function as given below

var sample = 'sample';
function fooBar() {
  var sample = 'This is a sample';
  console.log(sample); // 'This is a sample'
  console.log(window.sample); //Sample
  //console.log(this.sample);//Sample. Works only in non strict mode
}
fooBar();
console.log(sample); // 'sample'

Moreover, if someone says never use var then that little too hard a statement to make. var still has its use. You can have a look at this article by Kyle Simpson here

https://davidwalsh.name/for-and-against-let

Hope this be of some help.

Happy Learning :) Vatsal