A function is a reusable block of code that can be called anywhere in a program to perform a specific task. This prevents having to rewrite the same code multiple times. The document provides an example function called sayHello() that displays an alert box with the text "Hello World" when clicked. It also explains that a for loop repeats a block of code a specified number of times, with the example looping and writing "hello" to the page the number of times dictated by the parameters.