2

In the chrome console, when I declare variables with let or const these DO NOT become the property of window object. However, the variable declared with var DO becomes the direct property of the window object in the chrome console. For e.g:

let sayHi = 'Hi'
const greet = 'Good Morning'
var sayHola = 'Hola Hola'

window.hasOwnProperty('sayHi') //false
window.hasOwnProperty('greet') //false
window.hasOwnProperty('sayHola') //true

Then what are the actual scopes/object of a variable declared with let or const in the chrome console?

Michael M.
  • 10,486
  • 9
  • 18
  • 34
dkjain
  • 831
  • 1
  • 9
  • 36

1 Answers1

3

All variables (whether declared with var, const, or let) declared in the console are global by default, but being a property of the window object is not the same as having global scope.

This actually isn't just something that happens in the console, variables defined with let and const never are set as properties to window. See this snippet:

let sayHi = 'Hi';
const greet = 'Good Morning';
var sayHola = 'Hola Hola';

console.log(window.hasOwnProperty('sayHi')); // => false
console.log(window.hasOwnProperty('greet')); // => false
console.log(window.hasOwnProperty('sayHola')); // => true

This behavior is intentional and is set out by the standard. It allows for better isolation of variables to specific scopes and no meddling from outside that scope.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • I am more interested in knowing what are the actual scopes/object of a variable declared with let or const in the chrome console? – dkjain Dec 21 '22 at 21:21
  • @dkjain Variables declared in the console have a global scope by default unless you define them inside of a block. I've updated my answer to reflect that. – Michael M. Dec 21 '22 at 21:36