Code Formatting
When writing tutorials, blog posts, or documentation, you'll often need to include code snippets. Markdown provides several ways to format code, from inline code snippets to multi-line code blocks with syntax highlighting included.
Inline code
Inline code is created using backticks (`). This is useful for including short code examples such as variable names, a method name, elements, commands, or other code elements within a paragraph of text.
Syntax:
Create a JavaScript variable using the `var` keyword, followed by a name.
Result:
Create a JavaScript variable using the var keyword, followed by a name.
Code blocks
For larger code snippets, often multi-line, Markdown provides two methods to create code blocks:
1. Fenced code blocks
Modern Markdown flavors support fenced code blocks using three backticks (```) or three tildes (~~~) at the start and end of the block.
Syntax:
```
const name = 'Homer';
const learningMarkdown = true;
console.log(name, learningMarkdown);
```
Or:
~~~
const name = 'Homer';
const learningMarkdown = true;
console.log(name, learningMarkdown);
~~~
Result:
const name = 'Homer';
const learningMarkdown = true;
console.log(name, learningMarkdown);
2. Indented code blocks
You can create a code block by indenting each line with four spaces or one tab.
Syntax:
const name = 'Homer';
const learningMarkdown = true;
console.log(name, learningMarkdown);
Result:
const name = 'Homer';
const learningMarkdown = true;
console.log(name, learningMarkdown);
Syntax highlighting
Many Markdown processors support syntax highlighting by adding the language after the opening fence.
Syntax:
```javascript
let user = {
first: 'Homer',
last: 'Simpson',
occupation: 'Safety Inspector',
};
document.getElementById('title').innerText = user;
```
Result:
let user = {
first: 'Homer',
last: 'Simpson',
occupation: 'Safety Inspector',
};
document.getElementById('title').innerText = user;
Common language identifiers include:
htmlcssjavascriptorjspythonjavajsonmarkdownxmlrubysql
Escaping backticks
Backticks can also be included within the inline code by adding double backticks:
Syntax:
`` Adding `backticks` within code ``
Result:
Adding `backticks` within code