Variables

JavaScript Variables (JavaScript变量)

Variables in javaScript

Variables in javaScript (JavaScript中的变量)

Variable means anything that can be changed anytime. A JavaScript variable is the name of storage location. Variables can be used to store goodies, visitors, and other data. Every programming language use variables. We use variables as symbolic names for values in an application. (变量是指任何可以随时更改的内容。JavaScript变量是存储位置的名称。变量可用于存储商品、访客和其他数据。每种编程语言都使用变量。我们在应用程序中使用变量作为值的符号名称。)

We can create variables using any of these keywords: ‘var’, ‘let’ and ‘const’. Don’t worry if many of these words are new to you. You will understand these terms later.

Local and Global Variables

Local and Global Variables (局部和全局变量)

There are two types of variables in JavaScript that can be represented and manipulated in a programming language: local and global.

A JavaScript local variables are declared inside function or block and accessible only within the function or block. (JavaScript局部变量在函数或块中声明,只能在函数或块中访问。)

function localFunc() {
 var x = 10; //local variable  
 console.log(x); //10  
}
localFunc();

JavaScript global variables are accessible from any function: they can be declared outside the function or with window objects.

var globalVar = "some val"; //global variable           
function globalFunc() {
 console.log(globalVar); //global variable , result  is "some val"
}
globalFunc();

A local variable takes priority over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, it will hide the global variable. For instance:

var variable = "global variable";
function localVar() {
 var variable = "local variable";
 console.log(variable); //local variable
}
console.log(variable); //global variable
localVar();

The output in this function showVariables() shows that both global and local variables are available inside the function as we can console.log them. (此函数showVariables ()中的输出显示,全局和局部变量在函数内都可用,因为我们可以console.log它们。)

var globalVar = "global variable";
function showVariables() {
 console.log(globalVar); //global variable
 var localVar = "local variable";
 console.log(localVar); //local variable
};
showVariables();

JavaScript variable names

JavaScript variable names (JavaScript变量名称)

You need to know about one very important thing when using variables. A variable name must have a clear and obvious meaning, when it describes stored data. Variable naming is one of the important and difficult skills in programming. (使用变量时,您需要了解一件非常重要的事情。在描述存储的数据时,变量名称必须具有清晰而明显的含义。变量命名是编程中重要而困难的技能之一。)

It’s much easier to find information, when the variables have good names, that’s why you should think about the right name for a variable. (查找信息要容易得多,当变量具有良好的名称时,这就是为什么您应该考虑变量的正确名称。)

Here are some good-to-follow rules for you:

  • Name must start with some letter (a to z or A to Z), underscore ( _ ), or dollar ( $ ) sign;

  • JavaScript variable names shouldn’t start with a numeral (0-9). We can use digits (0 to 9) after first letter or underscore character, for example value1 or _1value. (- JavaScript变量名称不应以数字( 0-9 )开头。我们可以在第一个字母或下划线字符后使用数字( 0到9 ) ,例如value1或_1value。)

  • JavaScript variable names are case-sensitive. For instance, Name and name are two different variables. (- JavaScript变量名称区分大小写。例如, Name和name是两个不同的变量。)

  • Use human-readable names like firstName or lastName;

  • Escape abbreviations or short names like a, b, c, unless you really know what you’re doing;

  • Make names maximally descriptive and brief. The examples of bad names: data and value, because they don’t say nothing.

Examples of the correct JavaScript variables:

var x = 7;
console.log(x); // 7  
var value = "w3cdoc";
console.log(value); // w3cdoc

Examples of the incorrect JavaScript variables:

var  123 = 40;  //Unexpected number
var *aa = 250; //Unexpected token '*'

Datatypes in JavaScript

Datatypes in JavaScript (JavaScript中的数据类型)

One of the important characteristics of a programming language is the set of data types it supports. That types can be represented and manipulated in a programming language. There are two main types of languages: statically typed language and dynamically typed language.

In statically typed language each variable and expression type is already known at assemble time. After declaring a variable in a determined data type, it can’t hold values of other data types. The examples of this type: C++, Java.

The other dynamically typed language, which can receive different data types over time. The examples are Ruby, Python, JavaScript etc. (另一种动态类型语言,可以随着时间的推移接收不同的数据类型。例如Ruby、Python、JavaScript等。)

JavaScript is dynamically typed scripting language, it also called loosely typed. So variables in javascript can receive different data types over time. Datatypes are the typed of data which can be used and manipulated in a program.

Types

Types (类型)

The newest ECMAScript(ES6) standard defines 8 data types: 7 of them are Primitive.

  • Numbers: 10, 5.4, etc.

  • String: “Welcome to w3cdoc” etc.

  • Boolean: Represents a logical operation and can have two values: true or false.

  • Symbol: This is for unique identifiers.

  • BigInt: It is for integer numbers of arbitrary length.

  • Null: Has only one value: null.

  • Undefined: A variable which hasn’t been assigned a value.

And one special type:

Object:The most important data-type for modern JavaScript.

