Functions in JavaScript

Learn how to create reusable blocks of code with functions.

What are Functions?

Functions are reusable blocks of code that perform a specific task. They help you organize your code, avoid repetition, and make your programs easier to understand and maintain.

Key Concept: Functions follow the DRY principle - Don't Repeat Yourself. Write once, use many times!

Function Declarations

The most common way to create a function is using a function declaration.

Try it yourself
Output

Function Expressions

Functions can also be stored in variables. This is called a function expression.

Try it yourself
Output

Arrow Functions

Arrow functions provide a shorter syntax for writing functions. They're especially useful for simple operations.

Try it yourself
Output

Parameters and Arguments

Functions can accept parameters (inputs) and return values (outputs).

Try it yourself
Output

Return Values

Functions can return a value using the return statement. If no return is specified, the function returns undefined.

Try it yourself
Output

Challenge: Create a Calculator

Create a function called calculate that takes three parameters: two numbers and an operator (+, -, *, /). Return the result of the operation.

Your solution
Output