The lexical structure of JavaScript

In-depth understanding of the building blocks of JavaScript: Unicode, semicolons, spaces, case sensitivity, comments, text, identifiers, and reserved words

Unicode

JavaScriptIs written asUnicode. This means that you can use Emojis as variable names, but more importantly, you can write identifiers in any language (such as Japanese or Chinese),There are some rules.

semicolon

JavaScript has a syntax very similar to C, and you may see a lot of code examples with semicolons at the end of each line.

Semicolon is not mandatory, And JavaScript has no problems in code that does not use them. Recently, many developers, especially those from languages without semicolons, have begun to avoid using them.

You just need to avoid doing weird things, such as typing statements on multiple lines

return
variable

Or start with brackets ([or(), then you will be safe 99.9% of the time (your shorthair cat will warn you).

It depends on personal preference, I recently decidedNever add useless semicolons, So you will never see them on this site.

Space

JavaScript considers whitespace to be meaningless. Spaces and newlines can be added in any way you like, even if this isTheoretically.

In practice, you are likely to maintain a clear style and follow the styles commonly used by people, and use lint or style tools (e.g.more beautiful.

For example, I like to always indent by 2 characters.

case sensitive

JavaScript is case sensitive. Named variablesomethingUnlikeSomething.

The same is true for any identifier.

comment

You can use two kinds of annotations in JavaScript:

/* */

//

The first one can span multiple lines and needs to be closed.

The second line comments everything on the right side of the current line.

Text and identifier

We define asTextValues written in the source code, such as numbers, strings, Boolean values, or other more advanced constructs, such as Object Literals or Array Literals:

5
'Test'
true
['a', 'b']
{color: 'red', shape: 'Rectangle'}

OneIdentifierIt is a sequence of characters that can be used to identify variables, functions, and objects. It can start with a letter, dollar sign$Or underscore_, And can contain numbers. With Unicode, letters can be any allowed characters, such as emoji😄.

Test
test
TEST
_test
Test1
$test

The dollar sign is usually used for referenceDOMelement.

Reserved word

You cannot use any of the following words as identifiers:

break
do
instanceof
typeof
case
else
new
var
catch
finally
return
void
continue
for
switch
while
debugger
function
this
with
default
if
throw
delete
in
try
class
enum
extends
super
const
export
import
implements
let
private
public
interface
package
protected
static
yield

Because they are reserved by the language.

Download mine for freeJavaScript beginner's manual


More js tutorials: