JavaScript Functions for Beginners

A function is a piece of code that you can reuse.
This is useful because you do not have to write the same code again and again.

Example

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
</head>

<body>
<h1>JavaScript Functions</h1>
<p id=”output”></p>
<button onclick=”showMessage()”>Show message</button>

<script>
function showMessage() {
document.getElementById(“output”).innerHTML = “Hello, welcome to this website!”;
}
</script>
</body>
</html>

Explanation

The function is called showMessage().
This function runs when you click the button.
The text inside the element with the id output is then changed.

Why are functions useful?

  • you can reuse code
  • your code stays more organized
  • you repeat less