Cost Check Now
Programming·JavaScript

How to create a function in JavaScript (2026)

Verified from sources

Quick Answer

In JavaScript, you create a function by defining a reusable block of code with a name, optional inputs called parameters, and optional output using return. The most common form is function myFunction() { ... }, but you can also use function expressions and arrow functions. The key is to choose the right syntax for your use case, then call the function and test that it behaves as expected.

Overview

A JavaScript function lets you group code into a reusable unit so you do not repeat the same logic throughout your program. Functions can take inputs, process them, and optionally return a result. This makes your code easier to read, test, maintain and debug. If you are learning JavaScript, creating functions is one of the first core skills to master because most real programs depend on them. There are three common ways to create a function in JavaScript: a function declaration, a function expression, and an arrow function. A function declaration is often the clearest starting point for beginners. Function expressions are useful when assigning a function to a variable or passing it around. Arrow functions are common in modern JavaScript, especially for short callbacks, but they behave differently with this, so they are not always a drop-in replacement. A good function should usually do one clear job, have descriptive names, and avoid relying too heavily on outside variables. Once you can define parameters, use return, and call the function correctly, you can build more complex logic with confidence. This guide shows the practical steps, explains why each one matters, and points out common errors that cause functions not to run.

Who this is for

Beginners learning JavaScript, students, self-taught developers, and anyone who needs to write basic reusable code in a browser or Node.js.

What you’ll need

  • A basic JavaScript environment such as a web browser console or Node.js
  • A text editor or IDE
  • Basic understanding of variables and JavaScript syntax
  • A way to run and test code, such as browser DevTools or the node command

Before you start

Make sure you know where your JavaScript code will run: in a browser, in Node.js, or inside a larger app. Also check that your editor saves plain JavaScript files correctly and that you can already run a simple line such as console.log('test') without errors.

Step-by-step

  1. 1

    Choose the function style you need

    Decide whether to use a function declaration, function expression, or arrow function. For a straightforward reusable function, start with a function declaration such as function greet() { }. Use a function expression when assigning a function to a variable. Use an arrow function for short modern syntax, especially in callbacks.

    Why: Each style is valid, but they behave differently in areas such as hoisting and this binding. Choosing the right form early avoids confusion later.

  2. 2

    Write the function name and parentheses

    Define the function with a clear descriptive name and add parentheses after it. For example: function addNumbers() { }. If the function needs input values, place parameter names inside the parentheses, such as function addNumbers(a, b) { }.

    Why: A descriptive name makes the code easier to understand, and parameters tell JavaScript what inputs the function expects.

  3. 3

    Add the code inside curly braces

    Place the function body between { and }. Write the instructions the function should carry out inside those braces. For example, you might calculate a value, check a condition, or display output.

    Why: The body is the actual reusable logic. Without a clear body, the function exists but does nothing useful.

  4. 4

    Return a result if needed

    If the function should produce a value for other code to use, add a return statement. Example: function addNumbers(a, b) { return a + b; }. If the function only performs an action, such as logging or updating the page, return may not be necessary.

    Why: return sends a value back to the caller. Without it, many functions produce undefined even if they perform calculations internally.

  5. 5

    Call the function correctly

    Run the function by using its name followed by parentheses. Example: addNumbers(2, 3). If the function requires parameters, supply arguments in the correct order. Store the result in a variable if needed, such as const total = addNumbers(2, 3).

    Why: Defining a function does not execute it. Calling it is what actually runs the code.

  6. 6

    Test with simple examples

    Try the function with expected inputs and a few edge cases. For instance, test whether addNumbers works with whole numbers, strings, or missing values. Use console.log or your debugger to inspect results.

    Why: Testing helps you catch common problems early, such as incorrect parameter handling, missing return statements, or unintended type conversion.

  7. 7

    Refine the function for readability

    If the function is getting long or doing several jobs, split it into smaller functions. Improve naming, keep parameters meaningful, and avoid relying on hidden global variables where possible.

    Why: Small focused functions are easier to reuse, debug and maintain, especially as your codebase grows.

Why this works

Functions work because JavaScript treats them as reusable callable blocks of code. You define logic once, then run it whenever needed with different inputs, which reduces repetition and makes behaviour easier to manage.

