functions

Functions in JavaScript

Functions in JavaScript

Functions allow us to group code into reusable blocks. They can accept inputs, perform tasks, and return values.

Defining a Function

Use the function keyword to define a function:

      
        function greet(name) {
          console.log("Hello, " + name + "!");
        }
      
    

Calling a Function

Call a function by writing its name followed by parentheses:

      
        greet("Alice");
      
    

Activity

Try It Yourself!

Create a function that takes two numbers as parameters and returns their sum. Call the function with two numbers and log the result.

Quiz

Quick Quiz

  1. What is a function?
  2. How do you call a function?
  3. What is the purpose of a return statement?

Answers: A block of code that performs a task; by its name and parentheses; to output a value.