As far as I know variables declared inside a function are local variables (using var
keyword or not).
If so then why does this output 5
? Shouldn't I get a ReferenceError
when calling func2
because x
is only known to func1
?
<script>
function func1(){
x = 5;
}
function func2(){
document.write(x);
}
func1();
func2();
</script>
As far as I know variables declared inside a function are local variables (using var
keyword or not).
If so then why does this output 5
? Shouldn't I get a ReferenceError
when calling func2
because x
is only known to func1
?
<script>
function func1(){
x = 5;
}
function func2(){
document.write(x);
}
func1();
func2();
</script>
Share
Improve this question
edited Jan 18, 2017 at 19:52
JosephGarrone
4,1613 gold badges41 silver badges61 bronze badges
asked Jan 18, 2017 at 19:37
OnTheFenceOnTheFence
1094 silver badges9 bronze badges
3
-
1
"variables declared inside a function", which you didnt do as you did not use
let
orvar
– Patrick Evans Commented Jan 18, 2017 at 19:39 -
Variables are local when declared with
val
. Otherwise they're global. – Iván Nokonoko Commented Jan 18, 2017 at 19:40 - Read up on JavaScript Scope. – Dust_In_The_Wind Commented Jan 18, 2017 at 19:42
4 Answers
Reset to default 2Afaik, variables declared inside a function are local variables (using var keyword or not).
Variables declared inside a function are local, but you are not declaring any variables. What you have is what's known as an "implicit global" and it only works in "sloppy mode".
From MDN:
Assigning a value to an undeclared variable implicitly creates it as a global variable (it bees a property of the global object) when the assignment is executed.
In strict mode, your code produces an error:
"use strict";
function func1() {
x = 5;
}
function func2() {
document.write(x);
}
func1();
func2();
It is because you did not define it as
function func1(){
var x = 5;
}
This means that JS will use the global variable x
which does not exist, but will when you run func1.
The addition of the "var" defines the variable within the local scope of func1
.
function func1(){
x = 5;
}
is equivalent to
var x; // In global scope
function func1(){
x = 5;
}
As the variable was not scoped to func1
with a declaration.
If this was the case, then you would e across an error in the console since you are trying to access a variable that is not defined yet.
function func1(){
var x = 5;
}
"use strict";
function func1() {
window.x = 5;
}
function func2() {
document.write(x);
}
func1();
func2();