Common mistakes to avoid

  • Forgetting to call the function after defining it
  • Missing or mismatched parentheses or curly braces
  • Expecting a result without using return
  • Using an arrow function where you need its own this value
  • Giving parameters unclear names so the function becomes hard to use
  • Relying on global variables instead of passing needed values in as parameters

Troubleshooting

The function name is recognised but nothing seems to happen

Check whether the function body actually contains code that changes something visible or returns a value you inspect. Also confirm that you are calling it, not just defining it.

The function returns undefined

Add a return statement if you expect a result, and make sure the intended value is on the same execution path.

You get a syntax error

Check for missing commas, parentheses, curly braces, or misspelled keywords such as function or return.

The function works with some inputs but not others

Inspect the types of the arguments being passed in. JavaScript may coerce values unexpectedly, so add checks or conversions where appropriate.

this is not what you expected inside the function

Review whether you used an arrow function. Arrow functions do not create their own this, so use a regular function if you need method-style this behaviour.

Compare your options

Function declaration

Best for: General-purpose named functions and beginners

Pros: Clear syntax, easy to read, hoisted so it can be called before its definition in many cases

Cons: Less flexible when you specifically need an inline or conditionally assigned function

Function expression

Best for: Assigning functions to variables or passing them as values

Pros: Flexible, works well when functions are treated as data

Cons: Can be slightly less readable for beginners and is not hoisted in the same way as a declaration

Arrow function

Best for: Short callbacks and modern concise code

Pros: Compact syntax, useful in array methods and promise chains

Cons: Does not have its own this, arguments, super, or new.target, so it is not right for every case

Alternatives

  • Use a method inside an object if the function logically belongs to that object
  • Use a class method if you are structuring code with classes
  • Use built-in array methods with callbacks instead of writing repetitive loops for simple transformations

Pro tips

  • Start with function declarations until you are comfortable with the basics
  • Use verb-based names such as calculateTotal or formatDate
  • Keep each function focused on one job
  • Test functions in the browser console for quick feedback
  • Prefer passing values in as parameters instead of reading from unrelated global state

Safety notes

  • Do not use untrusted input directly in code execution features such as eval
  • Be careful when functions handle user input that later affects the page, file system, network requests, or databases
  • Avoid naming collisions by using clear unique function names within larger projects

What this guide does not cover: This guide covers the basics of creating functions in JavaScript but does not go deeply into asynchronous functions, closures, generators, recursion, object methods, class methods, or framework-specific usage.

Cost considerations

You can create and test JavaScript functions using free tools, including a browser console, free editors, and the standard Node.js runtime. Paid IDEs and training resources are optional rather than required.

Frequently asked questions

What is the simplest way to create a function in JavaScript?+

Use a function declaration, such as function sayHello() { console.log('Hello'); }. This is usually the clearest format for beginners.

What is the difference between parameters and arguments?+

Parameters are the names listed in the function definition. Arguments are the actual values you pass in when calling the function.

Do all functions need a return statement?+

No. Use return when you need the function to give a value back. If the function only performs an action, it may not need one.

When should I use an arrow function?+

Arrow functions are useful for short functions and callbacks, especially in modern JavaScript. Avoid them when you need a normal function's this behaviour.

Can I call a function before I write it in the file?+

With function declarations, often yes because they are hoisted. With function expressions and arrow functions assigned to variables, usually no in the same way.

Sources & references

Guidance on this page is traced to documented sources. Last checked 24 September 2026.

The fundamentals of creating functions in JavaScript are stable, though style preferences and newer syntax features can evolve over time.

Related guides

Legal Disclaimer: The information provided on Cost Check Now is for general informational and educational purposes only. It does not constitute financial, legal, professional, or any other form of advice. Cost Check Now makes no representations or warranties of any kind, express or implied, about the completeness, accuracy, reliability, suitability, or availability of any information, products, services, or related graphics contained on this website. Any reliance you place on such information is strictly at your own risk. In no event will Cost Check Now, its owners, operators, contributors, or affiliates be liable for any loss or damage including without limitation, indirect or consequential loss or damage, or any loss or damage whatsoever arising from loss of data or profits arising out of, or in connection with, the use of this website. Always seek independent professional advice before making financial or purchasing decisions.