Basic JavaScript - Global vs. Local Scope in Functions

Hi everyone!

I have coded the piece below in the console of my web browser and wonder why the following results will be shown. Thanks for your help!

var someVar = "hat";

function Func() {
    const someVar = "gloves";
    return someVar;
   

};

Func();

console.log(someVar);

/* the result is "Uncaught SyntaxError: Identifier 'someVar' has already been declared
    at <anonymous>:1:1" */
const someVar = "hat";

function func() {
    
    const someVar = "gloves";
    return someVar;
};

func();

console.log(someVar);

/* the output is  hat */

It took me a little bit to understand the unexpected outcome of this code. The reason why you are getting this error is not about scopes. Because you run the code in browser console, two of the code pieces runs like they are written on the same file.

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