Code Examples & Syntax HighlightingLink to section

This page demonstrates various ways to display code, from simple inline snippets to complex multi-language code blocks with syntax highlighting.

Inline CodeLink to section

Basic UsageLink to section

Use backticks for inline code snippets within text:

  • Variable names: userName, isAuthenticated, MAX_RETRIES
  • Function calls: calculateTotal(), array.map(), console.log()
  • File names: package.json, tsconfig.json, .env.local
  • Commands: npm install, git commit -m "message", python app.py
  • Configuration values: port: 3000, NODE_ENV=production

Inline Code in Different ContextsLink to section

The Array.prototype.reduce() method executes a reducer function on each element of the array. You can call it like array.reduce(reducer, initialValue).

Common Git commands:

  • git status - Check repository status
  • git add . - Stage all changes
  • git commit -m "message" - Commit with message
  • git push origin main - Push to remote

Escaping BackticksLink to section

To show literal backticks: `backticks` are created using double backticks.

To show code with backticks: ``const str = `template literal`;``

Code BlocksLink to section

Basic Code BlockLink to section

Without language specification:

This is a plain code block
No syntax highlighting applied
Useful for:
- Terminal output
- Log files
- Plain text examples

Language ShowcaseLink to section

JavaScriptLink to section

// Modern JavaScript with ES6+ features
const greet = (name = 'World') => {
console.log(`Hello, ${name}!`);
return { message: `Greeting sent to ${name}`, timestamp: Date.now() };
};
// Async/await example
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to fetch user:', error);
throw error;
}
}
// Class with private fields
class User {
#id;
#name;
constructor(id, name) {
this.#id = id;
this.#name = name;
}
get name() {
return this.#name;
}
}

TypeScriptLink to section

