Introducing Functions

In JavaScript, a function is a block of reusable code designed to perform a specific task when invoked or 'called'. Consider a scenario in which we need to compute something or create a pop-up notification every time a user clicks on a button. In such situations, we would enclose the necessary code within a function and invoke it whenever the button is clicked.

Here is an example of defining a function named sayHello:

JavaScript
// a function to say hello
function sayHello() {
  // code inside here runs when the function is called
  console.log("Hello, world!");
}

In this function, named sayHello, we print "Hello, world!" to the console when the function is invoked or called.

You have learned to define or declare a straightforward function in JavaScript. This is the initial building block in creating reusable code blocks.

Invoking Functions

To utilize a function, we have to invoke or 'call' it by appending parentheses () to the function's name. This process resembles joining a teleconference using a unique meeting link. Just as you join the meeting only when you click the link, the code inside the function is executed only when the function is called.

Let's invoke our sayHello function:

sayHello();  // Invokes the function, outputting: "Hello, world!"

Here, sayHello(); is a function call informing JavaScript to execute the code block within the sayHello function.

The Role of Parameters in Functions

Parameters provide a function with its inputs, significantly enhancing the function's reusability. It's akin to injecting some intelligence into a function, creating a lightbulb moment. Consider a function that calculates the area of a circle. Such a function would only be useful if it could compute the area for any circle, regardless of its radius, and not just for a circle with a fixed radius.

Observe the following function that greets a person using their name:

// a function that greets a person by name
function greetPerson(name) {
  console.log("Hello, " + name + "!");
}

// invoking the function with "Alice" as an argument
greetPerson("Alice");  // Outputs: "Hello, Alice!"

In this function, name is a parameter. When we invoked greetPerson("Alice");, the value "Alice" was passed as an argument to the function.

You've learned about bestowing a function with intelligence through parameters, making the function versatile and broadly applicable.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal