Syntax Rules
Every programming language has a syntax parser that reads the code you write and determines its structure and whether it is valid. Most of this guidebook will focus on the semantics and syntax of JavaScript. You will learn the syntax rules in each chapter as we cover the different features of the language. Here are some basics to get us started.
Semicolon
Most statements in JavaScript must end with a semicolon (;). However, JavaScript engines typically feature Automatic Semicolon Insertion (ASI). This means if you omit a semicolon, the engine will automatically insert one where it determines a statement ends.
ASI behavior can vary between implementations, and the engine may end a statement somewhere you did not intend. So my personal preference is to always end statements with a semicolon. Most JavaScript code formatters, such as Prettier, default to this behavior as well. That said, some developers disagree with this practice.
Identifier naming rules
Identifiers (names of any function, property, or variable) may contain letters (Unicode letters are allowed), numbers, dollar signs, or underscores. Emojis are not valid identifier characters. Here are a few more things to keep in mind:
-
The first character must not be a number. This rule exists to simplify parsing: it allows the lexer to immediately determine whether a token is a number literal or an identifier based on its first character. Without this rule, expressions like
1e10would be ambiguous (scientific notation or identifier?). -
It is also recommended not to use
$or_as the first character of your variables. This is mainly for clarity: some popular JavaScript libraries (such as jQuery, Underscore, and Lodash) use these characters as their identifiers. -
Keep in mind JavaScript is case sensitive.
Like most programming languages, JavaScript has a number of reserved words that you cannot use to name your functions and variables (e.g., var, let, new, function, class, return, if, else, for, while, etc.).
Comments
Comments in JavaScript are similar to Java and C++:
// I am a single-line comment!
/*
I am a block comment,
and I can be expanded over several lines!
*/
let /* hourly */ payRate = 12.5; // dollars