javascript

Reserved Keywords

A complete guide to JavaScript reserved keywords — what they are, why you cannot use them as variable names, and a full list with real examples of each keyword in action.

15 min read 13 sections Tutorial
Share

JavaScript Reserved Keywords

JavaScript Reserved Keywords

Reserved keywords are words that JavaScript uses for its own grammar. Words like if, for, let, function, and return have a fixed meaning in the language. JavaScript needs these words to understand your code.

Because JavaScript already uses these words, you cannot use them as names for your own variables, functions, or classes. If you try, JavaScript throws a SyntaxError and your code will not run.

This page gives you a complete list of every reserved keyword, explains what each one does, and shows you real examples so you understand them fully.

Why are keywords reserved?

Imagine if you could name a variable if. Then JavaScript would not know: does if mean your variable, or does it mean the start of an if-statement? It would be impossible to understand the code.

Reserving keywords solves this problem. JavaScript sees if and immediately knows: this is an if-statement, not a variable name.

🚫

Cannot Be Variable Names

You cannot use let, for, class, or any reserved keyword as an identifier.

Can Be Part of a Name

forEach, letValue, myClass are fine — the keyword is not alone.

📋

About 40 Keywords

Modern JavaScript has around 40 reserved words. You will use most of them every day.

🔮

Future Keywords

Some words like enum are reserved for future use. Avoid them even if they work today.

What Happens If You Use a Keyword as a Name

What Happens If You Use a Keyword as a Name

If you try to use a reserved keyword as a variable name, JavaScript gives you a SyntaxError immediately — before your code even starts running. This is one of the easiest errors to fix once you know the rule.

javascript
1// ❌ These all cause SyntaxError — cannot use keywords as names:
2// let let = 5; // SyntaxError: Unexpected strict mode reserved word
3// let const = 5; // SyntaxError
4// let for = 5; // SyntaxError
5// let if = 5; // SyntaxError
6// let class = 5; // SyntaxError
7// let return = 5; // SyntaxError
8// let new = 5; // SyntaxError
9
10// ✅ But you CAN use a keyword as part of a longer name:
11let letValue = 5; // 'let' is part of the name — OK
12let myClass = 'Math'; // 'class' is part of the name — OK
13let returnValue = 42; // 'return' is part of the name — OK
14let forLoop = true; // 'for' is part of the name — OK
15let newUser = 'Alice'; // 'new' is part of the name — OK
16
17console.log(letValue, myClass, returnValue, forLoop, newUser);
18
19// ✅ Keywords work fine as object property keys (not identifiers)
20const obj = {
21 if: 'this works',
22 for: 'this works too',
23 class: 'also works'
24};
25console.log(obj.if, obj.for, obj.class);

Declaration Keywords

Declaration Keywords

These keywords are used to declare (create) variables, functions, and classes. You use these every single day in JavaScript.

javascript
1// var — old way to declare a variable (avoid in modern code)
2var oldScore = 50;
3console.log('var:', oldScore);
4
5// let — modern variable — can be changed later
6let score = 100;
7score = 95; // OK — let allows reassignment
8console.log('let:', score);
9
10// const — constant — cannot be reassigned
11const MAX_SCORE = 100;
12// MAX_SCORE = 200; // ❌ TypeError
13console.log('const:', MAX_SCORE);
14
15// function — declares a function
16function greet(name) {
17 return 'Hello, ' + name + '!';
18}
19console.log(greet('Alice'));
20
21// class — declares a class (blueprint for objects)
22class Animal {
23 constructor(name) {
24 this.name = name;
25 }
26 speak() {
27 return this.name + ' makes a sound.';
28 }
29}
30const cat = new Animal('Cat');
31console.log(cat.speak());
KeywordWhat It DoesExample
varDeclares a function-scoped variable (legacy)var name = 'Alice';
letDeclares a block-scoped variablelet age = 25;
constDeclares a block-scoped constantconst PI = 3.14;
functionDeclares a functionfunction add(a, b) { }
classDeclares a classclass User { }

Control Flow Keywords

Control Flow Keywords

These keywords control which code runs and when. They let you make decisions, repeat actions, and jump between parts of your code.

