Skip to main content

What are functions?

Functions are reusable blocks of code. You define them once and call them whenever you need that logic. If you’ve written def in Python, you already understand the concept — JavaScript just wraps it differently.

Function declarations

The most common way to create a function:
The structure is identical — keyword, name, parameters, body, return. JavaScript uses function instead of def, curly braces instead of indentation, and camelCase instead of snake_case.

Return values

Functions return undefined by default. If you want a value back, you need an explicit return statement.
return also exits the function immediately. Code after return never runs.

Function expressions

You can also create functions by assigning them to variables:
This is called a function expression. The function doesn’t have its own name — it’s stored in the variable multiply.
Function declarations are “hoisted” — you can call them before they appear in your code. Function expressions are not. For now, stick with function declarations. You’ll use function expressions more when you learn arrow functions next.

Functions as values

JavaScript relies much more heavily on functions as values in everyday programming patterns — but Python supports the same concept.
You’ll use this pattern constantly. Array methods like .map(), .filter(), and .forEach() all take functions as arguments. React event handlers work the same way.
Get comfortable with passing functions as arguments. It’s one of the most common patterns in JavaScript and React. You’ll see it everywhere: array.map(myFunction), button.addEventListener("click", myFunction), <button onClick={myFunction}>.

Calling vs referencing

A subtle but important distinction:
With parentheses () you call the function. Without parentheses, you reference it. This matters when passing functions to event handlers or array methods — you pass the reference, not the result.

Common mistakes

If your function computes a value but doesn’t return it, you get undefined. This is one of the most common bugs in JavaScript — especially for Python developers, since Python returns None explicitly.
When passing a function as an argument, don’t add () unless you want it to run immediately. This trips up everyone at first — especially in React’s onClick handlers.
Function declarations don’t end with a semicolon (they’re statements). Function expressions do (they’re assignments). This is a minor style point — Prettier handles it automatically if you have it set up.

What’s next?

You know how to write and call functions. JavaScript has a shorter, more modern syntax for functions called arrow functions — you’ll use them everywhere in React.

Arrow functions

Write shorter, cleaner functions with the modern syntax