0

I'm refreshing my JS knowledge by doing a JS course. There's something about variables that have left me a little confused.

var variableVar = 'This is a variable pre ES6'; // var
let variableLet = 'This is a variable that can be changed'; // let
const variableConst = 'This variable cannot be changed'; // con
alsoWorks = 'This also works'; // What's this?

console.log(variableVar);
console.log(variableLet);
console.log(variableConst);
console.log(alsoWorks);

I understand var, const and let. I also noticed I don't need to declare any of these for a variable to work e.g. alsoWorks = 'This also works';. Why shouldn't I write a variable like this?

Sam
  • 1,401
  • 3
  • 26
  • 53
  • 3
    Because it's declaring it in the global scope. Possible dupes of [What is the purpose of the var keyword and when should I use it (or omit it)?](https://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-should-i-use-it-or-omit-it) and [Is using 'var' to declare variables optional?](https://stackoverflow.com/questions/2485423/is-using-var-to-declare-variables-optional). – Tyler Roper Sep 24 '19 at 15:20
  • Open the console and add `alsoWorks = 'This also works';`, then notice that window.alsoWorks was set. In the context of the browser, the window object is the global scope, and you just modified it. – Josh Sep 24 '19 at 15:22
  • 2
    You can get rid of this and some other oddities of javascript by putting "use strict"; at the top your script or function. – georg Sep 24 '19 at 15:23
  • Thank you, I'll explore the duplicate questions. – Sam Sep 24 '19 at 15:23

0 Answers0