AI Hints
JavaScript · Lesson 31 of 138

Functions

Reusable code.

⏱ 2 min read▶ Video at 37:39🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

If you write the same few lines again and again, wrap them in a function. A function is a named block of code you can run whenever you like, just by calling its name. It's the most important building block in JavaScript.

Functions
From the video: Functions
  • Same lines again and again?
  • Wrap them in a function
  • Call it by name

Defining and calling

The function keyword, a name, round brackets, and the code in curly braces. That's the definition, and on its own, it doesn't run anything. To run it, we call it, with its name and brackets. We can call it as many times as we like. Run it.

app.jsjavascript
function greet() {
  console.log("Hello!");
  console.log("Welcome to the course.");
}

greet();
greet();
Output
Hello!
Welcome to the course.
Hello!
Welcome to the course.

Why functions matter

Functions let you write code once, and use it everywhere. If there's a bug, you fix it in one place. They also give a name to a piece of work, so your code reads like a list of steps. Load the data, check it, show the results.

keyvalue
Definefunction name() { }
Callname()
Write onceuse many times
Namesdescribe the work

Summary

A function is a named block of code. Define it once, and call it with its name and brackets. Next, giving functions inputs and outputs.

Key takeaways
  • function name() { }
  • Call with name()
  • Reuse code
Next up: Parameters and Return — inputs and outputs