Two Ways to Show Code
Markdown provides two distinct syntaxes for displaying code: inline code for short snippets within sentences and code blocks for multi-line examples that stand alone. Understanding when to use each—and how to maximize their effectiveness—is essential for clear technical documentation. The wrong choice creates confusion and breaks reading flow; the right choice makes complex technical concepts accessible and scannable.
Inline Code: Code Within Text
Inline code uses single backticks (`) to mark code within regular paragraphs, preserving its literal formatting while maintaining text flow.
Basic Syntax
Use the `print()` function to output text in Python.
The variable `user_count` stores the number of active users.
Run `npm install` to install dependencies.
Renders as: Use the print() function to output text in Python.
When to Use Inline Code
Function and Method Names: Mark function calls to distinguish them from prose:
Call `authenticate()` before calling `fetchUserData()`.
Variable Names: Identify variables referenced in explanations:
The `max_connections` variable limits concurrent database connections.
Short Commands: Indicate terminal commands within instructions:
Run `git status` to check your repository state.
File and Directory Names: Clarify paths and filenames:
Edit the `config.json` file in the `/etc/app/` directory.
Parameter Names: Reference parameters in API documentation:
The `timeout` parameter controls request duration in seconds.
Keywords and Operators: Highlight programming language keywords:
Use the `async` keyword before function declarations.
Configuration Keys: Identify configuration options:
Set `debug: true` in your settings.
Best Practices for Inline Code
Don't Overuse: Not every technical term needs backticks. "We're using React" doesn't require React in code formatting—it's clear from context. Reserve inline code for identifiers that benefit from literal formatting.
Maintain Readability: Excessive inline code makes paragraphs choppy. This is hard to read:
The `function` `getUserData()` calls the `API` endpoint `/api/users` with the `userId` parameter.
Better:
The getUserData() function calls the `/api/users` endpoint with a userId parameter.
Be Consistent: If you mark one function name with inline code, mark all function names consistently throughout your documentation.
Include Syntax When Helpful: For functions, include parentheses: getData() not getData. For methods with parameters, consider showing them: fetch(url, options).
Code Blocks: Standalone Code Examples
Code blocks display multiple lines of code as distinct, formatted sections separate from surrounding text.
Fenced Code Block Syntax
Use three backticks (```) or three tildes (~~~) on lines before and after code:
```
function greet(name) {
return `Hello, ${name}!`;
}
```
Specify Language for syntax highlighting:
```javascript
function greet(name) {
return `Hello, ${name}!`;
}
```
Markdown renderers apply language-specific syntax highlighting, dramatically improving readability.
Supported Languages
Most renderers support 100+ languages:
Common Languages:
```python # Python
```javascript # JavaScript
```typescript # TypeScript
```java # Java
```csharp # C#
```cpp # C++
```go # Go
```rust # Rust
```ruby # Ruby
```php # PHP
```sql # SQL
```bash # Bash/Shell
```json # JSON
```yaml # YAML
```xml # XML
```html # HTML
```css # CSS
```markdown # Markdown
```diff # Diff files
```text # Plain text
### When to Use Code Blocks
**Complete Functions**: Show full implementations:
````markdown
```python
def calculate_average(numbers):
if not numbers:
return 0
return sum(numbers) / len(numbers)
**Configuration Examples**: Display complete config files:
````markdown
```yaml
database:
host: localhost
port: 5432
username: admin
password: secret
```
API Requests and Responses:
```json
{
"userId": 123,
"name": "Alice Johnson",
"email": "[email protected]"
}
```
Shell Commands and Output:
```bash
$ npm test
> [email protected] test
> jest
PASS tests/calculator.test.js
✓ adds numbers correctly (2 ms)
✓ subtracts numbers correctly (1 ms)
```
Multi-Line Algorithms: Show step-by-step logic:
```python
# Binary search implementation
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
```
Code Block Best Practices
Always Specify Language: Syntax highlighting isn't just prettier—it's functional. Colored keywords, strings, and comments guide comprehension.
Include Comments: Explain non-obvious code within blocks:
```javascript
// Debounce function prevents excessive API calls
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId); // Cancel previous timer
timeoutId = setTimeout(() => func(...args), delay);
};
}
```
Show Complete, Runnable Examples: Readers appreciate code they can copy and execute. Include imports, declarations, and cleanup:
```python
import requests
def fetch_user(user_id):
response = requests.get(f'https://api.example.com/users/{user_id}')
return response.json()
# Example usage
user = fetch_user(123)
print(user['name'])
```
Use Line Length Limits: Keep lines under 80-100 characters when possible for better rendering on narrow screens.
Separate Setup from Core Logic:
```javascript
// Setup
const API_URL = 'https://api.example.com';
const API_KEY = process.env.API_KEY;
// Core function
async function fetchData(endpoint) {
const response = await fetch(`${API_URL}/${endpoint}`, {
headers: { 'Authorization': `Bearer ${API_KEY}` }
});
return response.json();
}
```
Indented Code Blocks (Legacy Syntax)
Standard Markdown also supports indented code blocks—indent every line by 4 spaces or 1 tab:
Normal paragraph text.
function example() {
return "indented code block";
}
Back to normal text.
Limitations:
- No syntax highlighting
- No language specification
- Easy to accidentally create with improper indentation
- Harder to visually distinguish from normal paragraphs
Recommendation: Use fenced code blocks (triple backticks) instead. They're clearer, support syntax highlighting, and are the GFM standard.
Advanced Code Block Features
Line Highlighting
Some renderers support highlighting specific lines:
```javascript {2,4-6}
function processData(data) {
const filtered = data.filter(item => item.active);
const mapped = filtered.map(item => ({
id: item.id,
name: item.name,
timestamp: Date.now()
}));
return mapped;
}
```
Highlights lines 2, 4, 5, and 6, drawing attention to key code.
Line Numbers
Many renderers add line numbers automatically or support enabling them:
```python showLineNumbers
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
```
Code Titles
Some systems support code block titles:
```javascript:fibonacci.js
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n-1) + fibonacci(n-2);
}
```
Diff Highlighting
Show code changes with diff syntax:
```diff
function greet(name) {
- return "Hello " + name;
+ return `Hello, ${name}!`;
}
```
Lines starting with - appear red (removed), + appear green (added).
Common Mistakes and How to Avoid Them
Mistake 1: Using Code Blocks for Single Identifiers
Wrong:
userId
Right:
The `userId` parameter identifies the user.
Code blocks for single words waste space and break flow.
Mistake 2: Missing Language Specification
Wrong:
```
def hello():
print("Hello")
```
Right:
```python
def hello():
print("Hello")
```
Syntax highlighting dramatically improves readability.
Mistake 3: Mixing Code and Output Without Distinction
Confusing:
```
$ npm test
PASS tests/app.test.js
```
Clear:
```bash
$ npm test
```
Output:
```
PASS tests/app.test.js
✓ renders correctly (12 ms)
```
Separate commands from output for clarity.
Mistake 4: Incomplete Examples
Frustrating:
```javascript
await fetchData();
```
Helpful:
```javascript
const API_URL = 'https://api.example.com/data';
async function fetchData() {
const response = await fetch(API_URL);
return response.json();
}
// Usage
const data = await fetchData();
console.log(data);
```
Readers need context—imports, definitions, usage.
Choosing Between Inline and Block
Use Inline Code When:
- Referencing identifiers within sentences
- Mentioning single commands or functions
- Discussing parameters in prose
- The code is 1-5 words
Use Code Blocks When:
- Showing complete implementations
- Displaying configuration files
- Presenting API examples
- The code is multiple lines or complex
Gray Area Example: For a short command with options, either works:
Run `git commit -m "Initial commit"` to commit changes.
Or:
Commit your changes:
```bash
git commit -m "Initial commit"
Choose based on emphasis—inline maintains flow, blocks emphasize importance.
## Preview Your Code Formatting
Want to see how your inline code and code blocks render? Our [Markdown Preview](/tools/markdown-preview) tool provides real-time rendering with full syntax highlighting support. Test different languages, check formatting, and ensure your code examples look exactly as intended.
## Mastering Code Presentation
Effective technical documentation depends on clear code presentation. Inline code marks identifiers without disrupting reading flow. Code blocks showcase complete examples with syntax highlighting that guides comprehension. Master both, understand when each applies, and your documentation will communicate technical concepts with clarity and precision that benefits every reader.
The difference between inline code and code blocks isn't just syntactic—it's semantic. One preserves sentence flow while marking technical terms; the other creates visual separation that signals "stop and read carefully." Choose wisely, and your code examples become powerful teaching tools rather than confusing obstacles.