BudiBadu Logo
Samplebadu

Markdown by Example: Code Blocks

CommonMark / GFM

Code blocks are used to display source code. This example shows inline code and fenced code blocks with syntax highlighting.

Code

Inline code uses backticks: `const x = 10;`

Fenced code block (using three backticks):

```javascript
function greet(name) {
    console.log("Hello, " + name);
}
```

Indented code block (4 spaces):

    <html>
      <body>
        <p>Old style code block</p>
      </body>
    </html>

Diff syntax highlighting:

```diff
- var x = 1;
+ var x = 2;
```

Explanation

For short snippets of code within a sentence, use single backticks `. This renders the text in a monospaced font and preserves special characters. If you need to include a literal backtick inside the code, wrap it in double backticks `` ` ``.

For larger blocks of code, "fenced code blocks" are the standard. They start and end with three backticks ``` or three tildes ~~~. You can optionally specify the language name after the opening backticks (e.g., ```python) to enable syntax highlighting. This is a feature of GFM and most modern renderers.

The original Markdown specification used 4-space indentation to define code blocks. While still supported, it is less convenient than fenced blocks because you have to manually indent every line, and it doesn't support syntax highlighting hints. Fenced blocks are generally preferred today.

Code Breakdown

1
`const x = 10;` renders as inline code.
5
```javascript starts the block and tells the highlighter to use JavaScript rules.