“Code Tailor “provides technology related information and a series of basic articles for front-end developers. Follow the wechat public account” Rookie of Xiaohe Mountain “to get the latest articles.

preface

Before we get started, we want to let you know that this article is a summary of the “Language basics – Syntax and variables” section of the JavaScript language. If you already know the following, you can skip this section and jump right into the exercises

  • JavaScript syntax
  • Declare variables and assign values

Summary to summarize

First code

To get started with JavaScript, let’s look at some JavaScript code like this:

console.log('Hello JavaScript! ')
Copy the code

Can you guess the result of this code? What this code does is output Hello JavaScript on the console! That’s the end of the first code.

JavaScript syntax

Case sensitive

You need to know that everything in ECMAScript is case sensitive. Variables, function names, and operators are case sensitive. For example, the variable XHS and the variable XHS are two different variables.

identifier

An identifier is the name of a variable, function, attribute, or function parameter. An identifier can consist of one or more of the following characters:

  • The first character must be a letter, underscore (_) or dollar sign ($);
  • The remaining characters can be letters, underscores, dollar signs, or numbers.

The letters in an identifier can be letters in Extended ASCII or Unicode alphabetic characters.

By convention, ECMAScript identifiers use camelcase, i.e. the first letter of the first word is lowercase and the first letter of each subsequent word is capitalized, as in:

xhsRookies
xhsRookiesBoy
Copy the code

While this is not mandatory, it is a best practice because it is consistent with the naming of ECMAScript built-in functions and objects.

Note that keywords, reserved words, true, false, and NULL cannot be used as identifiers.

Code comments

There are two types of comments in JavaScript: single-line comments and multi-line comments.

Commented code is not executed in the program

Single-line comments begin with two slash characters, such as:

// Single-line comment
Copy the code

Multi-line comments begin with a slash and an asterisk (/*) and end with their reverse combination (*/), as in:

/* This is a multi-line comment */
Copy the code

Strict mode

ECMAScript 5 adds the concept of Strict mode. Strict mode is a different model of JavaScript parsing and execution in which non-canonical writing of ECMAScript 3 is handled and errors are thrown for unsafe activities. To enable strict mode for the entire script, add this line at the beginning of the script:

'use strict'

Copy the code

Although it looks like a string that is not assigned to any variable, it is actually a preprocessor instruction. Any engine that supports JavaScript will see it and switch to strict mode. This syntax form was chosen so as not to break ECMAScript 3 syntax.

It is also possible to specify a separate function to execute in strict mode by placing the preprocessor at the beginning of the function body:

function doSomething() {
  'use strict'
  / / the function body
}
Copy the code

Strict mode affects many aspects of JavaScript execution and is supported by all modern browsers.

statements

Statements in ECMAScript end with a semicolon. Omitting the semicolon means that the parser determines where the statement ends, as in the following example:

var sum = a + b // It works without a semicolon, but is not recommended
var diff = a - b // A semicolon is recommended
Copy the code

A semicolon at the end of a statement should be added even if it is not required. Remember to add a semicolon to help prevent problems with ellipsis, such as incomplete input. In addition, adding semicolons makes it easier for developers to compress code by removing empty lines (if there is no trailing semicolon, removing only empty lines will result in a syntax error). Semicolons can also help improve performance in some cases, as parsers try to fill in semicolons in the right places to correct syntax errors.

Keywords and reserved words

Ecma-262 describes a set of reserved keywords that have special uses, such as indicating the beginning and end of a control statement, or performing a specific operation. By rule, reserved keywords cannot be used as identifiers or attribute names.

break       do          in            typeof
case        else        instanceof    var
catch       export      new           void
class       extends     return        while
const       finally     super         with
continue    for         switch        yield
debugger    function    this
default     if          throw
delete      import      try
Copy the code

The specification also describes a set of future reserved words that cannot be used as identifiers or attribute names. Although reserved words have no specific purpose in the language, they are reserved for future use as keywords. Below are all the words reserved for the future in ecMA-262 version 6.

Always reserved:

enum
Copy the code

Reserved in strict mode

