JavaScript Lexical Structure: Case, Whitespace, Comments, Literals, Identifiers and Reserved Words
The lowest-level rules of JavaScript: case sensitivity, whitespace and line terminators, every comment form (including JSDoc and #! lines), all kinds of literals, what makes a valid identifier, and exactly which reserved words are banned in sloppy code, strict code and modules, verified with code.
kvi5hnuCode Sprout team member10 min readOn this page
Before a JavaScript engine can run your program, it has to cut the text into tokens: names, numbers, strings, operators and punctuation. The rules for doing that are the language's lexical structure. They decide questions like "is Total the same as total?", "can I name a variable class?" and "is 5.toString() legal?".
This is the least glamorous part of any language, but it explains a surprising number of confusing error messages. Each rule below is short, and the edge cases are verified with runnable code.

Case sensitivity
JavaScript is case-sensitive. total, Total and TOTAL are three different names, and keywords must be lowercase: while is a loop, While is just an identifier.
let total = 1;
let Total = 2;
let TOTAL = 3;
console.log(total, Total, TOTAL);
console.log(typeof While); // not a keyword, just an undeclared name
1 2 3
undefined
Two conventions build on this. Variables and functions use camelCase (orderTotal, getUser), and classes use PascalCase (ShoppingCart). Constants that are true configuration values are often written in UPPER_SNAKE_CASE (MAX_RETRIES).
Case sensitivity applies to the language, not necessarily to everything around it: HTML tag and attribute names are case-insensitive, while file names in import paths depend on the operating system. A module imported as ./Utils.js may work on macOS or Windows and then fail on a Linux server where the file is utils.js.
Whitespace and line terminators
Spaces, tabs and line breaks between tokens are ignored, so you can lay code out however you like:
const area=width*height; // cramped
const area2 = width * height; // conventional
const area3 =
width *
height; // spread over lines
Besides the ordinary space, JavaScript treats tabs, the vertical tab, form feed, the no-break space (U+00A0), the byte order mark (U+FEFF) and every other Unicode "space separator" as whitespace. Line terminators are line feed (\n), carriage return (\r), the CR LF pair used on Windows, and the rarely seen Unicode line separator (U+2028) and paragraph separator (U+2029).
Line breaks are mostly ignored, with one important exception: in a few places a line break acts as a semicolon, which can change what your code means. Article 8 covers these rules (automatic semicolon insertion) in detail.
Comments
JavaScript has two comment forms:
// A single-line comment runs to the end of the line.
/* A block comment can span
several lines. */
let speed = 30; /* it can also sit inside a line */ let limit = 50;
Block comments don't nest: the first */ ends the comment, whatever came before.
try {
eval("/* outer /* inner */ still a comment? */ 42");
} catch (err) {
console.log(err.name + ": " + err.message);
}
console.log(eval("/* first */ 42 /* second */"));
SyntaxError: Unexpected identifier 'a'
42
The comment ended at the first */, so the engine tried to parse still a comment? */ 42 as code and choked on the second word. To comment out a block of code that already contains block comments, use // on every line (editors do this with Ctrl+/ or Cmd+/).
Three special forms are worth recognizing:
-
Documentation comments start with
/**. They're ordinary block comments to the engine, but tools read them: the JSDoc format with tags like@paramand@returnsgives editors hover documentation and type hints, and TypeScript can type-check plain JavaScript using JSDoc types.javascript/** * Converts a temperature from Celsius to Fahrenheit. * @param {number} celsius - the temperature in degrees Celsius * @returns {number} the temperature in degrees Fahrenheit */ function toFahrenheit(celsius) { return celsius * 9 / 5 + 32; } -
A hashbang line,
#!/usr/bin/env node, is allowed as the very first line of a file (standardized in ES2023). On Unix systems it lets you run a script directly as./tool.jsafterchmod +x. The engine treats the line as a comment. -
HTML-like comments
<!--and-->are a legacy from 1990s browsers that didn't understand<script>. Engines still accept them in classic scripts for compatibility, but not in modules. Never write them on purpose; just know whyx <!--ydoesn't mean "x is less than not-decremented y".
Literals
A literal is a value written directly in the source code. Here's a preview of every kind; part 3 covers numbers and strings in depth.
// numbers
console.log(42, 3.14, .5, 5., 2.5e3, 1e-3); // decimal forms
console.log(0xff, 0o17, 0b1010); // hex, octal, binary
console.log(1_000_000, 0xff_ff); // _ separators for readability (ES2021)
console.log(123n, 0x10n); // BigInt literals
// strings
console.log("double", 'single', `back${"tick"}`);
console.log("line1\nline2"); // escape sequences
// others
console.log(true, false, null);
console.log(/ab+c/i.test("xABBBC")); // a regular expression literal
console.log([1, 2, 3], { x: 1 }); // array and object literals
42 3.14 0.5 5 2500 0.001
255 15 10
1000000 65535
123n 16n
double single backtick
line1
line2
true false null
true
[ 1, 2, 3 ] { x: 1 }
A few lexical details trip people up:
- Numeric separators may only sit between digits, and only one at a time.
1_000is fine;1__000,1000_and_1000are not (and_1000is a valid identifier, so it's aReferenceError, not a number). - Legacy octal: in sloppy mode, a number with a leading zero such as
0377means octal 255, while08is plain decimal 8. Strict mode forbids both forms. Always write0o377when you mean octal. - Calling a method on an integer literal needs care, because the dot is read as a decimal point:
5.toString()is a syntax error. Write5..toString(),(5).toString()or5 .toString().
const results = [];
for (const src of ["0377", "'use strict'; 0377", "08", "1__000", "_1000", "5.toString()", "5..toString(2)"]) {
try {
results.push(`${src} => ${eval(src)}`);
} catch (err) {
results.push(`${src} => ${err.name}: ${err.message}`);
}
}
console.log(results.join("\n"));
0377 => 255
'use strict'; 0377 => SyntaxError: Octal literals are not allowed in strict mode.
08 => 8
1__000 => SyntaxError: Only one underscore is allowed as numeric separator
_1000 => ReferenceError: _1000 is not defined
5.toString() => SyntaxError: Invalid or unexpected token
5..toString(2) => 101
(eval runs a string as code, which is handy for demonstrating syntax errors without crashing the whole program. Real code should almost never use it.)
Identifiers
An identifier is a name for a variable, function, class, parameter, property or label. The rules:
- The first character must be a letter,
_or$. - Later characters may also be digits.
- "Letter" means any Unicode letter, so
größe,π,ñandúand价格are all valid identifiers. Emoji and symbols are not. - A name can't be a reserved word (next section), except as a property name.
let $price = 9.5; // $ is an ordinary character: jQuery made it famous
let _internal = true; // a leading _ conventionally means "private, don't touch"
let item2 = "pen"; // digits are fine after the first character
// let 2item = "pen"; SyntaxError: can't start with a digit
// let my-item = "pen"; SyntaxError: - is the minus operator
The first-character rule exists so that the tokenizer can tell 2e5 (a number) from e5 (a name) at a glance.
Class bodies add one more form: private names such as #balance, which can only be used inside the class. The # is part of the name. Part 9 covers them.
Reserved words
Some words belong to the language and can't be used as variable names. JavaScript's rules are more nuanced than "a fixed list", because new keywords had to be added without breaking old code. The table below was produced by actually trying var <word> = 1 in each kind of code:
| Category | Words | Sloppy script | Strict code | Module |
|---|---|---|---|---|
| Always reserved | break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with | banned | banned | banned |
| Reserved in strict code | let static yield implements interface package private protected public | allowed | banned | banned |
| Reserved in modules (and async functions) | await | allowed | allowed | banned |
| Restricted names | arguments eval | allowed | can't be declared or assigned | can't be declared or assigned |
| Contextual keywords | as async from get of set target meta accessor | allowed | allowed | allowed |
yield is also reserved inside generator functions, and await inside async functions, wherever they are. And undefined, NaN and Infinity aren't keywords at all: they're read-only properties of the global object. You can declare a local variable called undefined inside a function, which is a great way to confuse every reader, so don't.
function canDeclare(word, strict) {
try {
new Function(`${strict ? '"use strict";' : ""} var ${word} = 1;`);
return "ok";
} catch {
return "--";
}
}
console.log("word sloppy strict");
for (const word of ["class", "enum", "let", "yield", "static", "await", "of", "eval", "async"]) {
console.log(word.padEnd(9), canDeclare(word, false).padEnd(6), canDeclare(word, true));
}
// Any reserved word works as a property name:
const settings = { class: "admin", new: true, default: 3, for: "everyone" };
console.log(settings.class, settings.new, settings.default, settings.for);
word sloppy strict
class -- --
enum -- --
let ok --
yield ok --
static ok --
await ok ok
of ok ok
eval ok --
async ok ok
admin true 3 everyone
Property names may be any word because after a . or in an object literal there's no ambiguity: settings.class can't be the start of a class declaration. That's also why APIs can freely use names like promise.catch() and map.delete(key).
The simplest rule in practice: never use any word from the table as a variable name, except the contextual ones (of, get, set, from, target, async...), which are safe and commonly used.
Common questions
Why is let allowed as a variable name in sloppy mode?
Because code written before 2015 might have used let as a name, and changing that would break it. In sloppy code var let = 1 still works, but let let = 1 is always an error, and strict code reserves the word completely. The same reasoning applies to yield and static.
Can a variable name contain a dollar sign or start with one?
Yes. $ and _ are treated like letters. Libraries use them as short names ($ for jQuery, _ for Lodash), and a leading $ sometimes marks variables that hold DOM elements or observables, purely as a convention.
Is undefined a keyword? Can I assign to it?
No and no. It's a read-only global property: in sloppy mode undefined = 5 is silently ignored, and in strict mode it throws a TypeError. Local variables can shadow it, which is why old libraries wrote void 0 to get a guaranteed undefined.
What's the difference between a keyword and a reserved word?
A keyword has a meaning in the grammar (if, return). A reserved word can't be used as an identifier; most keywords are reserved, plus enum and the strict-mode words reserved for possible future use. Contextual keywords like of and get have meaning only in specific positions and stay usable as names.
Summary
- JavaScript is case-sensitive, ignores whitespace between tokens, and treats line breaks as whitespace except where automatic semicolon insertion applies.
- Comments are
//and non-nesting/* */./** */is read by JSDoc tools, and#!is allowed on the first line. - Literals cover numbers (decimal,
0x,0o,0b, exponents,_separators,nfor BigInt), strings, template literals, booleans,null, regular expressions, arrays and objects. - Identifiers start with a letter,
_or$and continue with those or digits. Unicode letters are allowed; emoji are not. - Some words are always reserved, some only in strict code or modules, and some are merely contextual. All of them work as property names.
Practice Questions
Which of these are valid identifiers: _, $$, 2fast, fast2, my_var, my-var, café, const?
Answer
Valid: _, $$, fast2, my_var, café. Invalid: 2fast (starts with a digit), my-var (the - is an operator) and const (reserved).
What does console.log(010 + 1) print in a sloppy script, and what happens in a module?
Answer
In a sloppy script, 010 is the legacy octal literal 8, so it prints 9. Modules are strict code, so the same line is a SyntaxError ("Octal literals are not allowed in strict mode").
Why does this code work even though new and delete are operators?
const obj = { new: 1, delete: 2 };
obj.new + obj.delete
Answer
Reserved words are only banned as identifiers (variable, function and class names). Property names in object literals and after a dot can be any word, because the grammar position makes their meaning unambiguous. The result is 3.
A teammate comments out a function with /* ... */, and now the file has a syntax error. The function contains the regular expression /\d*/g. What's going on?
Answer
Any */ inside the commented-out code ends the comment early. Here the regex literal /\d*/g contains the characters */, so everything after them becomes code again. Comment out code with // on each line instead.
Is await a reserved word?
Answer
It depends where. In a classic (sloppy or strict) script, outside async functions, await is an ordinary identifier. In modules and inside async functions it's reserved, because there it's the await operator.
Previous: Your First Real JavaScript Program: A Word Frequency Report from Standard Input
Next: Unicode in JavaScript Source Code: Escapes, Normalization and Invisible Characters

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.