javascript
1// if / else — run code based on a condition
2const temperature = 28;
3
4if (temperature > 35) {
5 console.log('Very hot!');
6} else if (temperature > 25) {
7 console.log('Warm day.'); // this runs
8} else {
9 console.log('Cool or cold.');
10}
11
12// switch / case / default / break — choose between many options
13const day = 'Monday';
14
15switch (day) {
16 case 'Monday':
17 case 'Tuesday':
18 case 'Wednesday':
19 case 'Thursday':
20 case 'Friday':
21 console.log('Weekday — time to work!');
22 break; // stop here — do not fall through to next case
23 case 'Saturday':
24 case 'Sunday':
25 console.log('Weekend — time to rest!');
26 break;
27 default:
28 console.log('Unknown day');
29 break;
30}
javascript
1// for — repeat code a set number of times
2for (let i = 1; i <= 5; i++) {
3 if (i === 3) continue; // skip 3
4 if (i === 5) break; // stop at 5
5 console.log('for:', i); // prints 1, 2, 4
6}
7
8// while — repeat while a condition is true
9let count = 3;
10while (count > 0) {
11 console.log('while countdown:', count);
12 count--;
13}
14
15// do...while — runs at least once, then checks condition
16let attempts = 0;
17do {
18 attempts++;
19 console.log('Attempt:', attempts);
20} while (attempts < 3);
21
22// return — exits a function and gives back a value
23function multiply(a, b) {
24 return a * b; // stops the function and sends back the result
25}
26console.log('5 x 4 =', multiply(5, 4));
KeywordWhat It Does
ifRuns a block of code only when a condition is true
elseRuns when the if condition is false
switchChooses between many possible values
caseA single option inside a switch
defaultThe fallback option in a switch (when no case matches)
breakExits a switch case or a loop immediately
continueSkips the current iteration of a loop and goes to the next
forRepeats code a set number of times
whileRepeats code while a condition is true
doRuns code once, then repeats while a condition is true
returnExits a function and optionally returns a value

Error Handling Keywords

Error Handling Keywords

These keywords let you catch errors and handle them gracefully instead of letting them crash your program.

javascript
1// try — wrap code that might cause an error
2// catch — runs if an error happens inside try
3// finally — ALWAYS runs at the end, error or not
4
5function parseUserData(jsonString) {
6 try {
7 const data = JSON.parse(jsonString); // might throw SyntaxError
8 console.log('Parsed successfully:', data.name);
9 return data;
10 } catch (error) {
11 console.log('Error:', error.message); // handle the error
12 return null;
13 } finally {
14 console.log('Done — always runs.') // cleanup code
15 }
16}
17
18parseUserData('{"name": "Alice"}'); // works
19parseUserData('{ bad json }'); // caught
20
21// throw — create your own error on purpose
22function divide(a, b) {
23 if (b === 0) {
24 throw new Error('Cannot divide by zero!'); // throw keyword
25 }
26 return a / b;
27}
28
29try {
30 console.log(divide(10, 2)); // 5
31 console.log(divide(10, 0)); // throws
32} catch (e) {
33 console.log('Caught:', e.message);
34}

Value Keywords

Value Keywords — true, false, null, undefined

These keywords represent built-in values in JavaScript. They are not strings — they are actual values with a specific meaning.

javascript
1// true and false — boolean values
2const isLoggedIn = true;
3const isAdmin = false;
4
5if (isLoggedIn) {
6 console.log('Welcome back!');
7}
8console.log('isAdmin:', isAdmin);
9
10// null — intentional empty value (you set it on purpose)
11let currentUser = null; // no user yet
12console.log('currentUser:', currentUser); // null
13console.log('type of null:', typeof null); // 'object' (a famous JS quirk)
14
15// undefined — a variable exists but has no value assigned
16let notAssigned; // declared but not given a value
17console.log('notAssigned:', notAssigned); // undefined
18
19function noReturn() {
20 // no return statement
21}
22console.log('noReturn():', noReturn()); // undefined
23
24// null vs undefined
25console.log(null == undefined); // true — both mean 'empty'
26console.log(null === undefined); // false — different types

null and undefined are different

  • null means: I intentionally set this to empty. A programmer did this on purpose.
  • undefined means: this variable exists but has never been given a value.

Use null when you want to say "no value here yet" in your own code. JavaScript uses undefined automatically when something has no value.

Object & Class Keywords

Object & Class Keywords

These keywords are used when working with objects and classes — the building blocks of object-oriented JavaScript.