implements  package     public
interface   protected   static
let         private
Copy the code

Reserved in the module code

await
Copy the code

Declare variables and assign values

In JavaScript, there are three keywords to declare variables: var, const, and let. Var is available in all versions of ECMAScript, while const and let are available only in ECMAScript 6 (which you’ll learn about later) and later.

The var keyword

To define a variable, use the var keyword followed by the variable name:

var xhsRookies
Copy the code

This line defines a variable called xhsRookies, which you can use to hold any type of value. ECMAScript implements variable initialization, so you can define a variable and set its value at the same time:

var xhsRookies = 'hi'
Copy the code

XhsRookies is defined as a variable that holds the string value hi. Initializing a variable like this does not identify it as a string, just a simple assignment. You can then change not only the saved value, but also the type of the value:

var xhsRookies = 'hi'
xhsRookies = 100 // Legal, but not recommended
Copy the code

In this example, the variable xhsRookies is first defined as a variable that holds the string value hi, and then rewritten to hold the value 100. Changing the type of variable saved values is not recommended, but it is perfectly valid in ECMAScript.

1. Var declares scope

A variable defined using the var operator becomes a local variable of the function that contains it. For example, using var to define a variable inside a function means that the variable will be destroyed when the function exits:

function xhsTest() {
  var xhsRookies = 'hi' // Local variables
}
xhsTest()
console.log(xhsRookies) / / error!
Copy the code

Here, the xhsRookies variable is defined inside the function using var. The function is called xhsTest(), which creates the variable and assigns it a value. The variable is destroyed immediately after the call, so the last line in the example causes an error. However, we can create a global variable by omitting the var operator when defining variables within a function:

function xhsTest() {
  xhsRookies = 'hi' // Global variables
}
xhsTest()
console.log(xhsRookies) // "hi"
Copy the code

With the var removed, xhsRookies becomes a global variable. This variable is defined once the function xhsTest() is called and can be accessed outside the function.

While it is possible to define global variables by omitting the var operator, this is not recommended. Global variables defined in local scope are difficult to maintain and can cause confusion.

If you need to define multiple variables, separate each variable (and optional initialization) in a single statement with a comma:

var xhsRookies = 'hi',
  xhsFound = false,
  xhsNumber = 29
Copy the code

There are three variables defined and initialized.

2. The var declaration is improved

The following code does not report an error when var is used. This is because variables declared with this keyword are automatically promoted to the top of block scope 5:

{
  console.log(xhsNumber) // undefined
  var xhsNumber = 26
}
Copy the code

The error is not reported because the ECMAScript runtime sees this as equivalent to code like this:

{
  var xhsNumber
  console.log(xhsNumber) // undefined
  xhsNumber = 26
}
Copy the code

This is called the “hoist,” which simply pulls all variable declarations to the top of the block scope.

Let the statement

Let and VAR have similar functions, but with a very important difference. The most obvious difference is that the scope of the LET declaration is block scope, while the scope of the VAR declaration is function scope.

{
  var xhsRookies = 'xhs-rookies'
  console.log(xhsRookies) // xhs-rookies
}
console.log(xhsRookies) // xhs-rookies
Copy the code
{
  let xhsNumber = 26
  console.log(xhsNumber) / / 26
}
console.log(xhsNumber) // ReferenceError: xhsNumber is not defined
Copy the code

Here, the xhsNumber variable cannot be referenced outside the block scope because its scope is limited to the inside of the block. Block scopes are subsets of function scopes, so the same scope restrictions that apply to var also apply to LETS.

Let also does not allow redundant declarations in the same block scope. This will result in an error:

var xhsRookies
var xhsRookies
let xhsNumber
let xhsNumber // SyntaxError; The identifier xhsNumber is already declared
Copy the code

Of course, the JavaScript engine keeps track of the identifiers used for variable declarations and the block scope in which they are located, so nesting the same identifiers is not an error because there are no duplicate declarations in the same block:

