4
头图
"Code tailor" provides technical-related information and a series of basic articles for front-end developers. Follow the "Novices of Xiaohe Mountain" public account on WeChat to get the latest articles in time.

Preface

Before starting to learn, what we want to tell you is that this article is a JavaScript "Language Basics-Grammar and Variables" in 0609d37f1cde16 Language Knowledge. If you have mastered the following knowledge items, you can skip this link directly Go to exercise

  • JavaScript syntax
  • Declare variables and assign values

Summary

The first code

When starting to learn JavaScript , we first look at a section of JavaScript code, as follows:

console.log('Hello JavaScript!')

Can you guess the result of this code? The operation of this code is to output Hello JavaScript! in the console, and the first code is over here.

JavaScript syntax

case sensitive

You need to know ECMAScript is case sensitive. Whether it is a variable, function name, or operator, all are case sensitive. For example, the variable XHS and the variable xhs are two different variables.

Identifier

The so-called identifier is the name of a variable, function, attribute or function parameter. The 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 the identifier can be the letters in the extension ASCII(Extended ASCII) or the alphabetic characters Unicode

By convention, the ECMAScript identifier uses camel case, that is, the first letter of the first word is lowercase, and the first letter of each subsequent word is uppercase, such as:

xhsRookies
xhsRookiesBoy

Although this writing method is not mandatory, it is considered a best practice because it is consistent with the naming method of ECMAScript

Note that the , reserved words, true , false and null cannot be used as identifiers.

Code comment

JavaScript : single-line comments and multi-line comments.

The commented code will not be executed in the program

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

// 单行注释

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

/* 这是多行
       注释 */

Strict mode

ECMAScript 5 adds the concept of strict mode ( strict mode ). Strict mode is a different JavaScript parsing and execution model. ECMAScript 3 will be processed in this mode, and errors will be thrown for unsafe activities. To enable strict mode for the entire script, add this line at the beginning of the script:

'use strict'

Although it looks like a string that is not assigned to any variable, it is actually a preprocessing instruction. Any JavaScript will switch to strict mode when it sees it. The purpose of choosing this grammatical form is not to damage the ECMAScript 3 grammar.

You can also specify a function to execute in strict mode, as long as the preprocessing instruction is placed at the beginning of the function body:

function doSomething() {
  'use strict'
  // 函数体
}

Strict mode affects JavaScript execution, and all modern browsers support strict mode.

Statement

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

var sum = a + b // 没有分号也有效,但不推荐
var diff = a - b // 加分号有效,推荐

Even if the semicolon at the end of the statement is not required, it should be added. Remember to add a semicolon to help prevent problems caused by omissions, for example, to avoid incomplete input. In addition, adding a semicolon is also convenient for developers to compress the code by deleting blank lines (if there is no trailing semicolon, only deleting blank lines will result in syntax errors). Adding a semicolon can also help improve performance in some cases, because the parser will try to add a semicolon at the right place to correct grammatical errors.

Keywords and reserved words

ECMA-262 describes a set of reserved keywords , these keywords have special purposes, such as indicating the start and end of control statements, or to perform specific operations. According to regulations, 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

The specification also describes a set of future reserved words , which 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. The following are all the words reserved for the future ECMA-262

Always keep:

enum

Reserved in strict mode

implements  package     public
interface   protected   static
let         private

Keep in the module code

await

Declare variables and assign values

In JavaScript , there are 3 keywords to declare variables: var , const and let . Which, var in ECMAScript can be used in all versions, while const and let only ECMAScript 6 (will learn later) and later versions use.

var keyword

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

var xhsRookies

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

var xhsRookies = 'hi'

xhsRookies is defined as a variable that hi Initializing a variable like this will not identify it as a string type, just a simple assignment. Later, not only can the saved value be changed, but also the type of the value:

var xhsRookies = 'hi'
xhsRookies = 100 // 合法,但不推荐

In this example, the variable xhsRookies first defined as a hi , and then it is rewritten to hold the value 100 . Although it is not recommended to change the type of variable saved value, it is completely valid ECMAScript

1. var declaration scope

The variable defined using the var operator becomes the local variable of the function containing 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' // 局部变量
}
xhsTest()
console.log(xhsRookies) // 出错!

Here, the xhsRookies variable is defined var inside the function. The function is called xhsTest() , calling it will create this variable and assign a value to it. The variable is destroyed immediately after the call, so the last line in the example will cause an error. var operator when defining variables in the function, you can create a global variable:

function xhsTest() {
  xhsRookies = 'hi' // 全局变量
}
xhsTest()
console.log(xhsRookies) // "hi"

After removing the previous var , xhsRookies becomes a global variable. As long as the function xhsTest() called once, this variable will be defined and can be accessed outside the function.

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

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

