Menu
Coddy logo textTech

What is Function?

Lesson 2 of 14 in Coddy's Function Declarations in JavaScript course.

Imagine you have a favorite recipe for cookies. Baking those cookies every time you crave them can be a bit repetitive. Functions are like superhero helpers in JavaScript that come to the rescue! They are reusable blocks of code that perform specific tasks. Just like you follow the recipe steps to bake cookies, functions have instructions that get executed when you call on them (like giving the recipe a name and following those steps).

Function Syntax:

function functionName(parameter1, parameter2, ...) {
	// Code to be executed (the superhero's instructions)
	return value; // Optional: Returning a value (like the baked cookies!)
}
  • function: This keyword tells JavaScript that we're creating a function.
  • functionName: This is the name you give your function.
  • parameter1, parameter2, ...: These are like ingredients or tools the function might need to do its job. They are variables that hold the information you provide when you call the function.

Here's an example to illustrate how functions work:

function greet(name) {
	console.log("Hello, " + name + "!");
	return "Have a fantastic day!";
}

const message = greet("Alice"); // Calling the function
console.log(message);
// Output: Hello, Alice!
//         Have a fantastic day!
  • We define a function named greet that takes one parameter, name.
  • The return statement sends back the message "Have a fantastic day!".
  • We call the greet function with the argument "Alice" and store the returned value (the message) in the message variable.
  • Finally, we print both the greeting and the returned message.

Let's take on this simple challenge!

challenge icon

Challenge

Easy

Your task is to create a function named myFunction that takes no arguments and simply prints the message “Hello, Coddies!” to the console.

Try it yourself

// Write code here

All lessons in Function Declarations in JavaScript