Getting startedChapter 5 of 21
Syntax
The vocabulary: values, variables, operators, keywords and expressions.
Values
JavaScript deals in two sorts of value: fixed ones you write down, called literals, and ones held by a name.
JavaScript
console.log(42);
console.log('a string literal');
console.log(true);
console.log([1, 2, 3]);
console.log({ key: 'value' });Output
42
a string literal
true
[1, 2, 3]
{key: "value"}Names
A name is attached to a value with const or let. From then on the name stands in for the value everywhere.
JavaScript
const country = 'Germany';
let visits = 3;
visits = visits + 1;
console.log(country, visits);Output
Germany 4
Operators
Operators combine values. Arithmetic ones produce numbers, comparison ones produce true or false, and assignment stores a result.
JavaScript
console.log(7 + 3);
console.log(7 > 3);
console.log('a' + 'b');Output
10 true ab
Expressions and statements
An expression is anything that produces a value. A statement is an instruction. 2 + 2 is an expression; const four = 2 + 2; is a statement containing one.
The difference matters because expressions can go wherever a value is expected, including inside other expressions.
JavaScript
const width = 4;
const height = 3;
console.log('area: ' + (width * height));Output
area: 12
Keywords
Some words are reserved by the language and cannot be used as names: const, let, function, return, if, class and around thirty more. Trying to use one is a syntax error, which at least fails loudly.
Identifiers
A name may contain letters, digits, _ and $, and may not start with a digit. Convention is camelCase for variables and functions, PascalCase for classes, and capitals for values that are fixed for the life of the program.
JavaScript
const firstName = 'Ada';
const MAX_USERS = 100;
console.log(firstName, MAX_USERS);Output
Ada 100
Test yourself
2 questionsWhat is the difference between an expression and a statement?
Show the answer
An expression produces a value; a statement is an instruction Which is why an expression can be nested inside another one, and a statement cannot.
Which name is not allowed?
Show the answer
2fast An identifier may contain digits but may not start with one.
Comments
Notes the engine ignores, and what is worth writing in them.