JavaScript Syntax

6 minute read

Syntax is the grammar of a language — the rules that decide whether a line of code is even legal before the engine tries to run it. JavaScript’s syntax is relaxed compared to languages like Java or C++, but it has firm rules about identifiers, keywords, literals, case sensitivity, and Unicode. Knowing them up front saves hours of debugging later.

The Building Blocks

Every piece of JavaScript source is made of five kinds of token:

Token Example Meaning
Keyword let, const, if, return Reserved word with a built-in meaning
Identifier name, userCount, _temp A name you choose (variables, functions, classes)
Literal 42, "hi", true, null A value written directly into the source
Operator +, ===, &&, => Acts on operands to produce a value
Punctuation { }, ( ), ;, , Structures the code
let userCount = 42 + 1;   // keyword, identifier, operator, literal, operator, literal, punctuation

Identifiers — Naming Things

An identifier is the name you give to a variable, function, class, or property.

Rules

// ✅ Legal
let name;
let _private;
let $element;
let user2;
let über = "ok";        // Unicode letters allowed
let π = 3.14159;
let camelCase, snake_case;

// ❌ Illegal
let 2cool;              // can't start with a digit
let user-name;          // hyphens are not allowed
let class;              // reserved keyword
let "name";             // strings aren't identifiers
Rule Allowed
Start with Letter, _, $, or Unicode letter
Subsequent chars Letters, digits, _, $, Unicode letters
Cannot start with A digit
Cannot be A reserved keyword
Case sensitive ✅ name ≠ Name ≠ NAME

Naming Conventions (Strong Recommendations)

Style Used For Example
camelCase Variables, functions, methods userName, getOrders()
PascalCase Classes, constructors, components class HttpClient {}
UPPER_SNAKE_CASE True constants MAX_RETRIES = 5
_leading Internal / “private” (convention) _internalCache
$leading jQuery-style, DOM refs $button
// ✅ Idiomatic modern JS
const MAX_RETRIES = 5;

class HttpClient {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
  }
  async fetchUser(userId) { /* ... */ }
}

const client = new HttpClient("https://api.example.com");

Tip: Names are documentation. let x = users.filter(u => u.a) is unreadable. const activeUsers = users.filter(u => u.isActive) reads like English.

Reserved Keywords

You can’t use these as identifiers — they have meaning to the language itself.

Category Words
Declarations var, let, const, function, class, import, export
Control flow if, else, switch, case, default, for, while, do, break, continue, return, throw
Error handling try, catch, finally
Operators new, delete, typeof, instanceof, in, of, void, yield, await
Boolean / null true, false, null
Context this, super
Future-reserved enum, implements, interface, package, private, protected, public, static
let class = "x";    // ❌ SyntaxError
let new = 5;        // ❌ SyntaxError
let className = "x"; // ✅ fine

Note: undefined, NaN, and Infinity are not reserved words — they’re global properties. You shouldn’t reassign them, but the language doesn’t stop you. Use them as values, not identifiers.

Literals

A literal is a value written directly into the source code. JavaScript has literals for every primitive type:

// Number literals
42                  // integer
3.14                // float
1_000_000           // numeric separator (readable)
0xff                // hex (255)
0b1010              // binary (10)
0o755               // octal (493)
2.5e3               // scientific (2500)
9007199254740993n   // BigInt

// String literals
"double quotes"
'single quotes'
`template literal with ${interpolation}`

// Boolean literals
true
false

// null and undefined
null
undefined

// Array literal
[1, 2, 3]

// Object literal
{ name: "Ada", age: 36 }

// Regular expression literal
/^[a-z]+$/i

// Function literal (expression)
function () { return 1; }
() => 1

Operators

Operators combine values to produce new values. Categories you’ll meet:

Category Examples
Arithmetic + - * / % **
Assignment = += -= *= /= **= &&= ??=
Comparison == === != !== < <= > >=
Logical && \|\| ! ??
Bitwise & \| ^ ~ << >> >>>
String + (concatenation), template literals
Type typeof, instanceof
Member access . [] ?.
Spread / rest ...
Ternary cond ? a : b

Operator precedence is covered in chapter 11.

Case Sensitivity

JavaScript is case sensitive everywhere. Identifiers, keywords, properties — all of it.

let name = "Ada";
let Name = "Linus";
let NAME = "Grace";

console.log(name, Name, NAME);
// Output: Ada Linus Grace — three different variables

let If = "ok";   // ✅ "If" ≠ keyword "if"
let if = "x";    // ❌ SyntaxError — "if" is reserved
const user = { name: "Ada" };
console.log(user.Name);  // undefined — property "Name" doesn't exist
console.log(user.name);  // "Ada"

Warning: Case-sensitivity bugs are silent. getElementById vs getElementByID returns undefined and then crashes later when you try to use it. Stick to camelCase religiously.

Comments — A Quick Preview

Comments aren’t executed; they exist for humans. Two flavours (covered in chapter 6):

// Single-line: from // to end of line

/* Multi-line:
   spans
   multiple lines */

Strings — Single, Double, or Backtick

All three create strings. Pick a style and stick to it; backticks unlock interpolation.

const a = "double";
const b = 'single';
const c = `backtick`;
const d = `Hello, ${a} quotes!`;   // template literal — supports ${expr}
const e = `multi
            line
            string`;               // backticks preserve newlines

Tip: Modern style guides (Prettier, StandardJS) default to double quotes ("...") for plain strings and backticks (`...`) when you need interpolation or multi-line.

Whitespace

Whitespace is for humans, not for the engine.

// All identical to the engine
let x=1+2;
let x = 1 + 2;
let x   =   1   +   2;
let x =
    1
  + 2;

The one place whitespace matters is inside template literals, where every space, tab, and newline is preserved in the resulting string.

Indentation

There is no “right” indent size — but consistency matters. Two dominant styles:

Style Used By
2 spaces Most modern JS (Prettier default, React, Vue, npm)
4 spaces Older codebases, Python-influenced teams
Tabs A vocal minority

Pick one, configure your editor and Prettier, move on.

Unicode and Emoji

JavaScript source is UTF-8 / UTF-16. Identifiers can include Unicode letters; strings can include anything.

const π = Math.PI;
const naïve = true;
const greeting = "こんにちは, 🌎";

console.log(greeting);
// Output: こんにちは, 🌎

Emojis in identifiers are technically legal but a terrible idea — stick to ASCII for names.

Putting Syntax Rules Together

// Keywords, identifiers, literals, operators, blocks
const MAX_USERS = 100;
let userCount = 0;

function addUser(name) {
  if (userCount >= MAX_USERS) {
    throw new Error(`Cannot add ${name}: at capacity`);
  }
  userCount += 1;
  return { id: userCount, name };
}

const ada = addUser("Ada");
console.log(ada);
// Output: { id: 1, name: 'Ada' }

Every token in that block falls into one of the five categories at the top of this chapter.

Syntax Checklist

  • ✅ Use camelCase for variables and functions, PascalCase for classes, UPPER_SNAKE_CASE for constants
  • ✅ Pick a quote style (") and a indent (2 spaces) and let Prettier enforce them
  • ✅ Avoid reserved keywords — your editor will underline them in red
  • ✅ Names should describe what the value means, not how it’s stored
  • ❌ Don’t mix camelCase and snake_case in the same codebase
  • ❌ Don’t reassign undefined, NaN, Infinity, or any global

What’s Next?

Now you know what valid code looks like. Comments are the one piece of syntax that gets ignored at runtime — let’s see how to use them well (and when not to).

← Previous: JS Statements Next: JS Comments →

Updated: