0

I am quite new to JS, Pardon me if this is not a valid question.

What will be scope/type (var/let) of variable if I don't define it as var or let?

Say,

function f1(){
 a="Sample"
 console.log("F1",a);
}

function f2(){
 console.log("F2",a);
}
f2();

It Outputs: F2 Sample

I understand function and block level scope of let and var but here how a is printing, thats confusing.

Aishwarya
  • 987
  • 3
  • 10
  • 26

1 Answers1

0

It will attach itself to the global object, and will become a global variable.

function f1(){
    a="Sample"
}
console.log(a) // Uncaught ReferenceError because there is no a variable in global scope till now.
f1()
console.log(a) // "Sample"

Edit: After suggestion by @Quentin

Below statement will just declare testVar in global scope if used without 'use-strict'

testVar = 17 

but below will throw ReferenceError

'use-strict'
testVar = 17

Conclusion: Strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work" . Assignments, which would accidentally create global variables, instead throw an error in strict mode

Ashish
  • 4,206
  • 16
  • 45
  • Maybe. It might also throw an exception. – Quentin Aug 09 '19 at 10:44
  • Exception is thrown when you try to access a vaiable which is not yet defined. So after function execution since `a` was not defined inside function scope it is hoisted to the global object – Ashish Aug 09 '19 at 10:48
  • You should read up on strict mode. Attempting to implicitly declare a global will throw an exception when it is enabled (which it should be as it catches all sort of bad practices that can lead to logic errors) – Quentin Aug 09 '19 at 10:50
  • In 'strict-mode' you will get the error, but it was not there in the question. – Ashish Aug 09 '19 at 10:52
  • So? A complete answer would still mention it. – Quentin Aug 09 '19 at 10:54