Problems with declaring a global variable without the var keyword

Variables which are declared without the var keyword are automatically created in the global scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var .

Hope you can provide me with some examples about the two cases mentioned in the freecodecamp paragraph where problems show up without the var keyword.

Challenge: Global Scope and Functions

Link to the challenge:

You want as few properties to the global object as possible. Sometimes you do have to expose values globally, like libraries often does (e.g. window.jQuery).

Adding properties to the global object unintentionally is never good. What errors and bugs it might cause is situational.

window.JSON
// JSON {Symbol(Symbol.toStringTag): 'JSON', parse: ƒ, stringify: ƒ}

JSON.stringify({name: 'John'})
// '{"name":"John"}'

JSON = 'Some value'
JSON // 'Some value'

JSON.stringify({name: 'John'})
// Uncaught TypeError: JSON.stringify is not a function

In general, I think you should keep variable scopes as close to their usage as possible.

Whenever you can, simply pass values around using parameters and arguments until you need to store the final value. Functions taking and returning values transforming the values along the way is much less error-prone than having top-level variables that keep changing after each function call.

What do you mean by the global object?
also, I have another question on global vs local. Can I change the value of the global variable when calling a certain function with a local variable of the same name?

When you run JS code in the browser, the browser provides a global object named window. You can look at this object yourself. Open up the dev tools, go to the Console tab and type window at the prompt. If you do this while you are looking at FCC then you’ll see all the various packages/libraries FCC uses (such as jQuery). You can test this for yourself, type the following statements at the console prompt:

test1 = true;
let test2 = true;

Then type window again and look to see which one is in the global window object.

Yes, you can always refer to the global variable using the window object. If the global variable is named test and you have a local variable named test then you can access the global one with window.test.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.