Differences between var and var when defining variables in javascript _ basic knowledge-js tutorial

Source: Internet
Author: User
It is not safe to omit var when defining variables, but it is legal. The scope of the defined variable depends on the location of the definition. 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, and the variable is defined after the function that references this variable. The bug will destroy you ." Run it on the browser. What is the result? Perfect run! Next, let's take a look at what's going on. There is a difference between var and variables without var definitions.

1. No var

In short, it is not safe to omit var when defining a variable, but it is legal. At this time, no matter where the variable is defined, the interpreter will assign the variable a global scope.

2. var

Safe and valid. The scope of the defined variable depends on the location of the definition. For details about the scope, see the article "javascript scope" in this blog.

In this way, the problem at the beginning can be solved. In the function, abc is defined, but the value is undefined. At this time, abc has a global scope. Outside the function, only the value of abc is updated.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.