JS Syntax
JavaScript syntax is the set of rules that defines a valid program. Most of it should feel familiar if you've seen any C-family language.
The core rules
- Case-sensitive —
totalandTotalare different. - Whitespace and line breaks are ignored (mostly — see ASI).
- Statements end with
;(auto-inserted in most cases). - Blocks are wrapped in
{ }. - Strings are
"…",'…', or`…`. - Comments are
// …or/* … */.
Identifiers (names)
| Rule | OK | Not OK |
|---|---|---|
Must start with letter, $, or _ | name, $x, _tmp | 2nd, -name |
Letters, digits, $, _ only | user1 | user-name |
| Not a reserved word | cls | class, return |
Tiny program
JS
// declarations
const name = "Ada";
let xp = 0;
// function declaration
function gain(amount) {
xp += amount;
return xp;
}
// control flow
if (gain(50) >= 50) {
console.log(`${name} levelled up!`);
}
Tip: Read JavaScript style guides (Airbnb, Standard) once. Most teams pick one, lint against it, and never argue about syntax again.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Syntax!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Pick a valid identifier name to declare a counter.
let
= 0;
Letters and underscores work; cannot start with a digit.
Discussion
Loading…