JavaScript basic Syntax--a comprehensive understanding of variables and identifiers _ basics

Source: Internet
Author: User
Tags reserved variable scope

The first more important concept about JavaScript is the variable, and the working mechanism of the variable is the basic feature of JavaScript. In fact, a variable is one of the identifiers. This article describes the variables and identifiers in more detail

Defined 

An identifier (Identifier) is a name that is used to name a variable, function, property, parameter, or to use as a marker for a jump position in some loop statement

Variable
var Identifier = 123;
Property
(New Object). Identifier = ' test ';
Functions and Parameter function
IdentifierName (Identifier1) {};
Jump Tag
Identifier: For
(var i = 0; i < 5; i++) {
  if (i = = 3) {break
    Identifier;
  }
}

In daily life, some things are fixed and some things change. For example, a person's name and birthday are fixed, but mood and age change over time. People refer to things that change, as variables.

When the program needs to save the value for future use, it assigns it to a variable. A variable (variable) is a placeholder for saving values that can be used to obtain a reference to a value by a variable name

Naming rules 

In the lexical structure article, we introduce JavaScript as a case-sensitive language, and, like any other programming language, JavaScript retains some identifiers for itself, and reserved words cannot be used as normal identifiers

[note] reserved words include keywords, future reserved words, empty literals, and Boolean literal values

Reserved word reservedword::
  Keyword
  futurereservedword
  nullliteral
  booleanliteral

JavaScript identifier names allow letters, numbers, dollar signs, and underscores (but the first character is not allowed to be digits)

Error demonstration 6num//Beginning can not be used with
 digital
 %sum//Beginning can not use except (_ $) outside special symbols, such as (% +/etc)
 Sum+num//The beginning of the middle can not be used except (_ $) outside special symbols, such as (% +/etc.)

JavaScript allows letters and numbers (including Chinese) in the Unicode character Fu Quan set to appear in the identifier. Therefore, programmers can also use non-English language or mathematical symbols to write identifiers

var Test text = ' Test ';

[note] For portability and easy writing, we usually don't use extended ASCII or Unicode characters

Usually the hump format is the preferred format for identifier naming, the first letter is lowercase, and the remainder of the first letter of each word is capitalized

var mymoodtoday = ' happy ';

For different data types, JavaScript has a convention for naming rules for identifier names

The type          prefix      sample    
array,   a  aitems
Boolean (Boolean) b biscomplete floating-point number
(F      loat)   f  fprice
function (function)  fn  fnhandler
Integer (integer)  i  Iitemcount
Objects (object)   o  oDIv1
Regular expression (REGEXP)    re  reemailcheck
    string (String)    s  susername
variable () Variant  v  vanything        

Variable declaration

Statement

In JavaScript, you should declare (declare) before using a variable, which is declared using the keyword VAR (variable abbreviation)

var i;
var sum;

You can also declare multiple variables with one var keyword

var i, sum;

assigning values

The operation of storing the value in a variable is called an Assignment (Assignment). When a variable is assigned, we say that the variable contains this value

The process of assigning a variable to its first value, called initialization.

We can write the initial assignment of the variable and the variable declaration together

var message = ' Hello ';
var i=0,j=0,k=0;

If the variable is not given an initial value in the Var declaration statement, the variable is declared, but before it is stored in a value, its initial value is undefined

The Var statement can also be used in the for and for-in loops so that you can more succinctly declare the loop variables that are used in the loop syntax

for (var i=0; i<10; i++) Console.log (i);

Variables can be assigned when they are declared, but they cannot have other actions, such as + =, =, etc.

var a = 2;//is correct
var a + = 2;//is wrong
var a = 2++;//is wrong, + + can only be used for variables, not for constants

Repeat statement

It is legal and harmless to use the VAR statement to repeat the declaration of a variable, and if it is repeated and with an assignment, it is equivalent to a new assignment

Omission statement

If you try to read a value for a variable that is not declared, JavaScript will complain

JavaScript allows omitted declarations, that is, assigning a value directly to a variable without prior declaration, the assignment automatically declares the variable

However, in ECMAScript5 strict mode, assigning a value to a variable that is not declared can be an error

<script>
' use strict ';
A = 5;
Console.log (a);
</script>

Variable attributes 

A JavaScript variable is a weak type (also known as a loose type), which is a loosely typed type that can be used to hold any type of data

There are two types of programming languages, dynamic type language and static type language. A dynamic type language is a language that does data type checking during run time, that is, when programming in a dynamically typed language without assigning a data type to any variable, the language records the data type internally when the first assignment is given to the variable. JavaScript is the representative of the dynamic type language.

