As found in the MDN docs
You can declare a variable in three ways:
With the keyword var. For example, var x = 42. This syntax can be used to declare both local and global variables.
By simply assigning it a value. For example, x = 42. If this form is used outside of a function, it declares a global variable. It generates a strict JavaScript warning. You shouldn't use this variant.
With the keyword let. For example, let y = 13. This syntax can be used to declare a block-scope local variable. See Variable scope below.
Your function will work, because it satisfies method #2, declaring a variable by assigning it a value.
The console.log(myvar)
will not work as myvar
was never declared through any of the 3 means mentioned above. As such, you get a ReferenceError
.
According to my understanding, javascript goes line by line, examines
the variables and their scope. Keeping that in mind shouldn't the
following print 'undefined', as myvar exists in global scope?
No, the function was not called, and as such the code inside it was not run, and so the variable was never created. If you had myvar = 'local variable';
outside of the function, it will work.