JavaScript's Reserved Keywords

JavaScript has a set of reserved words known as keywords, which are predefined by the JavaScript engine for specific purposes. These words are essential to the language's syntax and cannot be used as variable names, function names, or identifiers. In this guide, we'll explore the full list of JavaScript keywords and how they are used in programming.


JavaScript Reserved Keywords

The following is a list of all reserved keywords in JavaScript. These keywords are part of the JavaScript language syntax and serve specific purposes. They cannot be used as variable names, function names, or identifiers:

breakcasecatchclassconst
continuedebuggerdefaultdeletedo
elseexportextendsfinallyfor
functionifimportininstanceof
letnewreturnsuperswitch
throwtrytypeofvarvoid
whilewithyield

These are the reserved keywords in JavaScript as of the latest version. You cannot use any of these as identifiers (such as variable names, function names, or class names) because they have specific meanings and purposes in the JavaScript language.

1. break

The break keyword is used to exit from a loop or a switch statement before it completes all its iterations or cases. When the break statement is encountered, the program immediately exits the loop or switch block.

This is useful when you want to stop the loop or switch as soon as a specific condition is met, saving time and resources.

Common uses:

  • Exiting from a for, while, or do...while loop early.
  • Breaking out of a switch statement to prevent further case evaluations.

In the example below, the program exits the loop when the value of x reaches 5:

javascript
let x = 0;

while (x < 10) {
  if (x === 5) {
    break;  // Exit the loop when x equals 5
  }
  console.log(x);
  x++;
}

// Output: 0, 1, 2, 3, 4

2. case

The case keyword is used within a switch statement to define multiple conditions that are evaluated. Each case represents a possible match for the value being tested in the switch block.

This is useful for handling multiple potential conditions with a single switch block, making your code more readable and efficient.

Common uses:

  • Evaluating multiple possible values in a switch statement.
  • Organizing conditions into clear cases.

In the example below, the program checks the value of fruit and matches it to one of the case conditions:

let fruit = "apple";

switch(fruit) {
  case "apple":
    console.log("It's an apple!");
    break;
  case "banana":
    console.log("It's a banana!");
    break;
  default:
    console.log("Unknown fruit.");
},// Output: It's an apple!

3. catch

The catch keyword is used in conjunction with the try keyword to handle exceptions in JavaScript. Code inside a catch block is executed if an error occurs within the corresponding try block.

This is helpful for gracefully handling runtime errors without crashing the application.

Common uses:

  • Handling errors that occur within a try block.
  • Providing alternative code execution when exceptions are thrown.

In the example below, the program catches any errors that occur when attempting to parse an invalid JSON string:

try {
  let data = JSON.parse('{"name": "John"');  // Invalid JSON
} catch (error) {
  console.log("Error parsing JSON: ", error.message);
},// Output: Error parsing JSON:  Unexpected end of input

4. class

The class keyword is used to define a class in JavaScript. A class is a blueprint for creating objects with shared properties and methods.

Classes allow you to create reusable structures, making your code modular and easier to manage.

Common uses:

  • Defining reusable objects with properties and methods.
  • Creating constructor functions to initialize class instances.

In the example below, a class is used to define a Person with a name and a greeting method:

class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log("Hello, " + this.name);
  }
}

const person1 = new Person("John");
person1.greet();  // Output: Hello, John

5. const

The const keyword is used to declare variables whose values cannot be reassigned after initialization. Once a variable is assigned with const, its value remains constant throughout its scope.

This helps prevent accidental reassignment of variables, making your code more predictable and reducing potential bugs.

Common uses:

  • Declaring variables that should not change their value.
  • Ensuring that an object or array reference does not change.

In the example below, the const variable pi cannot be reassigned once it is initialized:

const pi = 3.14159;
console.log(pi);  // Output: 3.14159

// Reassigning pi will throw an error
// pi = 3.14;  // Uncaught TypeError: Assignment to constant variable.

6. continue

The continue keyword is used to skip the current iteration of a loop and move to the next one. When continue is encountered, the remaining code in the loop is skipped for the current iteration.

This is useful when you want to skip certain iterations of the loop based on specific conditions, while still executing the rest of the loop.

Common uses:

  • Skipping an iteration when a specific condition is met in a loop.
  • Improving loop efficiency by avoiding unnecessary code execution.

In the example below, the program skips printing even numbers in the loop:

for (let i = 0; i < 10; i++) {
  if (i % 2 === 0) {
    continue;  // Skip even numbers
  }
  console.log(i);  // Output: 1, 3, 5, 7, 9
}

7. debugger

The debugger keyword is used to pause the execution of JavaScript code and start the debugging process. When debugger is encountered, it causes the code to stop executing, allowing developers to inspect variables and the call stack.

This is useful for troubleshooting and analyzing code behavior during development, especially in complex applications.

