Home Web Front-end JS Tutorial Example of the difference between variable declaration with var and without var in JavaScript_javascript skills

Example of the difference between variable declaration with var and without var in JavaScript_javascript skills

May 16, 2016 pm 04:36 PM
var variable declaration

This article discusses the difference between variable declarations in JavaScript with var and without var. The scope of variable declarations in JS is based on functions, so we often see the method to avoid global variable pollution is

(function(){ 
// ... 
})();
Copy after login

Within a function, variables declared with var and without var are different. Those declared with var are local variables, and those without var are declared global variables, so you can use this to expose interface stuff to the outside world.
When declaring a variable in the global scope, it looks the same with or without var. We know that the declared global variable is the attribute of window. Whether it is the same or not, we use the attribute query method provided by ECMAScrpit5 to find out. difference.

var fff = 2; 
window.ffa = 3; 
ffb = 4; 
this.ffc = 4; 
var ffftx = Object.getOwnPropertyDescriptor(window, 'fff'); //configurable:false,enumerable:true,value:2,writable:true 
var ffatx = Object.getOwnPropertyDescriptor(window, 'ffa'); //configurable:true,enumerable:true,value:2,writable:true 
var ffbtx = Object.getOwnPropertyDescriptor(window, 'ffb'); //configurable:true,enumerable:true,value:2,writable:true 
var ffctx = Object.getOwnPropertyDescriptor(window, 'ffc'); //configurable:true,enumerable:true,value:2,writable:true
Copy after login

Through the above, we found that there is still a difference. Let's use delete to delete the attribute to verify that the attribute with configurability of false cannot be deleted. That is to say, the attributes of the global object declared through the variable var cannot be deleted. We will also find that the attributes of the global object created by the function declaration cannot be deleted.

delete fff; // 无法删除 
delete ffa; // 可删除 
delete ffb; // 可删除 
delete ffc; // 可删除
Copy after login

The conclusion is that there is a difference between declaring global variables with var and without var.

It is legal and harmless to use var statements to repeat declaration statements. If the statement is repeated with an assignment, it is no different from a normal assignment statement. If you try to read an undeclared variable, JS will report an error.
Within the function scope of JavaScript, declared variables or internal functions are visible in the function body. Meaning, the function may be available before it is defined. There are two ways to define a function, one is a function definition expression, and the other is a function declaration statement.

// 函数定义表达式 
var fns = function (){ 
// ... 
}; 
// 函数声明语句 
function fns(){ 
// ... 
} 
Copy after login

Function declaration statements are "advanced" to the top of the external script or external function scope, so a function declared in this way can be called by code that appears before it is defined. In function definition expressions, the declaration of variables is advanced, but the assignment to variables is not advanced. Therefore, functions defined in expressions cannot be called before the function is defined.

(function() { 
testa(); // 打印出testa 
testb(); // 报错:提示undefined is not a function 
console.log(testc); //undefined,如果移到上面就可以了 
function testa() { 
console.log("testa"); 
} 
var testb = function() { 
console.log("tesb"); 
} 
var testc = "testc"; 
})();
Copy after login

Of course, when we declare variables and functions, we must comply with basic specifications. Variables and functions must be declared in advance.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solve the 'error: use of undeclared identifier 'variable'' problem in C++ code Solve the 'error: use of undeclared identifier 'variable'' problem in C++ code Aug 26, 2023 pm 01:46 PM

Solving the "error:useofundeclaredidentifier'variable'" problem in C++ code When programming in C++, we often encounter various errors. One of the common errors is "error:useofundeclaredidentifier'variable'". This error usually means that we are using an undeclared variable in our code. This article will detail

Let's talk about the differences between var, let and const (code example) Let's talk about the differences between var, let and const (code example) Jan 06, 2023 pm 04:25 PM

This article brings you relevant knowledge about JavaScript. It mainly introduces the differences between var, let and const, as well as the relationship between ECMAScript and JavaScript. Interested friends can take a look at it. I hope Helpful to everyone.

18 Ways to Fix Audio Service Not Responding Issue on Windows 11 18 Ways to Fix Audio Service Not Responding Issue on Windows 11 Jun 05, 2023 pm 10:23 PM

Audio output and input require specific drivers and services to work as expected on Windows 11. These sometimes end up running into errors in the background, causing audio issues like no audio output, missing audio devices, distorted audio, etc. How to Fix Audio Service Not Responding on Windows 11 We recommend you to start with the fixes mentioned below and work your way through the list until you manage to resolve your issue. The audio service may become unresponsive for a number of reasons on Windows 11. This list will help you verify and fix most issues that prevent audio services from responding on Windows 11. Please follow the relevant sections below to help you through the process. Method 1: Restart the audio service. You may encounter

The role and examples of var keyword in PHP The role and examples of var keyword in PHP Jun 28, 2023 pm 08:58 PM

The role and examples of var keyword in PHP In PHP, the var keyword is used to declare a variable. In previous PHP versions, using the var keyword was the idiomatic way to declare member variables, but its use is no longer recommended. However, in some cases, the var keyword is still used. The var keyword is mainly used to declare a local variable, and the variable will automatically be marked as local scope. This means that the variable is only visible within the current block of code and cannot be accessed in other functions or blocks of code. Use var

How to use variables in PHP How to use variables in PHP May 20, 2023 pm 02:33 PM

PHP is a very popular web development language that allows developers to create dynamic web applications on the server side. In PHP, a variable is a basic data structure used to store values ​​and data. This article will introduce how to use variables in PHP. Basic Syntax of Variables The syntax for declaring variables in PHP is very simple. Variable names begin with a dollar sign ($), followed by the variable name. Variable names can be a combination of letters, numbers, or underscores, but they must begin with a letter or an underscore. For example, the following code declares a name

Solution to the error AttributeError(\'{0!r} object has no attribute {1!r}\'.format(type(self).__name__, k)) Solution to the error AttributeError(\'{0!r} object has no attribute {1!r}\'.format(type(self).__name__, k)) Feb 29, 2024 pm 06:40 PM

The reason for the error message indicates that in the python code, an object (represented by the self variable) is used, but the object does not have an attribute named k. This may be because the object does not have this property defined, or a type error in the code causes the object to not be of the expected type. How to Fix To resolve this error, you may need to do one or more of the following: Check your code for the error and make sure the object referenced by the self variable has a property named k. Check your code for type errors and make sure the object referenced by the self variable is of the expected type. If the attribute is missing, you need to define this attribute in the class and use tryexcept to get this error. If you are sure that k is an attribute that is not defined in the class, please confirm

What does let var const mean? What does let var const mean? Nov 14, 2023 pm 03:00 PM

llet, var, and const represent block scope variables, function scope variables, and constants respectively. Detailed introduction: 1. let, used to declare a variable in a block scope. A variable declared using let cannot be accessed before it is declared. This is the so-called temporary dead zone; 2. var, used to declare the key to a variable. Word, the declared variable is in function scope or global scope and is not restricted by block-level scope; 3. const, used to declare a constant. Once assigned, the variable cannot be reassigned. The value is after declaration. Cannot be modified etc.

How to solve golang error: undeclared name 'x' (cannot refer to unexported name), solution steps How to solve golang error: undeclared name 'x' (cannot refer to unexported name), solution steps Aug 19, 2023 am 11:01 AM

How to solve golang error: undeclaredname'x'(cannotrefertounexportedname), solution steps. During the development process of using Golang, we often encounter various error messages. One of the common errors is "undeclaredname'x'(cannotrefertounexportedname)" which refers to the variable

See all articles