var xhsRookies = 'hi',
  xhsFound = false,
  xhsNumber = 29

Three variables are defined and initialized here.

2. Var declaration is improved

When using var , the following code will not report an error. This is because variables declared with this keyword will automatically be promoted to the top of block scope 5:

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

The reason why no error is reported is that ECMAScript is regarded as equivalent to the following code when running:

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

This is the so-called "promotion" ( hoist ), which is to pull all variable declarations to the top of the block scope.

let statement

let similar to var , but there are very important differences. The most obvious difference is let is block scope, while the var declared by 0609d37f1ce440 is function scope.

{
  var xhsRookies = 'xhs-rookies'
  console.log(xhsRookies) // xhs-rookies
}
console.log(xhsRookies) // xhs-rookies
{
  let xhsNumber = 26
  console.log(xhsNumber) // 26
}
console.log(xhsNumber) // ReferenceError: xhsNumber 没有定义

Here, the xhsNumber variable cannot be referenced outside the scope of the block because its scope is limited to the inside of the block. Block scope function is a subset of the scope, thus suitable for var scope restrictions also apply to let .

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

var xhsRookies
var xhsRookies
let xhsNumber
let xhsNumber // SyntaxError;标识符xhsNumber已经声明过了

Of course, the JavaScript engine will record the identifier used for variable declaration and the scope of the block in which it is located, so the nested use of the same identifier will not report an error, and this is because there is no repeated declaration 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
}

let of statements will not be affected by mixing 0609d37f1ce501 and var These two keywords do not declare different types of variables, they just indicate how the variable exists in the relevant scope.

var xhsRookies
let xhsRookies // SyntaxError
let xhsNumber
var xhsNumber // SyntaxError

1. Global declaration

Unlike the var keyword, variables declared in the global scope let window object ( var declared by 0609d37f1ce53e will).

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

However, the let declaration still occurs in the global scope, and the corresponding variables will continue in the life cycle of the page. Therefore, in order to avoid SyntaxError , you must ensure that the page does not declare the same variable repeatedly.

2. let scope

Before let appeared, the iteration variables defined in the code block would penetrate to the outside:

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

let , this problem disappeared, because let variable is limited to the code block:

{
  let xhs = 0
}
console.log(xhs) // ReferenceError: xhs 没有定义

const declaration

const behavior and let basically the same, you must initialize the variable when the only important difference is to use it to declare variables and try to modify const declared variables can cause a runtime error.

const xhsNumber = 26
xhsNumber = 36 // TypeError: 给常量赋值

// const 也不允许重复声明
const xhsRookies = 'xhs-rookies'
const xhsRookies = 'xhs-rookies-boy' // SyntaxError

// const 声明的作用域也是块
const xhsRookies = 'xhs-rookies'
console.log(xhsRookies) // xhs-rookies

Variable naming rules

  1. Strict case sensitivity (uppercase variables and lowercase variables are different variables);
  2. Variable names can be composed of numbers, letters (upper and lowercase), underscores, and dollar $ (0609d37f1ce652 ), but they cannot start with a number;
  3. It can not be javascript keywords and reserved words, such as: if , else , function and so on;
  4. Variable names need to be meaningful, that is, semantic, to enhance code readability. For example, use name age for name, which can prevent you from not understanding what the code is after a while, and it can also prevent others from not understanding during cooperation;
  5. Use camel case nomenclature: start with the second word and capitalize the first letter, such as user personal data ( userPersonalData );

Self-test

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

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

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

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

console.log(xhsNumber)
let xhsNumber = 26

3: What is the output result of the following code?

const xhsNumber = 26
xhsNumber = 36
console.log(xhsNumber)

Problem analysis

One,

Answer:A

This question examines the var declaration scope. In the first line, the xhsRookies variable is defined outside the textFun var , and the third line xhsRookies variable is defined var inside the textFun So the last line of output xhsRookies is actually defined in the first line, and the result is: hello

two,

Answer:

undefined

ReferenceError: Cannot access 'xhsNumber' before initialization

This question examines the improvement of variables. When outputting xshRookies , since xshRookies with var , there is variable promotion, so before the output, it will be considered that var xshRookies not assigned, so it is undefind ; when parsing the code, the engine will also notice that JavaScript let declaration at the end of the block, but the undeclared variable cannot be referenced in any way before this. The let is called the "temporary dead zone" ( temporal dead zone ). Reference to any variable declared later at this stage will throw ReferenceError .

three,

Answer:

TypeError: Assignment to constant variable.

This question examines the const declaration. When using it to declare a variable, the variable must be initialized at the same time, and trying to modify const will cause a runtime error.


小和山的菜鸟们
377 声望2.1k 粉丝

每日进步的菜鸟,分享前端学习手册,和有心学习前端技术的小伙伴们互相探讨,一同成长。