Asperger
Asperger

Reputation: 3222

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)

Upvotes: 1

Views: 1828

Answers (2)

Vatsal
Vatsal

Reputation: 2128

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

Upvotes: 1

Oriol
Oriol

Reputation: 288010

It's valid.

And since one declaration is outside the function and the other is inside, you could even declare both with var:

var sample = 'sample';
function fooBar() {
  var sample = 'This is a sample';
  console.log(sample); // 'This is a sample'
}
fooBar();
console.log(sample); // 'sample'

Upvotes: 1

Related Questions