Last updated
JavaScript Formatter Examples
The JavaScript Formatter applies consistent indentation, spacing, and style rules to JavaScript code. Below are before-and-after examples for common formatting scenarios and style guide options.
Example: Inconsistent Spacing and Indentation
// Before:
function fetchUser(id){
const url=`/api/users/${id}`
return fetch(url)
.then(res=>res.json())
.then(data=>{
if(!data.active){throw new Error('User inactive')}
return data
})
}
// After (Prettier style, 2-space indent):
function fetchUser(id) {
const url = `/api/users/${id}`;
return fetch(url)
.then(res => res.json())
.then(data => {
if (!data.active) {
throw new Error('User inactive');
}
return data;
});
}
Example: Object and Array Formatting
// Before:
const config={host:'localhost',port:3000,database:{name:'mydb',pool:{min:2,max:10}},options:{ssl:true,timeout:5000}}
// After:
const config = {
host: 'localhost',
port: 3000,
database: {
name: 'mydb',
pool: {
min: 2,
max: 10
}
},
options: {
ssl: true,
timeout: 5000
}
};
Example: Import Statement Formatting
// Before:
import React,{useState,useEffect,useCallback,useMemo,useRef} from 'react'
import {BrowserRouter as Router,Route,Switch,Redirect,Link,NavLink} from 'react-router-dom'
// After:
import React, {
useState,
useEffect,
useCallback,
useMemo,
useRef
} from 'react';
import {
BrowserRouter as Router,
Route,
Switch,
Redirect,
Link,
NavLink
} from 'react-router-dom';
Example: Ternary and Conditional Formatting
// Before:
const message=isLoggedIn?isAdmin?'Welcome, Admin!':'Welcome back!':'Please log in'
// After:
const message = isLoggedIn
? isAdmin
? 'Welcome, Admin!'
: 'Welcome back!'
: 'Please log in';
Example: Function Call Argument Formatting
// Before:
createServer({host:'0.0.0.0',port:8080,middleware:[cors(),helmet(),express.json(),express.urlencoded({extended:true})],errorHandler:customErrorHandler})
// After:
createServer({
host: '0.0.0.0',
port: 8080,
middleware: [
cors(),
helmet(),
express.json(),
express.urlencoded({ extended: true })
],
errorHandler: customErrorHandler
});
Style Guide Comparison
// Same code formatted with different style guides:
// Prettier (default):
function greet(name) {
return `Hello, ${name}!`;
}
// Airbnb (single quotes, semicolons, trailing commas):
function greet(name) {
return `Hello, ${name}!`;
}
// Standard (no semicolons):
function greet (name) {
return `Hello, ${name}!`
}
// Google (4-space indent, single quotes):
function greet(name) {
return `Hello, ${name}!`;
}
Example: Semicolon Handling
// Before (inconsistent semicolons):
const a = 1
const b = 2;
function add(x, y) {
return x + y
}
const result = add(a, b);
// After (semicolons always):
const a = 1;
const b = 2;
function add(x, y) {
return x + y;
}
const result = add(a, b);
// After (semicolons never — Standard style):
const a = 1
const b = 2
function add(x, y) {
return x + y
}
const result = add(a, b)
Example: Trailing Commas
// Before (no trailing commas):
const obj = {
name: 'Alice',
age: 30,
city: 'New York'
};
// After (ES5 trailing commas — cleaner git diffs):
const obj = {
name: 'Alice',
age: 30,
city: 'New York', // ← trailing comma
};
// Function parameters with trailing commas (ES2017+):
function createUser(
name,
email,
role, // ← trailing comma
) {
// ...
}
Diff View Example
Changes made by formatter:
1 | function add(a,b){ → function add(a, b) {
2 | return a+b → return a + b;
3 | } → }
Lines changed: 3
Characters added: 5 (spaces and semicolon)
Characters removed: 0
No logic changes — formatting only.
TypeScript Formatting Example
// Before:
interface ApiResponse<T>{data:T;error:string|null;status:number;timestamp:Date}
async function get<T>(url:string,options?:RequestInit):Promise<ApiResponse<T>>{
const res=await fetch(url,options)
if(!res.ok)return{data:null as T,error:res.statusText,status:res.status,timestamp:new Date()}
const data=await res.json() as T
return{data,error:null,status:res.status,timestamp:new Date()}}
// After:
interface ApiResponse<T> {
data: T;
error: string | null;
status: number;
timestamp: Date;
}
async function get<T>(
url: string,
options?: RequestInit
): Promise<ApiResponse<T>> {
const res = await fetch(url, options);
if (!res.ok) {
return {
data: null as T,
error: res.statusText,
status: res.status,
timestamp: new Date()
};
}
const data = (await res.json()) as T;
return { data, error: null, status: res.status, timestamp: new Date() };
}
Paste your JavaScript or TypeScript code, choose a style guide, and get consistently formatted output. The formatter never changes your logic — only the whitespace and style.