JavaScript Define & Call Functions with Example

⚡ Smart Summary

JavaScript functions group reusable blocks of code that run only when called, and this walkthrough shows how to declare one, pass arguments into it, and return a value back to the caller.

  • 🔘 Syntax: The function keyword, a name, parentheses and curly braces define every classic function.
  • ☑️ Calling: Code inside a function executes only when the function name is invoked with parentheses.
  • Arguments: Values placed inside the parentheses pass data from the caller into the function body.
  • 🧪 Return: The return keyword sends a value back to the caller and stops execution at that point.
  • 🛠️ Variants: Declarations, expressions, arrow functions, IIFEs and callbacks each suit a different situation.
  • 📊 Scope: Function declarations are hoisted, while function expressions and arrow functions are not.

JavaScript Define and Call Functions

What is Function in JavaScript?

Functions are very important and useful in any programming language as they make the code reusable. A function is a block of code which will be executed only if it is called. If you have a few lines of code that needs to be used several times, you can create a function including the repeating lines of code and then call the function wherever you want.

Nothing inside the braces runs on its own. The browser stores the block under the name you gave it, and the code executes only when that name is written with parentheses after it, such as myFunction(). Functions therefore sit at the centre of every JavaScript program, whether the script lives inside the page or in an external file.

How to Create a Function in JavaScript

  1. Use the keyword function followed by the name of the function.
  2. After the function name, open and close parentheses.
  3. After parenthesis, open and close curly braces.
  4. Within curly braces, write your lines of code.

Syntax:

function functionname()
{

  lines of code to be executed

}

The example below defines myFunction() and then calls it on the very next line, so the message appears as soon as the page loads. Try this yourself:

<html>
<head>
	<title>Functions!!!</title>
	<script type="text/javascript">
      function myFunction()
      {
      	document.write("This is a simple function.<br />");
      }
		myFunction();
	</script>
</head>
<body>
</body>
</html>

Function with Arguments

You can create functions with arguments as well. Arguments should be specified within parentheses.

Syntax:

function functionname(arg1, arg2)

{

  lines of code to be executed

}

Here countVowels() receives whatever name the visitor types into the prompt, loops through each character, and reports how many vowels the name contains. Try this yourself:

<html>
<head>
	<script type="text/javascript">
		var count = 0;
		function countVowels(name)
		{
			for (var i=0;i<name.length;i++)
			{
              if(name[i] == "a" || name[i] == "e" || name[i] == "i" || name[i] == "o" || name[i] == "u")
              count = count + 1;
			}
		document.write("Hello " + name + "!!! Your name has " + count + " vowels.");
		}
   	 	var myName = prompt("Please enter your name");
    	countVowels(myName);
	</script>
</head>
<body>
</body>
</html>

JavaScript Return Value

You can also create JS functions that return values. Inside the function, you need to use the keyword return followed by the value to be returned.

Syntax:

function functionname(arg1, arg2)

{

  lines of code to be executed

  return val1;

}

In this last example returnSum() hands the total back to the line that called it, so the result can be joined into a sentence instead of being printed inside the function. Try this yourself:

<html>
<head>
	<script type="text/javascript">
		function returnSum(first, second)
        {
          var sum = first + second;
          return sum;
        }
      var firstNo = 78;
      var secondNo = 22;
      document.write(firstNo + " + " + secondNo + " = " + returnSum(firstNo,secondNo));
	</script>
</head>
<body>
</body>
</html>

Types of Functions in JavaScript

The three examples above all use the classic function declaration, yet modern JavaScript offers several other forms. They differ mainly in whether the engine hoists them and in how each one treats the this keyword.

Function type Typical syntax When it is used
Function declaration function greet() { } Named, reusable logic; hoisted to the top of its scope
Function expression const greet = function () { }; Storing a function in a variable; not hoisted
Arrow function (ES6) const greet = () => { }; Short callbacks; inherits this from the surrounding scope
Anonymous function setTimeout(function () { }, 100); One-off logic passed straight into another function
IIFE (function () { })(); Runs immediately and keeps its variables private
Callback items.forEach(showItem); A function handed to another function and invoked later

Note on the examples above: the historical samples use var and document.write(), and both still run in every browser. Current practice declares variables with let or const and prints output through console.log() or by setting textContent on an element, because document.write() wipes a page that has already finished loading. The type="text/javascript" attribute is also optional in HTML5.

Function Parameters, Arguments, and Default Values

Parameters are the placeholder names listed in the definition, while arguments are the real values supplied when the function is called. In countVowels(name) above, name is the parameter and the text typed into the prompt is the argument.

function greet(user, greeting = "Hello")
{
  return greeting + ", " + user;
}

greet("Ann");
greet("Ann", "Welcome");
  • A parameter with no matching argument becomes undefined unless a default value is supplied, as greeting is here.
  • Extra arguments are ignored by the parameter list but stay reachable through the arguments object inside any non-arrow function.
  • A rest parameter written as ...values collects every remaining argument into a genuine array.

Function Scope and Hoisting in JavaScript

Where a function is written decides what it can see and when it can be called. Two rules explain almost every surprise beginners meet.

  • Hoisting: function declarations are moved to the top of their scope before the script runs, so they may be called on a line above their definition. Function expressions and arrow functions are not hoisted and throw an error if called early.
  • Scope: variables declared with var inside a function are visible throughout that function, while let and const are limited to the block they sit in. Anything declared outside every function is global.

The vowel counter shows this in practice. Its count variable is declared outside the function, so calling countVowels() a second time on the same page continues adding to the earlier total instead of restarting at zero. Moving the declaration inside the function would reset it on every call.

These scoping rules carry over to server-side code as well, which is why the same reasoning applies when functions are written for Node.js, and why function behaviour appears so often in JavaScript interview questions.

FAQs

The function still runs, but it hands back undefined. Assigning that call to a variable stores undefined, which is why the sum example uses return rather than printing the total inside the function body.

AI assistants can suggest a function body from a comment, explain an unfamiliar callback line by line, and propose test inputs. Always run the suggestion, because generated code can silently assume a variable or browser API that the page does not provide.

Usually yes. GitHub Copilot completes arrow syntax and common callback patterns from context. Check the value of this in the result, since an arrow function inherits it while a classic function expression does not.

A closure is a function bundled with the outer variables it referenced when it was created. The inner function keeps reading those variables even after the outer function has finished, which is how private counters and factory functions are built.

Yes, and that is called recursion. The function must contain a base case that stops the chain, otherwise the browser raises a range error once the call stack is exhausted. Recursion suits tree walking and factorial style problems.

An async function always returns a promise. Inside it, await pauses that function until the awaited promise settles, letting asynchronous code read top to bottom. The rest of the page keeps responding while the function waits.

Attach it with an event listener: select the button, then call addEventListener with the event name and the function reference. The older inline onclick attribute also works, though separating markup from behaviour is now preferred.

Parentheses call it immediately and produce its result. Writing the name alone passes the function itself, which is what callbacks need. Adding parentheses by mistake inside setTimeout runs the code straight away rather than later.

Summarize this post with: