Home > Web Front-end > JS Tutorial > body text

A brief discussion on the difference between defining variables in JavaScript with or without var declaration_javascript skills

WBOY
Release: 2016-05-16 16:39:12
Original
1002 people have browsed it

Some time ago, I answered a question about the difference between using the keyword var when defining variables or not. Let me summarize it.

1. In the function scope, variables defined with var are local variables, and variables defined without var become global variables.
Use var definition:

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

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'
Copy after login

2. In the global scope, variables defined using var cannot be deleted, and variables defined without var can be deleted. This means that implicit global variables are not strictly speaking real variables, but attributes of the global object. Because attributes can be deleted through delete, but variables cannot.

3. Using var to define a variable will also promote the variable declaration, that is,
Use var definition:

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

Do not use var definition:

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

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

4. In the 'use strict' mode of ES5, if the variable is not defined using var, an error will be reported.

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!