We will learn about these data types in details in Data types. (我们将在数据类型中详细了解这些数据类型。)

Variable declaration in JavaScript

Variable declaration in JavaScript (JavaScript中的变量声明)

As we mentioned, there are 3 ways to declare a variable in JavaScript: let, const and var. Let’s explore them all in more detail:

Var

Var (VAR)

Var statement helps us to declare a variable, initializing it to a value. We can reset the values to the variables or redefine the variables as well. If you re-declare a variable, it won’t lose its value. The syntax for this kind of declaration is:

var varName;  //without initializing
var varName = “Welcome to w3cdoc!”; //initialized with a string

You can declare multiple variables in a single line, separating them with commas. (您可以在一行中声明多个变量,并用逗号分隔它们。)

Example of the var declare multiple variables:

var var1 = 20, var2 = “Welcome to w3cdoc”,...;
// single variable
var varName;
//multiple variables
var name, title, num;

Example of the initialization of variables with var:

// initializing variables
var name = "Docs";
name = "w3cdoc";

All the declarations in JavaScript are processed before program execution. So, declaring a variable anywhere is equal to declare it at the top of the code. It gives JavaScript a functionality to use the variables before their declarations in the code. This behavior of variables is called “var hoisting”. (JavaScript中的所有声明都在执行程序之前进行处理。因此,在任何地方声明变量等于在代码的顶部声明它。它为JavaScript提供了在代码中的声明之前使用变量的功能。这种变量的行为称为“var提升”。)

But it is recommended in programming to declare the variables before we use them, as it will help you avoid unintended redeclaration of a variable. (但建议在编程中在使用变量之前声明它们,因为它将帮助您避免意外重新声明变量。)

Let

Let (让)

The let keyword has scope constraints. You can’t redeclare the let declared variables. If you try to do so, you will face a SyntaxError. The scope of these variables is the block they are defined in, it can be also any sub-blocks. In case you try to access these variables outside of their block, the browser will throw a ReferenceError. (Let关键字具有范围约束。您不能重新声明let声明的变量。如果您尝试这样做,您将面临SyntaxError。这些变量的范围是它们定义的块,也可以是任何子块。如果您尝试访问块外的这些变量,浏览器将抛出ReferenceError。)

let varName; //without initializing
let varName = “Welcome to w3cdoc!” // initialized with a string

Example of the initialization of variables with let:

let user = 'Ann';
let age = 25;
let message = 'Welcome to w3cdoc!';

Both var and let can be suitable in any given part of a program, depending on the circumstances. (VAR和LET都可以适用于计划的任何给定部分,具体取决于具体情况。)

Example of the var:

console.log(x); // undefined
var x = 5;
console.log(x); // 5

Example of the let:

console.log(x); //Error
let x = 5;
console.log(x);

Var instead of let

Var instead of let (Var而不是let)

In older scripts you can meet another keyword: var instead of let:

var message = 'Welcome to w3cdoc!';

In this case the var keyword is almost the same as let. It also declares a variable, but in another, old way. (在这种情况下, var关键字几乎与let相同。它还声明了一个变量,但以另一种旧的方式。)

There are fine differences between let and var, but we will talk about them in “var hoisting”. (Let和var之间存在细微差异,但我们将在“var提升”中讨论它们。)

Const

Const (Const.)

Const (constant) is block-scoped. It means that the const declaration creates a constant which scope can be either global or local to the declared block. The value of a constant is read-only. You can’t change it through reassignment and can’t redeclare it. A variable or a function in the same scope can’t have the same name as the variable. (Const (常量)是块作用域。这意味着const声明创建一个常量,其范围可以是声明块的全局或本地。常量的值为只读。您不能通过重新分配来更改它,也不能重新声明它。同一范围内的变量或函数不能与变量具有相同的名称。)

It is a good practice for declaring your constants in uppercase, which will help programmers to separate the constants from other variables in the program. (用大写声明常量是一个很好的做法,这将有助于程序员将常量与程序中的其他变量分开。)

const VARNAME = “Welcome to w3cdoc”; // initialized with a string
const MYBIRTHDAY = '19.03.1986';
MYBIRTHDAY = '04.05.2003'; // error, can't reassign the constant!

Summary

Summary (概要)

There are two types of variables in JavaScript: local and global. They can be represented and manipulated in a programming language. Local variables are declared inside function or block. Global variables are accessible from any function.

We can declare variables by using the var, let, or const keywords. (我们可以使用var、let或const关键字声明变量。)

  • let is a modern variable declaration. (- let是一个现代变量声明。)

  • var is an old variable declaration. (- var是一个旧的变量声明。)

  • const is similar to let, but the value of the variable can’t be changed. (- const类似于let ,但无法更改变量的值。)

It’s important to name variables in a way that allows us to easily understand what’s inside them. (命名变量的方式很重要,使我们能够轻松了解变量内部的内容。)

One more important characteristic of a programming language is the set of data types it supports. There are two main types of languages: statically typed language and dynamically typed language.



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部