Search⌘ K
AI Features

Creating Functions

Explore how to define and invoke JavaScript functions using various methods like declarations, expressions, arrow functions, and immediately invoked expressions. Understand parameters, arguments, and default values to write modular, reusable code. This lesson helps you structure your code efficiently and avoid repetition for dynamic programming.

Functions are one of the foundational building blocks in JavaScript, allowing us to encapsulate reusable logic and structure our code effectively.

What are functions?

Functions are blocks of code that are designed to perform a specific task. They are executed when “called” or “invoked.” Functions allow us to avoid repeating code by defining reusable logic.

Syntax for defining functions

JavaScript provides several ways to define functions. Let’s explore the most common ones:

Function declaration

A function declaration defines a function with a name that can be called later.

function greet(name) {
return `Hello, ${name}!`;
}
Syntax for defining a function

In the above code:

  • Line 1: We use the function keyword to define the function, followed by the function name greet and parentheses containing parameters.

  • Line 2: Inside the curly braces {}, the ...