javascript
1// class and extends — create a class that inherits from another
2class Animal {
3 constructor(name) {
4 this.name = name; // 'this' refers to the current object
5 }
6 speak() {
7 return this.name + ' makes a sound.';
8 }
9}
10
11class Dog extends Animal { // 'extends' inherits from Animal
12 constructor(name) {
13 super(name); // 'super' calls the parent constructor
14 }
15 speak() {
16 return this.name + ' barks!';
17 }
18}
19
20// new — creates a new instance of a class or function
21const animal = new Animal('Cat');
22const dog = new Dog('Rex');
23
24console.log(animal.speak()); // Cat makes a sound.
25console.log(dog.speak()); // Rex barks!
26
27// instanceof — checks if an object is an instance of a class
28console.log(dog instanceof Dog); // true
29console.log(dog instanceof Animal); // true — because Dog extends Animal
30console.log(dog instanceof Array); // false
31
32// typeof — tells you the type of any value
33console.log(typeof 42); // 'number'
34console.log(typeof 'hello'); // 'string'
35console.log(typeof true); // 'boolean'
36console.log(typeof dog); // 'object'
37console.log(typeof undefined); // 'undefined'
38
39// delete — removes a property from an object
40const user = { name: 'Alice', age: 25, role: 'admin' };
41console.log('before:', user);
42delete user.role;
43console.log('after delete:', user); // role is gone

Module Keywords

Module Keywords — import & export

These keywords let you split your code into separate files and share code between them. This is how modern JavaScript applications are structured.

javascript
1// ── math.js — EXPORTING ───────────────────────────────────
2
3// Named export — you can have many of these
4export const PI = 3.14159;
5
6export function add(a, b) {
7 return a + b;
8}
9
10export function multiply(a, b) {
11 return a * b;
12}
13
14// Default export — only one per file
15export default function subtract(a, b) {
16 return a - b;
17}
18
19
20// ── app.js — IMPORTING ────────────────────────────────────
21
22// Import named exports — use exact name inside { }
23import { PI, add, multiply } from './math.js';
24
25// Import the default export — any name works
26import subtract from './math.js';
27
28// Import everything into one object
29import * as MathUtils from './math.js';
30
31console.log(PI); // 3.14159
32console.log(add(3, 4)); // 7
33console.log(subtract(10, 3)); // 7
34console.log(MathUtils.multiply(5, 4)); // 20
35
36// Dynamic import — load a file only when needed
37async function loadChart() {
38 const { Chart } = await import('./chart.js');
39 Chart.render();
40}

Modules are the standard in modern JavaScript

Every big JavaScript project — React apps, Node.js APIs, Vue apps — uses import and export. You will use them every day once you start building real projects. They keep your code organized by splitting it into small, focused files.

Other Important Keywords

Other Important Keywords

javascript
1// in — checks if a property exists in an object
2const person = { name: 'Alice', age: 25 };
3console.log('name' in person); // true
4console.log('salary' in person); // false
5
6// for...in — loops over object property NAMES (keys)
7for (const key in person) {
8 console.log(key + ':', person[key]);
9}
10
11// for...of — loops over VALUES in an iterable (array, string, etc.)
12const fruits = ['apple', 'banana', 'cherry'];
13for (const fruit of fruits) {
14 console.log(fruit);
15}
16
17// typeof — returns the type of a value as a string
18console.log(typeof 42); // 'number'
19console.log(typeof 'hello'); // 'string'
20console.log(typeof true); // 'boolean'
21console.log(typeof null); // 'object' (historical JS bug)
22console.log(typeof undefined); // 'undefined'
23console.log(typeof function(){}); // 'function'
24
25// void — evaluates an expression and returns undefined
26console.log(void 0); // undefined
27console.log(void 'anything'); // undefined (always undefined)
28
29// debugger — pauses code in browser DevTools (for debugging)
30// Uncomment in browser to pause here:
31// debugger;
javascript
1// async — marks a function as asynchronous (it can wait)
2// await — pauses inside an async function until a promise finishes
3
4async function fetchUserName(id) {
5 // Simulate waiting 1 second for server response
6 const result = await new Promise((resolve) => {
7 setTimeout(() => resolve({ id, name: 'Alice' }), 100);
8 });
9 return result.name;
10}
11
12// You must use await inside an async function
13async function main() {
14 const name = await fetchUserName(1);
15 console.log('Fetched user:', name); // Alice
16
17 // Without async/await, you use .then() — older style
18 fetchUserName(2).then(n => console.log('Then style:', n));
19}
20
21main();
22console.log('This runs while waiting for main() to finish.');
KeywordWhat It Does
inChecks if a key exists in an object
ofUsed in for...of to loop over values
typeofReturns the type of a value as a string
instanceofChecks if an object was created from a class
voidEvaluates an expression and returns undefined
deleteRemoves a property from an object
debuggerPauses execution in browser DevTools
asyncMarks a function as asynchronous
awaitWaits for a Promise to finish inside an async function
yieldPauses a generator function and returns a value
withExtends the scope chain (deprecated — do not use)

