JavaScript Tutorial
JavaScript Syntax
Identifiers, literals, and operators. JavaScript is case-sensitive: Name and name are different.
The pieces of a line
A typical line has a name, an operator, and a value. The name is an identifier. The written value is a literal. The operator says what to do.
Example
let total = 10 + 2;
console.log(total);total is the identifier. 10 and 2 are number literals. +and = are operators. let is a keyword.
Try the examples with Try it in JavaScript. That opens /javascript/try.
Identifiers
An identifier is a name you choose: a variable, a function, or a parameter. Start with a letter, underscore, or $. After that you may use letters, digits, underscores, or $. Do not start with a digit. Do not put a space or a hyphen in the name.
| Valid | Invalid |
|---|---|
count, player2, _tmp, $el | 2player, my-score, my score |
Choose names that say what the value is. score is better than x unless you are in a tiny math example.
Literals
A literal is a value written directly in the code. You do not look it up. You write it.
Example
console.log(42);
console.log(3.14);
console.log("Ada");
console.log(true);
console.log(null);| Kind | Example |
|---|---|
| Number | 42, 3.14 |
| String | "Ada", 'Ada' |
| Boolean | true, false |
| Nothing | null, undefined |
JavaScript is case-sensitive
Name and name are different identifiers. Console.log is notconsole.log. Keywords must be lowercase: Let is not let.
Example
let name = "Ada";
let Name = "Grace";
console.log(name);
console.log(Name);The console prints two strings. They are two boxes. Pick one spelling and keep it.
Reserved words
Some words already belong to the language. You cannot use them as variable names. The engine will report a syntax error.
| Keyword | Role |
|---|---|
let, const, var | Declare a name |
if, else, switch | Choose a branch |
function, return | Define and leave a function |
true, false, null | Built-in values |
If a name is already a keyword, pick another word: className instead of class,value instead of default.
Operators
Operators combine or compare values. Arithmetic uses +, -, *,/, and %. Assignment uses =. Comparison uses === and!==. Later chapters cover each group in full.
Example
let n = 7;
console.log(n + 3);
console.log(n === 7);
console.log(n !== 0);Strings are not identifiers
Quotes make a string. No quotes make a name. "score" is text. score is a variable. Mixing them up is a common first error: you log the word instead of the value, or you use a name that was never declared.
Next: comments, so you can leave notes that the engine skips.