Skip to main content

What Is a Function Body in Programming?

A function's body is where you place a sequence of statements you want to execute.

Syntax of a JavaScript Function Body

function nameOfFunction() {
// function's body
}

Function Body Examples

Below are examples of how we use the function body.

How to define a function with three statements in its body

function getName() {
const firstName = "Oluwatobi";
const lastName = "Sofela";
console.log(firstName + " " + lastName);
}

Try Editing It

In the snippet above, the function's body contains three statements that the computer will execute whenever the function gets invoked.

Note: console.log() is a method we use to log (write) messages to a web console.

How to define a function with two statements in its body

const bestColors = ["Coral", "Blue", "DeepPink"];

function updateMyBestColors(previousColors, newColor) {
const mybestColors = [...previousColors, newColor];
return mybestColors;
}

updateMyBestColors(bestColors, "GreenYellow");

Try Editing It

In the snippet above, the function's body contains two statements that the computer will execute whenever the function gets invoked.

note
  • The three dots we prepended to previousColors is called a spread operator. We used it to expand the array argument into individual elements.
  • You can also prepend the newColor parameter with a rest operator if you wish to add two or more new colors.
  • The return keyword ends its function's execution and returns the specified expression (or undefined if you provide no expression).

Overview

This article discussed what a function body is. We also used JavaScript examples to see how it works.

Your support matters: Buy me a coffee to support CodeSweetly's mission of simplifying coding concepts.

Tweet this article