Future Reserved Keywords

Future Reserved Keywords — Avoid These Too

Some words are reserved for future use — they are not keywords today, but JavaScript plans to use them later. If you use them as variable names today, your code may break when JavaScript updates.

Always avoid using these words as identifiers.

Complete Keyword List

Complete JavaScript Keyword List

Here is every reserved keyword in JavaScript. You cannot use any of these as a variable name, function name, or class name.

KeywordCategoryWhat It Does
breakControl FlowExits a loop or switch immediately
caseControl FlowA condition inside a switch statement
catchError HandlingHandles errors from a try block
classDeclarationDeclares a class (blueprint for objects)
constDeclarationDeclares a constant — cannot be reassigned
continueControl FlowSkips to the next loop iteration
debuggerDebuggingPauses code in browser DevTools
defaultControl FlowFallback in a switch when no case matches
deleteOperatorRemoves a property from an object
doControl FlowStarts a do...while loop
elseControl FlowRuns when an if condition is false
exportModulesMakes a value available for import in other files
extendsClassesMakes a class inherit from another class
falseValueBoolean false value
finallyError HandlingRuns after try/catch regardless of errors
forControl FlowStarts a loop
functionDeclarationDeclares a function
ifControl FlowRuns code only when a condition is true
importModulesLoads exports from another file
inOperatorChecks if a property exists in an object
instanceofOperatorChecks if an object was created from a class
letDeclarationDeclares a block-scoped variable
newOperatorCreates a new object from a class or constructor
nullValueIntentional absence of a value
returnControl FlowExits a function and returns a value
staticClassesDefines a method that belongs to the class itself
superClassesCalls the parent class constructor or methods
switchControl FlowChooses between multiple cases based on a value
thisObjectRefers to the current object
throwError HandlingCreates and throws an error
trueValueBoolean true value
tryError HandlingWraps code that might throw an error
typeofOperatorReturns the type of a value as a string
varDeclarationDeclares a function-scoped variable (legacy)
voidOperatorEvaluates expression and returns undefined
whileControl FlowRepeats code while a condition is true
withScopeDeprecated — do not use
yieldGeneratorPauses a generator function
asyncAsyncMarks a function as asynchronous
awaitAsyncWaits for a Promise inside an async function

Test Your Knowledge

Test Your Knowledge

Quick Check

What happens if you try to use a reserved keyword as a variable name?

Quick Check

Which of these variable names is NOT allowed?

Quick Check

What is the difference between null and undefined?

Quick Check

Which keyword do you use to stop a loop immediately?

Quick Check

What does the typeof keyword return for null?

Quick Reference

Reserved Keywords — Quick Reference

Pro Tips
  • 1Reserved keywords are words JavaScript uses for its own grammar. You cannot use them as variable or function names.
  • 2Using a keyword as a name causes a SyntaxError — the code will not run at all.
  • 3You CAN use a keyword as part of a longer name: letValue, myClass, forLoop are all valid.
  • 4Keywords as object property keys are allowed: obj.class, obj.if, obj.for all work.
  • 5Also avoid future reserved words like enum, implements, interface — they may become keywords later.
  • 6null and undefined are both 'no value' — but null is intentional, undefined is automatic.
  • 7typeof null returns 'object' — this is a historical bug. Use === null to check for null.
  • 8ES Modules and class bodies are always in strict mode — future keywords cause errors there.
Continue Learning
🏷️

Identifiers & Naming

The full rules for naming variables, functions, and classes in JavaScript.

📦

Variables — let, const, var

How to store values in JavaScript and the key differences between let, const, and var.

🔀

Control Flow

if/else, switch, and loops — using control flow keywords in real programs.

Async & Await

How async and await work — the modern way to handle asynchronous JavaScript.

You know JavaScript reserved keywords!

You now know every reserved keyword in JavaScript, what each one does, and why you cannot use them as names. More importantly, you know how to USE these keywords to write real programs. Every keyword you learned here — if, for, function, class, async, await — is something you will use every single day as a JavaScript developer.

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning