---
description: 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 l
title: JavaScript Define &#038; Call Functions with Example
image: https://www.guru99.com/images/javascript-define-call-functions.png
---

 

[Skip to content](#main) 

**⚡ 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.

[ Read More ](javascript:void%280%29;) 

![JavaScript Define and Call Functions](https://www.guru99.com/images/javascript-define-call-functions.png) 

## 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](https://www.guru99.com/introduction-to-javascript.html) program, whether the script lives [inside the page or in an external file](https://www.guru99.com/all-about-internal-external-javascript.html).

## 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>

### RELATED ARTICLES

* [For, While and Do While LOOP in JavaScript with Example ](https://www.guru99.com/how-to-use-loops-in-javascript.html "For, While and Do While LOOP in JavaScript with Example")
* [Conditional Statements in JavaScript: if, else, and else if ](https://www.guru99.com/how-to-use-conditional-statements-in-javascript.html "Conditional Statements in JavaScript: if, else, and else if")
* [Execute JavaScript Online ](https://www.guru99.com/execute-javascript-online.html "Execute JavaScript Online")
* [Difference Between =, ==, and === in JavaScript \[Examples\] ](https://www.guru99.com/difference-equality-strict-operator-javascript.html "Difference Between =, ==, and === in JavaScript [Examples]")

## 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](https://www.guru99.com/learn-arrays-in-javascript.html).

## 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](https://www.guru99.com/node-js-tutorial.html), and why function behaviour appears so often in [JavaScript interview questions](https://www.guru99.com/javascript-interview-questions-answers.html).

This code is editable. Click Run to Execute  

## FAQs

⚡ What happens when a JavaScript function has no return statement?

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.

🧠 How can AI assistants help when writing JavaScript functions?

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.

🤖 Can GitHub Copilot generate arrow functions and callbacks correctly?

Usually yes. [GitHub Copilot](https://github.com/features/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.

🔒 What is a closure in JavaScript?

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.

🔁 Can a JavaScript function call itself?

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.

⚙️ What is an async function and how does await behave inside it?

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.

🖱️ How do you call a JavaScript function from an HTML button?

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.

🧾 What is the difference between calling a function and passing a reference to it?

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:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter](https://www.guru99.com/images/footer-email-avatar-imges-1.png) Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/javascript-define-call-functions.png","url":"https://www.guru99.com/images/javascript-define-call-functions.png","width":"700","height":"250","caption":"JavaScript Define &amp; Call Functions","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/learn-functions-in-javascript-in-5-minutes.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/javascript","name":"JavaScript"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/learn-functions-in-javascript-in-5-minutes.html","name":"JavaScript Define &#038; Call Functions with Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/learn-functions-in-javascript-in-5-minutes.html#webpage","url":"https://www.guru99.com/learn-functions-in-javascript-in-5-minutes.html","name":"JavaScript Define &#038; Call Functions with Example","dateModified":"2026-07-29T17:23:52+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/javascript-define-call-functions.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/learn-functions-in-javascript-in-5-minutes.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/james","name":"James Hartman","description":"I am James Hartman, a seasoned professional in Oracle Certified Java Professional tutorials, specializing in crafting comprehensive guides to help you excel in your Java certification journey.","url":"https://www.guru99.com/author/james","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","url":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","caption":"James Hartman","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"JavaScript","headline":"JavaScript Define &#038; Call Functions with Example","description":"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 l","keywords":"javascript, java","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/james","name":"James Hartman"},"dateModified":"2026-07-29T17:23:52+05:30","image":{"@id":"https://www.guru99.com/images/javascript-define-call-functions.png"},"copyrightYear":"2026","name":"JavaScript Define &#038; Call Functions with Example","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What happens when a JavaScript function has no return statement?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"How can AI assistants help when writing JavaScript functions?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Can GitHub Copilot generate arrow functions and callbacks correctly?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"What is a closure in JavaScript?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"Can a JavaScript function call itself?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"What is an async function and how does await behave inside it?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"How do you call a JavaScript function from an HTML button?","acceptedAnswer":{"@type":"Answer","text":"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."}},{"@type":"Question","name":"What is the difference between calling a function and passing a reference to it?","acceptedAnswer":{"@type":"Answer","text":"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."}}]}],"@id":"https://www.guru99.com/learn-functions-in-javascript-in-5-minutes.html#schema-1154802","isPartOf":{"@id":"https://www.guru99.com/learn-functions-in-javascript-in-5-minutes.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/learn-functions-in-javascript-in-5-minutes.html#webpage"}}]}
```
