Differences between variable definition without var declaration in JavaScript _ javascript skills

Source: Internet
Author: User
This article mainly introduces the differences and examples of non-var declarations when defining variables in JavaScript, for more information about the differences between using the keyword var when defining variables, let's take a closer look.

1. the variables defined by var in the function scope are local variables, and those defined by var are global variables.
Use var to define:

var a = 'hello World';function bb(){ var a = 'hello Bill'; console.log(a);  }bb()      //'hello Bill'console.log(a);  //'hello world'

Do not use var definition:

var a = 'hello World';function bb(){ a = 'hello Bill'; console.log(a);  }bb()      //'hello Bill'console.log(a);  //'hello Bill'

2. in the global scope, the variables defined by var cannot be deleted, and the variables without var can be deleted. it means that the implicit global variable is not a real variable, but a global object attribute, because the attribute can be deleted through delete, but the variable cannot.

3. Using var to define a variable also promotes the variable Declaration, that is
Use var to define:

function hh(){ console.log(a); var a = 'hello world';}hh()      //undefined

Do not use var definition:

function hh(){ console.log(a); a = 'hello world';}hh()      //'a is not defined'

This is the declaration of variables defined using var in advance.

4. In ES5's 'use strict 'mode, if the variable is not defined using var, an error is returned.

Related Article

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.