In HTML, two elements are available for writing code, <code> and <pre>. Inline code is written using <code> element, and preformatted text is created using <pre> element. That is why Markdown has two different ways of creating code blocks, inline code and code blocks. Inline code is created by adding a single backtick (`) on either side of the code. On the other hand, the code block is created by adding three backticks (```) on either side of the code snippet.
Inline code appears within the paragraph of text and highlights the small piece of code within the sentence. To create an inline code, you have to write a single backtick before and after the code snippet.
Markdown | HTML Output |
---|---|
In JavaScript, `Math.max()` function returns the number which is maximum among the set of numbers passed to it. | In JavaScript, <code>Math.max()</code> function returns the number which is maximum among the set of numbers passed to it. |
Multiple lines of code are shown in code blocks. Code blocks help you to preserve the indentation present in the code. To create a code block, you have to write three backticks before and after the code snippet.
Markdown | HTML Output |
---|---|
``` function add(a, b){ return a + b; } add(3, 4); ``` |
<pre><code>function add(a, b){ return a + b; } add(3, 4); </code></pre> |
Syntax highlighting is a fantastic feature provided by many Markdown processors. Using it, you can add colour highlighting to your code based on the code's programming language. To add a syntax highlighting, you have to specify the programming language after the first three backticks. By doing this, the code will be formatted according to the specified programming language.
Markdown | Rendered Output |
---|---|
```JavaScript function add(a, b){ return a + b; } add(3, 4); ``` |
|
If you indent every line of code by a tab or a minimum of four spaces, you will get a code block in Markdown. Let's rewrite the above JavaScript code using this method.
Markdown | Rendered Output |
---|---|
function add(a, b){ return a + b; } add(3, 4); |
|
Note: It is recommended that you use backticks to create code blocks because it is easier to use, and you don't have to remember the four spaces.