Syntax is the set of rules for how a programming language must be written, the same way grammar and spelling are the rules for English. A reader can usually guess what a misspelled sentence means, but JavaScript cannot guess. If the syntax is wrong, it stops with an error or does something you did not intend. Learning these rules up front saves hours of debugging later.
Here is a tiny program that shows most of the pieces this lesson covers:
// How to declare variables:
let x = 5;
let y = 6;
// How to compute values:
let z = x + y;
// I am a comment. I do nothing.
Keywords (let), names (x, y, z), values (5, 6), operators (=, +), and comments. Each gets its own section below.
JavaScript syntax has two kinds of values: fixed values and variable values.
A literal is a value typed directly into the code. It means exactly what it says and never changes. Numbers and strings are the most common:
// Number literals: written with or without decimals, no quotes
10.50
1001
-100
// String literals: text inside double or single quotes
"John Doe"
'John Doe'
1001 is a number, "1001" is a string.
A variable is a named container that stores a value. Unlike a literal, what is inside can change. Each variable needs its own unique name:
let score; // create a variable called score
score = 6; // put the value 6 in it
score = 10; // replace it with 10
console.log(score);
Variables get three full lessons next (Variables, Let, Const). For now, just recognize the difference: 10 is a literal, score is a variable holding one.
Keywords are words JavaScript reserves for itself. Each one tells JavaScript to perform a specific action. let and const, for example, both mean "create a variable":
let x = 5;
const fname = "John";
Some keywords you will use constantly:
let // declare a variable that can change
const // declare a variable that cannot be reassigned
var // old-style declaration (avoid)
if // run code only when a condition is true
for // repeat code in a loop
function // define a reusable block of code
return // exit a function and send back a value
Because they are reserved, keywords cannot be used as variable names. let let = 5; is an error.
let. It does not read LET or Let as the keyword, so Let x = 5; fails with a SyntaxError. If you type in a word processor that auto-capitalizes the first word of a line, watch for this.
An identifier is the name you give a variable, function, or other item. JavaScript has strict rules about which names are legal:
_, or dollar sign $let, if, return, and so on)score and Score are two different names// Valid identifiers
let userName;
let _count;
let $price;
let item2;
// Invalid identifiers
let 2item; // starts with a digit
let user-name; // hyphen
let user name; // space
let let; // reserved keyword
Why can a name not start with a digit? So JavaScript can instantly tell names and numbers apart. When it sees 2 at the start of a word, it knows a number is coming. Why no hyphens? Because - already means minus. JavaScript would read user-name as "user minus name".
Operators are the symbols that do something with values.
The assignment operator = stores a value in a variable. It does not mean "equals" like in math; it means "put the value on the right into the name on the left":
let x = 5;
let y = 6;
let sum = x + y; // work out x + y, store the result in sum
The arithmetic operators compute values:
let a = 10;
let b = 3;
console.log(a + b); // addition
console.log(a - b); // subtraction
console.log(a * b); // multiplication
console.log(a / b); // division
console.log(a % b); // remainder (10 รท 3 is 3, remainder 1)
Notice the division result ends in 5 instead of repeating 3s forever. Computers store decimals with limited precision; the JS Numbers lesson explains why. The operators each get full lessons in the JS Operators section.
An expression is any combination of values, variables, and operators that computes to a single value. The computing is called evaluating:
(5 + 6) * 10 // evaluates to 110 (parentheses first)
x * 10 // evaluates to 50 when x is 5
"John" + " " + "Doe" // evaluates to "John Doe"
Expressions can be used anywhere a value is expected, including on the right side of =:
let price = 100;
let tax = 0.08;
let total = price + (price * tax);
console.log(total);
price * tax has a value (8). let total on its own does not; it is a declaration, part of a statement. Statements are the next lesson.
Text after // is a comment. JavaScript skips it completely; it is there for the humans reading the code. Comments get their own lesson (JS Comments).
let x = 5; // I will be executed
// x = 6; I will NOT be executed
JavaScript is case sensitive everywhere: keywords, variable names, function names, all of it. Two names that differ only by capitalization are two completely separate variables:
let lastName = "Doe";
let lastname = "Peterson"; // a different variable
console.log(lastName);
console.log(lastname);
console.log(LastName);
ReferenceError: X is not defined for a variable you are sure you created, check the capitalization first.
Variable names often need more than one word, and spaces are not allowed. Programmers have used several ways to join words:
| Style | Example | In JavaScript |
|---|---|---|
| lower camelCase | firstName | The standard for variables and functions |
| PascalCase | FirstName | Used for classes (a later topic) |
| UPPER_SNAKE_CASE | TAX_RATE | Fixed settings that never change |
| snake_case | first_name | Legal but not the JS habit (common in Python) |
| kebab-case | first-name | Not allowed: - is minus (fine in CSS/HTML) |
let firstName = "Alex";
let totalPrice = 149.99;
let isLoggedIn = true;
let maxRetryCount = 3;
A good name says what the value is. totalPrice beats tp, and isLoggedIn tells you at a glance it holds true or false.
Which of these names are legal? $total, 3rdPlace, _temp, high-score, const, player2
$total, _temp, player2. Illegal: 3rdPlace (starts with a digit), high-score (hyphen is minus), const (reserved keyword).What does this log?
let points = 4;
console.log((points + 2) * 10);
60. Parentheses first: 4 + 2 is 6, then 6 * 10 is 60.What happens here?
let Score = 10;
console.log(score);
ReferenceError: score is not defined. The variable is Score with a capital S. Lowercase score is a different name that was never created.let myCity = "Baltimore"; and logs it. Click Run and find Baltimore in the Consoleconsole.log(myCity) to console.log(mycity) and run it again. Read the ReferenceErrorLet x = 1; with a capital L. Run it, read the error, then fix it(8 + 2) * 5 and then 8 + 2 * 5. Why are they different?