Home > Web Front-end > JS Tutorial > Discussion on the difference between var and no var when defining variables in javascript_Basic knowledge

Discussion on the difference between var and no var when defining variables in javascript_Basic knowledge

WBOY
Release: 2016-05-16 16:41:32
Original
1300 people have browsed it

Let’s look at a piece of code first

function show(){ 
alert(abc); 
} 
var abc="defg"; 
show();
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template