Common uses:

  • Pausing execution during development to inspect code state.
  • Helping in debugging issues with code flow or variables.

In the example below, the execution will stop at the debugger statement, allowing the developer to inspect the state:

function calculateSum(a, b) {
  let sum = a + b;
  debugger;  // Execution will pause here
  return sum;
}

calculateSum(5, 3);

8. default

The default keyword is used in a switch statement to define the default block of code that runs when no case matches the value being evaluated.

It acts as a fallback for the switch statement when none of the conditions are met.

Common uses:

  • Specifying a fallback case in a switch statement.
  • Handling unexpected values when no matching case is found.

In the example below, the default block runs if the value doesn't match any of the cases:

let day = 3;

switch(day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  default:
    console.log("Unknown day");
    // Output: Unknown day
}

9. delete

The delete keyword is used to remove a property from an object or an element from an array. It can also be used to delete variables (although it is not typically recommended).

This is useful when you want to dynamically remove properties or values that are no longer needed, making the code more flexible and efficient.

Common uses:

  • Removing properties from an object.
  • Deleting array elements while maintaining array integrity.

In the example below, the property age is deleted from the person object:

let person = { name: "John", age: 30 };

delete person.age;

console.log(person);  // Output: { name: "John" }

10. do

The do keyword is used in a do...while loop to execute a block of code at least once before checking the condition. The loop will keep running as long as the condition specified in the while is true.

This is useful when you want to ensure the code is executed at least once, even if the condition is false on the first iteration.

Common uses:

  • Executing code at least once before checking the condition.
  • When you need a loop that runs before evaluating the condition.

In the example below, the code is executed once before checking the condition:

let i = 0;

do {
  console.log(i);
  i++;
} while (i < 5);
// Output: 0, 1, 2, 3, 4

11. else

The else keyword is used in conditional statements like if to define an alternative block of code that will execute when the condition evaluates to false.

It allows you to specify what should happen when the initial if condition isn't met.

Common uses:

  • Defining an alternative action when an if condition fails.
  • Ensuring that some code is always executed when the condition is false.

In the example below, if the condition is not true, the else block is executed:

let number = 10;

if (number > 20) {
  console.log("Number is greater than 20");
} else {
  console.log("Number is less than or equal to 20");  // Output: Number is less than or equal to 20
}

12. export

The export keyword is used in JavaScript modules to make functions, objects, or values available for import in other modules. This is part of ES6 module system, which helps in creating modular code that can be reused across different parts of an application.

This allows you to split your code into smaller files and import them wherever they are needed.

Common uses:

  • Exporting variables, functions, or classes to be used in other modules.
  • Creating reusable and maintainable code in separate files.

In the example below, a function is exported from one module and imported into another:

// module.js
export function greet(name) {
  return "Hello " + name;
}

// app.js
import { greet } from './module.js';
console.log(greet("Tom"));  // Output: Hello Tom

13. extends

The extends keyword is used in JavaScript to create a class that is a child of another class, thereby inheriting its properties and methods. This is a key feature of object-oriented programming (OOP) that enables the creation of hierarchies of classes.

It allows for code reuse and makes it easier to maintain and extend classes without rewriting code.

Common uses:

  • Creating a subclass that inherits properties and methods from a superclass.
  • Enabling polymorphism in JavaScript.

In the example below, a new class Dog extends the functionality of a superclass Animal:

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(this.name + " makes a sound");
  }
}

class Dog extends Animal {
  speak() {
    console.log(this.name + " barks");
  }
}

const dog = new Dog("Buddy");
dog.speak();  // Output: Buddy barks

14. finally

The finally keyword is used in a try...catch block to define a section of code that will always be executed, regardless of whether an exception is thrown or not. It is often used for cleanup actions like closing files, releasing resources, or resetting states.

This guarantees that certain operations are performed even if an error occurs in the try block.

Common uses:

  • Ensuring that clean-up code is always executed, regardless of success or failure.
  • Handling code that needs to run after both successful and unsuccessful executions.

In the example below, the finally block is always executed, whether or not an error occurs:

try {
  let result = riskyOperation();
} catch (error) {
  console.log("Error occurred:", error);
} finally {
  console.log("This will always run.");
  // Output: This will always run.
}

15. for

The for keyword is used to create a loop that will repeat a block of code a specified number of times. It allows you to control the iteration of a code block by specifying a start condition, an end condition, and the step (increment or decrement).

This is commonly used for iterating over arrays or performing actions multiple times based on a condition.

Common uses:

  • Iterating through elements in an array or list.
  • Performing repeated actions for a known number of times.

In the example below, the program prints numbers from 0 to 4 using a for loop:

for (let i = 0; i < 5; i++) {
  console.log(i);  // Output: 0, 1, 2, 3, 4
}

