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.
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
- Use the keyword function followed by the name of the function.
- After the function name, open and close parentheses.
- After parenthesis, open and close curly braces.
- 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
undefinedunless a default value is supplied, asgreetingis here. - Extra arguments are ignored by the parameter list but stay reachable through the
argumentsobject inside any non-arrow function. - A rest parameter written as
...valuescollects 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
varinside a function are visible throughout that function, whileletandconstare 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.
