Syntax
Semicolon
Statements in JavaScript must end in a ;
. However, JavaScript has Automatic Semicolon Insertion (ASI) which means that, if you omit a semicolon, JavaScript will automatically add it where it thinks it should go.
In this class, we always remember to insert semicolons.
Why?
Because omitting a semicolon in certain situations can cause problems.
Here is a completely contrived example:
x
++
y
should it be interpreted as:
x;
++y;
or:
x++;
y;
Depending on the implementation of ASI, it might be interpreted as the first or the second one.
Thus, it's recommended to insert the ;
where it is intended. Most JavaScript linters such as Prettier insert semicolons to your code.
ASI bites you even if you conscientiously put all semicolons! For instance if you accidentally hit enter after return
:
return // Semicolon inserted here
someComplicatedExpression;
Identifier naming rules
Identifiers (names of any function, property or variable) may contains letters (only ASCII letters), numbers, dollar signs or underscores.
The first character must not be a number.
Why?
It is also recommended to not use
$
or_
as the first character of your variables.
Why?
For clarity mainly! Some popular JavaScript libraries (such as jQuery, UnderscoreJS, Lodash) use these characters as their identifiers.
Keep in mind JavaScript is case sensitive.
In this course we use camelCase
naming conventions (so name your function calcTax
not calc_tax
). Refer to Google JavaScript Style Guide for more information.
Reserved words cannot be used as identifiers.
Like most programming languages, there are a number of reserved words in JavaScript that you cannot use to name your functions and variables (e.g. var
, let
, new
). For a complete list, refer to MDN web docs; JavaScript reference: Keywords.
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