16. function

The function keyword is used to define a function in JavaScript. A function is a block of reusable code that performs a specific task. Functions can take input parameters and return a result.

Functions help in breaking down complex tasks into smaller, more manageable parts, and they allow for code reusability.

Common uses:

  • Defining reusable blocks of code.
  • Breaking down complex logic into smaller parts.
  • Accepting inputs and returning values.

In the example below, a simple function is defined to add two numbers:

function add(a, b) {
  return a + b;
}

console.log(add(3, 4));  // Output: 7

17. if

The if keyword is used to perform a conditional check in JavaScript. It allows you to execute a block of code only if a specified condition is true. If the condition evaluates to true, the block inside the if statement runs.

This is useful for controlling the flow of your program, ensuring that certain operations are only performed when specific conditions are met.

Common uses:

  • Performing actions based on conditional logic.
  • Controlling program flow depending on user input or other conditions.

In the example below, the program checks if a number is positive before printing a message:

let number = 10;

if (number > 0) {
  console.log("Number is positive");  // Output: Number is positive
}

18. import

The import keyword is used to bring in functions, objects, or values from other modules into the current file. This is part of JavaScript's ES6 module system and helps in organizing code into modular, reusable parts.

The import statement allows you to manage dependencies between files in a clean and organized manner.

Common uses:

  • Importing functions or variables from external files.
  • Creating modular code that can be reused across different files.

In the example below, a function is imported from another file and used:

// utils.js
export function greet(name) {
  return "Hello " + name;
}

// main.js
import { greet } from './utils.js';
console.log(greet("Tom"));  // Output: Hello Tom

19. in

The in keyword is used to check if a specified property exists in an object or if an element exists in an array. It's commonly used in loops and conditional checks.

The in operator is versatile, allowing for both property checking and iterating through elements in arrays or objects.

Common uses:

  • Checking if a property exists in an object.
  • Looping through the properties of an object or elements of an array.

In the example below, the in operator is used to check if a property exists in an object:

const person = {
  name: "John",
  age: 30
};

console.log("name" in person);  // Output: true
console.log("address" in person);  // Output: false

20. instanceof

The instanceof keyword is used to check if an object is an instance of a specific class or constructor function. It is typically used to ensure that an object is an instance of a particular class or subclass before calling its methods or accessing its properties.

This is particularly useful when working with inheritance and object-oriented programming in JavaScript.

Common uses:

  • Checking an object's type or class before performing operations on it.
  • Ensuring type safety when working with objects in a class hierarchy.

In the example below, the instanceof operator is used to check if an object is an instance of a class:

class Animal {}
class Dog extends Animal {}

const dog = new Dog();
console.log(dog instanceof Dog);  // Output: true
console.log(dog instanceof Animal);  // Output: true
console.log(dog instanceof Object);  // Output: true

21. let

The let keyword is used to declare block-scoped variables in JavaScript. Unlike var, it does not allow redeclaration in the same scope and respects lexical scoping rules.

It is commonly used to declare variables that are meant to have limited scope within blocks such as if statements or for loops.

Common uses:

  • Declaring variables within a specific block or function scope.
  • Avoiding hoisting issues and accidental redeclarations.

Example:

let x = 10;
if (true) {
  let x = 20; // Different variable than the one outside the block
  console.log(x); // Output: 20
}
console.log(x); // Output: 10

22. new

The new keyword is used to create instances of objects that have a constructor function or class. It initializes a new object and sets the constructor’s prototype as the new object’s prototype.

This is fundamental in object-oriented JavaScript when creating instances from classes or constructor functions.

Common uses:

  • Creating instances of user-defined objects or classes.
  • Instantiating built-in object types such as Date or RegExp.

Example:

class Person {
  constructor(name) {
    this.name = name;
  }
}

const tom = new Person('Tom');
console.log(tom.name); // Output: Tom

23. return

The return keyword is used to exit from a function and optionally pass back a value to the function caller.

It's essential in any function that needs to compute and deliver a result to the place where the function was called.

Common uses:

  • Returning values from functions.
  • Exiting a function early based on certain conditions.

Example:

function add(a, b) {
  return a + b;
}

const result = add(3, 4);
console.log(result); // Output: 7

24. super

The super keyword is used to call the constructor or methods of a parent class. It is used inside a subclass to access functionality defined in its superclass.

You must call super() before using this in a subclass constructor.

Common uses:

  • Calling the parent class constructor in a derived class.
  • Accessing overridden methods from the superclass.

Example:

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    return `${this.name} makes a sound.`;
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name);
  }

  speak() {
    return super.speak() + ' Woof!';
  }
}

const dog = new Dog('Buddy');
console.log(dog.speak()); // Output: Buddy makes a sound. Woof!

25. switch

