...

/

Creating Functions

Creating Functions

Learn to create and use JavaScript functions, including common patterns and best practices.

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 function’s body contains the logic. Here, it ...

Access this course and 1400+ top-rated courses and projects.