PromptHub
JavaScript Beginner 14 views

SyntaxError: Unexpected Token

JavaScript parser encountered a token it didn't expect at that position.

Explanation

SyntaxError: Unexpected Token occurs when the JavaScript parser encounters a character or sequence of characters that it doesn't expect at that position in the code. This is a parse-time error that prevents the code from running at all. Common causes include missing commas in object literals, unmatched brackets or parentheses, using reserved words as identifiers, missing colons in objects, and incorrect template literal syntax. In Node.js, this often happens when trying to run ES module syntax in a CommonJS file.

Common Causes

  • Missing comma in objects/arrays
  • Unmatched brackets or parentheses
  • Using reserved words as identifiers
  • Template literal syntax error
  • ES module syntax in CommonJS

Solution

Check the line number and position indicated in the error message. Verify all brackets, parentheses, and braces are properly matched. Check for missing commas between object properties or array elements. Ensure template literals use backticks, not quotes. For Node.js ES module syntax errors, ensure package.json has "type": "module". Use an IDE with JavaScript syntax highlighting to catch errors in real-time. Run node --check filename.js to syntax check without execution.

Code Example

// Missing comma in object literal
const config = {
    host: 'localhost'
    port: 3000  // Unexpected token - missing comma!
}

// Fix
const config = {
    host: 'localhost',
    port: 3000
}

// Unmatched bracket
const arr = [1, 2, 3;  // Unexpected token

// Fix
const arr = [1, 2, 3];

// ES module syntax in CommonJS file
import express from 'express';  // SyntaxError in .js with no type:module

// Fix: use require()
const express = require('express');

// Or add to package.json
// { "type": "module" }

// Check syntax without running
node --check script.js

Error Information

Language

javascript

Difficulty

Beginner

Views

14

Related Errors