The switch statement allows for multi-branch conditional logic by evaluating an expression and matching its value against multiple case clauses.

It's often used as a cleaner alternative to multiple if-else statements when checking a single value against many possibilities.

Common uses:

  • Handling multiple potential values of a single variable.
  • Replacing complex conditional branching logic.

Example:

const color = 'blue';

switch (color) {
  case 'red':
    console.log('Red color');
    break;
  case 'blue':
    console.log('Blue color');
    break;
  default:
    console.log('Unknown color');
}

26. throw

The throw keyword is used to raise a custom exception or error in JavaScript. It allows you to signal that something unexpected has occurred during execution.

You can throw any expression, but it's best practice to throw an instance of the Error class or its subclasses.

Common uses:

  • Raising custom exceptions in your code.
  • Stopping execution when a condition is not met.

Example:

function divide(a, b) {
  if (b === 0) {
    throw new Error("Division by zero is not allowed.");
  }
  return a / b;
}

try {
  console.log(divide(4, 0));
} catch (e) {
  console.error(e.message); // Output: Division by zero is not allowed.
}

27. try

The try block is used to wrap code that might throw an exception. If an error occurs, control is passed to the catch block, allowing you to handle the error gracefully.

Optionally, a finally block can be added to run code after the try-catch, regardless of whether an error occurred.

Common uses:

  • Handling runtime errors without stopping execution.
  • Ensuring cleanup with finally blocks.

Example:

try {
  JSON.parse('invalid JSON');
} catch (error) {
  console.error("Parsing error:", error.message);
} finally {
  console.log("Attempted to parse JSON.");
}

28. typeof

The typeof operator is used to determine the type of a given operand. It returns a string indicating the type of the unevaluated operand.

It is especially useful for checking if a variable is a number, string, boolean, function, etc.

Common uses:

  • Type-checking before performing operations.
  • Debugging and inspecting variable types at runtime.

Example:

console.log(typeof 42);         // Output: "number"
console.log(typeof 'hello');    // Output: "string"
console.log(typeof true);       // Output: "boolean"
console.log(typeof {});         // Output: "object"
console.log(typeof undefined);  // Output: "undefined"
console.log(typeof null);       // Output: "object" (quirk)

29. var

The var keyword is used to declare variables in JavaScript. It has function scope rather than block scope, and allows redeclaration.

Although var is still valid, it has largely been replaced by let and const in modern JavaScript due to more predictable scoping.

Common uses:

  • Legacy codebases or compatibility with older JavaScript versions.
  • Function-scoped variables in older code.

Example:

function example() {
  if (true) {
    var x = 10;
  }
  console.log(x); // Output: 10 (function scoped)
}

example();

30. void

The void operator evaluates an expression and returns undefined regardless of the expression's result.

It's commonly used to avoid unwanted return values or in contexts like HTML hyperlinks where you want to prevent navigation.

Common uses:

  • Suppressing a return value intentionally.
  • Preventing navigation in anchor tags with javascript:void(0).

Example:

console.log(void 0);         // Output: undefined
console.log(void (2 + 2));    // Output: undefined

// In HTML: <a href="javascript:void(0)">Click me</a>

31. while

The while loop executes a block of code as long as the specified condition evaluates to true. The condition is evaluated before each iteration.

It is useful when the number of iterations is not known in advance and depends on dynamic conditions.

Common uses:

  • Repeating operations until a condition changes.
  • Polling or waiting for events or responses.

Example:

let count = 0;
while (count < 3) {
  console.log('Count:', count);
  count++;
}
// Output:
// Count: 0
// Count: 1
// Count: 2

32. with (deprecated)

The with statement extends the scope chain for a statement block, allowing for shorter syntax when accessing properties of a specific object.

⚠️ Deprecated: The use of with is discouraged as it makes code harder to understand and debug. It is forbidden in strict mode and should be avoided in modern JavaScript.

Common (legacy) uses:

  • Simplifying repeated property access on a single object (now discouraged).

Example (not recommended):

const obj = { a: 1, b: 2 };

with (obj) {
  console.log(a); // Output: 1
  console.log(b); // Output: 2
}

// Not allowed in strict mode

33. yield

The yield keyword is used inside a generator function to pause its execution and return a value. Execution can later be resumed from where it was paused.

It allows functions to generate a sequence of values over time, making it useful for lazy evaluation and asynchronous workflows.

Common uses:

  • Creating iterators using generator functions.
  • Controlling execution flow in asynchronous code with generators (e.g. in frameworks like Redux-Saga).

Example:

function* counter() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = counter();
console.log(gen.next().value); // Output: 1
console.log(gen.next().value); // Output: 2
console.log(gen.next().value); // Output: 3

What's Next?

Up next: Errors and exceptions in JavaScript—understand what goes wrong in your code and how to fix it without getting stuck.