Ad space (banner)
🟨JavaScript Lessons
Lesson 5 / 69

Creating Functions

In this lesson you'll learn how to write functions in JavaScript so you can write code that reuses the same logic multiple times. This is written for beginners who searched "JavaScript how to create a function" or "JavaScript function usage."

A function bundles a piece of processing and gives it a name. You define one with function name(arguments) { ...; return value; }, and call it with name(value). Think of it like a recipe: once you've written down a set of steps and given it a name, you can reproduce the same result any time you need it. The power of a function is that changing the arguments lets you get different results from the same logic.

The sample code defines a function called greet that takes an argument named name and uses return to give back a greeting message. A value returned with return can be used directly at the call site, for example console.log(greet("Bob")).

A common beginner mistake is forgetting to write return, which makes the function's result undefined. return means "finalize the function's result here and hand it back to the caller," so any function meant to produce a value absolutely needs it. Also watch out for confusion when a variable defined outside the function shares a name with one of its arguments.

In real development, the standard approach when you need to reuse the same calculation or data processing in multiple places is to extract it into a function first. Splitting your code into well-sized functions makes it easier to follow, and easier to fix bugs and write tests. The quality of your function design has a big impact on real-world code quality.

Some functions don't return a value and just perform an action — in that case you can omit return, and the caller simply runs the function without using a return value. Being conscious of the distinction between "functions that return a value" and "functions that just perform an action" makes your code's intent much clearer.

Function naming has its own tricks too: giving a function a name like greet or calculateTotal, where the verb conveys "what this function does," is the basic rule. A function whose name alone lets you guess what it does is a real kindness to whoever reads your code.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)