// Interface definition
interface User {
id: number;
name: string;
email?: string;
roles: Role[];
}
// Type alias
type Role = 'admin' | 'user' | 'guest';
// Generic function
function processArray<T>(items: T[], processor: (item: T) => void): void {
items.forEach(processor);
}
// Decorator
function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Calling ${propertyKey} with args:`, args);
return original.apply(this, args);
};
}
// Class with decorators
class ApiService {
@log
async fetchData(endpoint: string): Promise<any> {
const response = await fetch(endpoint);
return response.json();
}
}

PythonLink to section

# Import statements
import asyncio
from typing import List, Optional, Dict
from dataclasses import dataclass
# Dataclass example
@dataclass
class User:
id: int
name: str
email: Optional[str] = None
def __post_init__(self):
self.username = self.name.lower().replace(' ', '_')
# Async function with type hints
async def fetch_users(ids: List[int]) -> List[User]:
"""Fetch multiple users concurrently."""
tasks = [fetch_user(id) for id in ids]
return await asyncio.gather(*tasks)
# Context manager
class DatabaseConnection:
def __enter__(self):
self.connection = create_connection()
return self.connection
def __exit__(self, exc_type, exc_val, exc_tb):
self.connection.close()
# Generator with yield
def fibonacci(n: int):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b

React/JSXLink to section

import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
// Functional component with hooks
const UserProfile = ({ userId }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchUser(userId)
.then(setUser)
.finally(() => setLoading(false));
}, [userId]);
if (loading) {
return <div className="spinner">Loading...</div>;
}
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="user-profile"
>
<h2>{user.name}</h2>
<p>{user.bio}</p>
<div className="stats">
<span>Followers: {user.followers}</span>
<span>Following: {user.following}</span>
</div>
</motion.div>
);
};
export default UserProfile;

CSS/SCSSLink to section

// Variables and mixins
$primary-color: #3490dc;
$secondary-color: #ffed4a;
$breakpoint-md: 768px;
@mixin button-style($bg-color) {
background-color: $bg-color;
color: white;
padding: 0.5rem 1rem;
border: none;
border-radius: 0.25rem;
cursor: pointer;
transition: all 0.3s ease;
&:hover {
background-color: darken($bg-color, 10%);
transform: translateY(-2px);
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
&:active {
transform: translateY(0);
}
}
// Component styles
.user-profile {
display: grid;
grid-template-columns: auto 1fr;
gap: 2rem;
padding: 2rem;
@media (max-width: $breakpoint-md) {
grid-template-columns: 1fr;
}
.avatar {
width: 120px;
height: 120px;
border-radius: 50%;
object-fit: cover;
}
.info {
h2 {
margin: 0 0 0.5rem;
color: $primary-color;
}
.bio {
color: #666;
line-height: 1.6;
}
}
}

Shell/BashLink to section

#!/bin/bash
# Script configuration
set -euo pipefail
IFS=$'\n\t'
# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Function to log messages
log() {
echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}
error() {
echo -e "${RED}[ERROR]${NC} $1" >&2
exit 1
}
# Check dependencies
check_dependencies() {
local deps=("git" "node" "npm")
for dep in "${deps[@]}"; do
if ! command -v "$dep" &> /dev/null; then
error "$dep is required but not installed"
fi
done
}
# Main deployment function
deploy() {
local environment="${1:-production}"
log "Starting deployment to $environment"
# Build the project
npm run build || error "Build failed"
# Run tests
npm test || error "Tests failed"
# Deploy based on environment
case $environment in
production)
rsync -avz --delete dist/ user@production:/var/www/
;;
staging)
rsync -avz --delete dist/ user@staging:/var/www/
;;
*)
error "Unknown environment: $environment"
;;
esac
log "Deployment completed successfully"
}
# Parse command line arguments
while getopts "e:h" opt; do
case $opt in
e) ENV="$OPTARG";;
h) echo "Usage: $0 [-e environment]"; exit 0;;
\?) error "Invalid option: -$OPTARG";;
esac
done
# Run the deployment
check_dependencies
deploy "${ENV:-production}"

SQLLink to section

-- Create tables with constraints
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
content TEXT,
published BOOLEAN DEFAULT FALSE,
published_at TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Create indexes
CREATE INDEX idx_posts_user_id ON posts(user_id);
CREATE INDEX idx_posts_published ON posts(published, published_at DESC);
-- Complex query with CTEs
WITH user_stats AS (
SELECT
u.id,
u.username,
COUNT(p.id) as post_count,
COUNT(CASE WHEN p.published THEN 1 END) as published_count
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
GROUP BY u.id, u.username
),
recent_posts AS (
SELECT
user_id,
title,
published_at,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY published_at DESC) as rn
FROM posts
WHERE published = TRUE
)
SELECT
us.*,
rp.title as latest_post_title,
rp.published_at as latest_post_date
FROM user_stats us
LEFT JOIN recent_posts rp ON us.id = rp.user_id AND rp.rn = 1
WHERE us.post_count > 0
ORDER BY us.published_count DESC, us.username;

YAMLLink to section

# Docker Compose configuration
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
NODE_ENV: production
DATABASE_URL: ${DATABASE_URL}
volumes:
- ./data:/app/data
depends_on:
- postgres
- redis
postgres:
image: postgres:15
environment:
POSTGRES_DB: myapp
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
command: redis-server --appendonly yes
volumes:
postgres_data:

JSONLink to section

{
"name": "my-application",
"version": "1.0.0",
"description": "A sample application configuration",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest --coverage",
"build": "webpack --mode production"
},
"dependencies": {
"express": "^4.18.0",
"mongoose": "^6.0.0",
"jsonwebtoken": "^8.5.1"
},
"devDependencies": {
"jest": "^27.0.0",
"nodemon": "^2.0.0",
"webpack": "^5.0.0"
},
"config": {
"api": {
"baseUrl": "https://api.example.com",
"timeout": 5000,
"retries": 3
}
}
}

Special Code PatternsLink to section

Terminal SessionsLink to section

Terminal window
$ npm init -y
Wrote to /home/user/project/package.json:
{
"name": "project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
$ npm install express
added 57 packages, and audited 58 packages in 2s
$ npm install --save-dev nodemon
added 34 packages, and audited 92 packages in 1s

File TreesLink to section

project/
├── src/
│ ├── components/
│ │ ├── Button.tsx
│ │ ├── Card.tsx
│ │ └── index.ts
│ ├── utils/
│ │ ├── api.ts
│ │ └── helpers.ts
│ ├── App.tsx
│ └── index.tsx
├── public/
│ └── index.html
├── package.json
├── tsconfig.json
└── README.md

ASCII Art in Code BlocksLink to section

┌─────────────────────────────────────┐
│ │
│ Welcome to Code Block Examples │
│ │
├─────────────────────────────────────┤
│ │
│ • Syntax Highlighting │
│ • Multiple Languages │
│ • Clear Formatting │
│ │
└─────────────────────────────────────┘

Diff FormatLink to section

const oldFunction = () => {
console.log('This is the old implementation');
};
const newFunction = () => {
console.log('This is the new implementation');
console.log('With additional features');
};
// Unchanged code
const helper = () => {
return 'Helper function';
};

Best PracticesLink to section

For Inline CodeLink to section

  1. Use for short snippets (1-3 words typically)
  2. Don’t use for multi-line code
  3. Good for: variables, functions, file names, commands
  4. Consider readability in the sentence flow

For Code BlocksLink to section

  1. Always specify the language for proper syntax highlighting
  2. Keep examples concise but complete
  3. Add comments to explain complex logic
  4. Use meaningful variable names in examples
  5. Format code consistently with proper indentation

AccessibilityLink to section

  • Code blocks are announced to screen readers
  • Syntax highlighting is visual only (doesn’t affect meaning)
  • Consider adding descriptions for complex code examples
  • Use semantic HTML when possible

Supported LanguagesLink to section

The syntax highlighter supports a wide range of languages including:

  • Web: HTML, CSS, JavaScript, TypeScript, JSX, TSX
  • Backend: Python, Ruby, PHP, Java, C#, Go, Rust
  • Database: SQL, MongoDB queries
  • DevOps: Docker, Kubernetes YAML, Shell scripts
  • Data: JSON, YAML, TOML, XML
  • And many more!

Each language has its own syntax rules and highlighting patterns optimized for readability in both light and dark themes.