var xhsRookies = 'xhs-rookies'
console.log(xhsRookies) // 'xhs-rookies'
{
  var xhsRookies = 'xhs-rookies-boy'
  console.log(xhsRookies) // 'xhs-rookies-boy'
}
let xhsNumber = 30
console.log(xhsNumber) / / 30
{
  let xhsNumber = 26
  console.log(xhsNumber) / / 26
}
Copy the code

Error reporting on declaration redundancy is not affected by mixing let and var. These two keywords do not declare different types of variables; they simply indicate how variables exist in the relevant scope.

var xhsRookies
let xhsRookies // SyntaxError
let xhsNumber
var xhsNumber // SyntaxError
Copy the code

1. Global declaration

Unlike the var keyword, variables declared in the global scope using let do not become properties of the Window object (variables declared by var do).

var xhsRookies = 'xhsRookies'
console.log(window.xhsRookies) // 'xhsRookies'
let xhsNumber = 26
console.log(window.xhsNumber) // undefined
Copy the code

However, let declarations still occur in global scope, and the corresponding variables persist for the life of the page. Therefore, to avoid syntaxErrors, you must ensure that the page does not declare the same variable twice.

2. Let scope

Before let, the iteration variables defined in the code block would leak out:

{
  var xhs = 5
}
console.log(xhs) / / 5
Copy the code

This problem disappears when you use let instead, because the scope of the let variable is limited to inside the code block:

{
  let xhs = 0
}
console.log(xhs) // ReferenceError: XHS is not defined
Copy the code

Const statement

Const behaves much the same as let, with the only important differences being that variables declared with it must also be initialized, and attempts to modify a variable declared by const result in a runtime error.

const xhsNumber = 26
xhsNumber = 36 // TypeError: Assigns values to constants

// Const also does not allow repeated declarations
const xhsRookies = 'xhs-rookies'
const xhsRookies = 'xhs-rookies-boy' // SyntaxError

// The scope of const declarations is also a block
const xhsRookies = 'xhs-rookies'
console.log(xhsRookies) // xhs-rookies
Copy the code

Variable naming rules

  1. Strictly case sensitive (uppercase and lowercase variables are different variables);
  2. Variable names can consist of numbers, letters (upper and lower case), underscores, dollar signs ($), but cannot start with a number;
  3. Can’t bejavascriptKeywords and reserved words in, such as:if.else.functionAnd so on;
  4. Variable names need to be meaningful, that is, semantic, to enhance code readability, such as storing ageage, name withname, can prevent after a period of time do not understand what the code is, can also prevent cooperation when others do not understand;
  5. Use camelback nomenclature: Capitalize the first letter starting with the second word, such as user personal data (userPersonalData);

The title self-test

One: what is the output result of the following code?

var xhsRookies = 'hello'
function textFun() {
  var xhsRookies = 'hi'
}
console.log(xhsRookies)
Copy the code
  • A. hello
  • B. hi
  • C. hi hello
  • D. hello hi
Answer

Answer: A,

The xhsRookies variable is defined outside the scope of textFun using var. The xhsRookies variable is defined inside the scope of textFun using var. So the last line of output xhsRookies is actually defined on the first line, and the result is: Hello


Two: what is the output result of the following code?

console.log(xhsRookies)
var xshRookies = 'xhs-rookies'

console.log(xhsNumber)
let xhsNumber = 26
Copy the code
Answer

undefined

ReferenceError: Cannot access ‘xhsNumber’ before initialization

When xshRookies is outputed, it is undefind because xshRookies uses var to declare variable promotion. When parsing code, the JavaScript engine also pays attention to let declarations that appear after blocks, but undeclared variables cannot be referred to in any way until then. The moment of execution prior to a LET declaration is known as a “temporal dead zone,” where references to any variables declared later will raise a ReferenceError.


Three: what is the output result of the following code?

const xhsNumber = 26
xhsNumber = 36
console.log(xhsNumber)
Copy the code
Answer

TypeError: Assignment to constant variable.

This examines the nature of const declarations, which must be initialized at the same time as they are declared, and attempts to modify a variable declared by const results in a runtime error.

JavaScript series language foundation, we end here, thank you for your support to the author! Your attention and praise will be the strongest motivation for us to move forward! Thank you!