Home > Article > Web Front-end > Discussion on the difference between var and no var when defining variables in javascript_Basic knowledge
Let’s look at a piece of code first
function show(){ alert(abc); } var abc="defg"; show();
People who have experience in C or Java programming may say: "This program is dead. The variable is defined after the function that references the variable. The bug will kill you." Run it on the browser What's the result? Works perfectly! Next, let's talk about what's going on - the difference between variables defined with var and without var.
1. No var
To put it simply, it is unsafe to omit var when defining a variable, but it is legal. At this time, no matter where the variable is defined, the interpreter will give the variable a global scope.
2. There is var
Safe and legal. The scope of a defined variable depends on where it is defined. As for what the scope is specifically, please refer to the article "Javascript Scope" in this blog.
In this way, the problem at the beginning can be solved. What is inside the function is the definition of abc, but the value is undefined. At this time, abc has a global scope, and what is outside the function only updates the value of abc.