In JavaScript, you can modify the value's type while modifying the value of the variable

var message = ' Hi ';
Message = 100;//valid, but not recommended

The attributes of a variable loose type are summed up with two points: first, you don't have to specify the data type for the variable when you declare it, or you can modify the data type when you assign a value

Variable scope

The scope of the variable (scope), also called the Execution Environment (execution context), is the region in the program source code that defines this variable

The scope is divided into global scope and function scope (also called local scope) two kinds

The global scope is the outermost execution environment in which the global execution environment is considered a Window object in a Web browser. All global variables and functions are created as properties and methods of the Window object. Global variables have global scope and are defined anywhere in the JavaScript code. Global scope will not be destroyed until the application exits, such as closing a Web page or browser

Variables declared within a function are defined only in the body of the function. They are local variables and the scope is localized. Function arguments are also local variables, which are defined only within the function body. After all the code in the function scope has finished executing, the scope is destroyed, and all the variables and function definitions saved in it are destroyed

function test () {
  var message = ' Hi ';
}
Test ();
alert (message);//Error

If the var operator is omitted, a global variable is created

function test () {Message
  = ' Hi ';
}
Test ();
alert (message);//' Hi '

Although omitting the var operator can define global variables, it is not recommended. Global variables defined in a local scope are difficult to maintain, and if the Var operator is deliberately ignored, it can cause unnecessary confusion because the corresponding variable is not immediately defined, and assigning a value to an undeclared variable can cause a Referenceerror error to be thrown in strict mode

In the body of a function, a local variable has precedence over a global variable of the same name, and if a local variable or a variable with a global variable is declared within a function, the global variable is obscured by the local variable.

var scope = ' Global ';
function Checkscope () {
  var scope = ' local ';
  return scope;
Checkscope ()//' local '

Claim elevation (hoisting)

Block-level scopes

Block-level scopes mean that each piece of code within the curly braces has its own scope, while JavaScript does not have a block-level scope. JavaScript has only function scopes: variables are defined in the body of the function that declares them and in any function that is nested within the function body.

This means that the variable is even available before it is declared. This feature of JavaScript is informally called declarative elevation (hoisting), and all variables declared in JavaScript functions (not involving assignments) are advanced to the top of the function body

[note] In fact, in addition to the variable elevation, the function is also promoted to the function section will be described in detail

var scope = ' Global ';
function f () {
  console.log (scope);//undefined
  var scope = ' local ';
  Console.log (scope);//' Local '
}
After the variable declaration is promoted, the equivalent of the following code
var scope = ' Global ';
function f () {
  var scope;
  Console.log (scope);//undefined
  scope = ' local ';
  Console.log (scope);//' Local '
}

There is no block-level scope in JavaScript, so some programmers deliberately place variable declarations at the top of the function body, a source code that clearly reflects the real variable scope

Property variables

When you declare a JavaScript global variable, you are actually defining a property of the Global object window

When you declare a variable with VAR, the variable you create is not configurable, which means that the variable cannot be deleted by the delete operator

var truevar = 1;
Console.log (Truevar,window.truevar);//1 1
Delete truevar;//false
console.log (truevar,window.truevar);//1 1

If you do not use strict mode and assign a value to an undeclared variable, JavaScript automatically creates a global variable, and the variables created in this way are normal configurable properties of the global object and can be deleted

Window.fakevar1 = ten;
Console.log (FAKEVAR1,WINDOW.FAKEVAR1);//10 
this.fakevar2 =;
Console.log (FAKEVAR2,WINDOW.FAKEVAR2);
Fakevar =;
Console.log (Fakevar,window.fakevar); The delete

window.fakevar1;//true delete
this.fakevar2;//true
Delete fakevar;//true

Console.log (FAKEVAR1,WINDOW.FAKEVAR1)//Error
Console.log (FAKEVAR2,WINDOW.FAKEVAR2);//Error
Console.log ( Fakevar,window.fakevar); Error

JavaScript global variables are properties of global objects, which are enforced in ECMAScript. A local variable is treated as a property of an object associated with a function call. ECMASCRIPT3 is called the invocation object (call objects), ECMASCRIPT5 is called a declaration context object (declarative environment record). JavaScript allows you to use the This keyword to refer to global objects, but there is no way to reference objects stored in local variables. The unique nature of this stored local variable object is an internal implementation that is invisible to us.

The above JavaScript basic syntax--a comprehensive understanding of variables and identifiers is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.