ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://mimo.org/glossary/javascript/function |
| Last Crawled | 2026-04-10 19:00:32 (1 day ago) |
| First Indexed | 2023-02-07 01:20:15 (3 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Learn about Function in JavaScript to group related code |
| Meta Description | Explore JavaScript functions for modular and reusable code. From event handling to data processing, master function usage to code like a pro |
| Meta Canonical | null |
| Boilerpipe Text | JavaScript Function: Create and Call Functions in JS
In JavaScript, a function is a block of code that performs a specific task. By calling a function, you execute the function's code block.
How to Use JavaScript Functions
Defining Functions in JavaScript
To create a function in JavaScript, you need the
function
keyword, a name, and parentheses that may include parameters. Then, curly braces (
{}
) mark out the beginning and end of the function's body.
JSX
function
functionName
(
parameter1, parameter2
) {
// Block of reusable code
return
returnValue;
// Optional return statement
}
function
: The keyword to initiate the function statement.
functionName
: A unique identifier to name your function, following the JavaScript naming conventions.
parameter(s): Any number of variables listed inside the parentheses help pass data into the function (optional).
return
: The keyword that exits the function and usually returns the result of the function to its caller (optional).
returnValue
: A value or variable to return from the function (optional).
Calling Functions in JavaScript
To execute a function's code block, you need to call it by using its name along with parentheses.
JSX
functionName
(argument1, argument2);
function
: The keyword to start the function declaration.
argument(s): Values or variables to pass data into the function (if possible or required).
When to Use Functions in JavaScript
Functions in JavaScript encapsulate code that performs a specific task, making your code more readable, maintainable, and reusable. Here are several use cases:
Handling Events
You can use functions to handle events like clicks or key presses in web applications.
JSX
document
.
getElementById
(
"myButton"
).
addEventListener
(
"click"
,
function
(
) {
alert
(
"Button clicked!"
);
});
Organizing Complex Code
Using a function, you can organize complex code into a single code block you can call at any time.
JSX
function
calculateArea
(
radius
) {
return
Math
.
PI
* radius * radius;
}
console
.
log
(
calculateArea
(
5
));
// Output: 78.53981633974483
Repeating Actions
Functions are particularly great for grouping code you need to execute multiple times throughout your web application.
JSX
function
repeatLog
(
message, times
) {
for
(
let
i =
0
; i < times; i++) {
console
.
log
(message);
}
}
repeatLog
(
"Hello!"
,
3
);
Examples of JavaScript Functions
Functions are everywhere in JavaScript. Below are examples showcasing their common applications:
Form Validation
Functions can validate user inputs in forms, providing feedback or processing the data.
JSX
function
validateEmail
(
email
) {
const
re =
/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/
;
return
re.
test
(email);
}
console
.
log
(
validateEmail
(
"user@example.com"
));
// Output: true
Callbacks
You can pass functions as arguments to other functions, known as callbacks, allowing for asynchronous operations.
JSX
function
processData
(
callback
) {
let
data =
fetchData
();
// Assume fetchData gets data from an API
callback
(data);
}
processData
(
function
(
data
) {
console
.
log
(
"Data received:"
, data);
});
Array Operations
Functions are essential when working with
arrays
, especially with methods like
map
,
filter
, and
reduce
.
JSX
const
numbers = [
1
,
2
,
3
,
4
,
5
];
const
doubled = numbers.
map
(
function
(
number
) {
return
number *
2
;
});
console
.
log
(doubled);
// Output: [2, 4, 6, 8, 10]
Timeout and Interval
Functions manage timing through
setTimeout
and
setInterval
, allowing delayed and repeated actions.
JSX
setTimeout
(
function
(
) {
console
.
log
(
"This message is shown after 3 seconds."
);
},
3000
);
let
count =
0
;
const
intervalId =
setInterval
(
function
(
) {
count++;
console
.
log
(
"Interval tick"
, count);
if
(count >=
5
) {
clearInterval
(intervalId);
}
},
1000
);
Learn More About Functions in JavaScript
Async Function in JavaScript
Async functions can help you handle asynchronous operations. An async function enables pausing execution until a specific operation within its body is completed.
To create an async function, add the
async
keyword in front of the function's declaration.
JSX
async
function
fetchData
(
) {
let
response =
await
fetch
(
'https://api.example.com/data'
);
let
data =
await
response.
json
();
return
data;
}
Anonymous Function in JavaScript
Unlike regular functions, anonymous functions in JavaScript code have no name attached to them. Anonymous functions are useful for performing a quick operation where naming the function is unnecessary. A common use case for anonymous functions is in event listeners and timers.
JSX
setTimeout
(
function
(
) {
console
.
log
(
"This runs after 1 second."
);
},
1000
);
Arrow Function in JavaScript
JavaScript arrow functions are anonymous functions with a simpler syntax than traditional function expressions. An arrow function definition uses a pair of parentheses with the parameter list, an arrow (
=>
), and the function's body.
JSX
const
sum
= (
a, b
) => a + b;
console
.
log
(
sum
(
5
,
3
));
// Output: 8
If the function takes no parameters, you need to use an empty pair of parentheses before the arrow. Also, if the function body spans multiple lines, you need to use curly braces (
{}
) around it.
JSX
const
sayHelloHowAreYou
= (
) => {
console
.
log
(
"Hello!"
);
console
.
log
(
"How are you?"
);
};
Callback Function in JavaScript
A callback function is a function you pass into another function as an argument. The callback function is then called from inside the outer function to complete some kind of action. In JavaScript, callback functions are often anonymous functions or arrow functions.
JSX
function
loadScript
(
src, callback
) {
let
script =
document
.
createElement
(
'script'
);
script.
src
= src;
script.
onload
=
() =>
callback
(script);
document
.
head
.
append
(script);
}
loadScript
(
'script.js'
,
function
(
) {
console
.
log
(
'Script loaded successfully.'
);
});
Parameter Handling
JavaScript functions are flexible in how they handle parameters. Using the
arguments
object or rest parameters, functions can accept any number of parameters without specifying them individually in the function definition. This feature makes functions versatile for handling varying amounts of data.
JSX
function
sumAll
(
...args
) {
return
args.
reduce
(
(
acc, val
) =>
acc + val,
0
);
}
console
.
log
(
sumAll
(
1
,
2
,
3
,
4
));
// Output: 10 |
| Markdown | 
Learn
[Build](https://mimo.org/build)
Resources
[Pricing](https://mimo.org/pro)
[Log in](https://mimo.org/web/login)
[Sign up for free](https://mimo.org/web/register)
Learn
CAREER PATHS
[Full-Stack Development](https://mimo.org/courses/full-stack-development)[Front-End Development](https://mimo.org/courses/front-end-development)[Back-End Development](https://mimo.org/courses/back-end-development)[Python Development](https://mimo.org/courses/python-development)
COURSES
[HTML](https://mimo.org/courses/learn-html)[JavaScript](https://mimo.org/courses/learn-javascript)[React](https://mimo.org/courses/learn-react)[SQL](https://mimo.org/courses/learn-sql)
[CSS](https://mimo.org/courses/learn-css)[Typescript](https://mimo.org/courses/learn-typescript)[Python](https://mimo.org/courses/learn-python)[Swift](https://mimo.org/courses/learn-swift-programming)
Resources
[Glossary](https://mimo.org/glossary/html)[Tutorials](https://mimo.org/tutorials/html)[Learner stories](https://mimo.org/learner-stories)[Blog](https://mimo.org/blog)
[Pricing](https://mimo.org/pro)
Download
Coding Glossary
[HTML](https://mimo.org/glossary/html)
[CSS](https://mimo.org/glossary/css)
[JavaScript](https://mimo.org/glossary/javascript)
[Python](https://mimo.org/glossary/python)
[Swift](https://mimo.org/glossary/swift)
[TypeScript](https://mimo.org/glossary/typescript)
[SQL](https://mimo.org/glossary/sql)
[React](https://mimo.org/glossary/react)
[Programming Concepts](https://mimo.org/glossary/programming-concepts)
JavaScript Glossary
[HTML](https://mimo.org/glossary/html)[CSS](https://mimo.org/glossary/css)
[JavaScript](https://mimo.org/glossary/javascript)
[Python](https://mimo.org/glossary/python)[Swift](https://mimo.org/glossary/swift)[TypeScript](https://mimo.org/glossary/typescript)[SQL](https://mimo.org/glossary/sql)[React](https://mimo.org/glossary/react)[Programming Concepts](https://mimo.org/glossary/programming-concepts)
## All Terms & Concepts
- [What is JavaScript?](https://mimo.org/glossary/javascript)
- [Array() find](https://mimo.org/glossary/javascript/array-find)
- [\-- operator](https://mimo.org/glossary/javascript/minus-minus-operator)
- [\-= operator](https://mimo.org/glossary/javascript/minus-equal-operator)
- [\++ operator](https://mimo.org/glossary/javascript/plus-plus-operator)
- [\+= operator](https://mimo.org/glossary/javascript/+=-operator)
- [Accessing and setting content](https://mimo.org/glossary/javascript/accessing-and-setting-content)
- [AND operator](https://mimo.org/glossary/javascript/and-operator)
- [Array concat() method](https://mimo.org/glossary/javascript/array-concatenation)
- [Array indexOf()](https://mimo.org/glossary/javascript/array-indexof-method)
- [Array length](https://mimo.org/glossary/javascript/array-length)
- [Array pop()](https://mimo.org/glossary/javascript/array-pop)
- [Array shift](https://mimo.org/glossary/javascript/array-shift)
- [Array slice() method](https://mimo.org/glossary/javascript/array-slice)
- [Arrays](https://mimo.org/glossary/javascript/arrays)
- [Arrow function](https://mimo.org/glossary/javascript/arrow-function)
- [Async await](https://mimo.org/glossary/javascript/async-await)
- [Booleans](https://mimo.org/glossary/javascript/booleans)
- [Braces](https://mimo.org/glossary/javascript/braces)
- [Callback function](https://mimo.org/glossary/javascript/callback-function)
- [Calling the function](https://mimo.org/glossary/javascript/calling-the-function)
- [Class](https://mimo.org/glossary/javascript/class)
- [Closure](https://mimo.org/glossary/javascript/closure)
- [Code block](https://mimo.org/glossary/javascript/code-block)
- [Comment](https://mimo.org/glossary/javascript/comment)
- [Conditions](https://mimo.org/glossary/javascript/conditions)
- [Console](https://mimo.org/glossary/javascript/console)
- [const](https://mimo.org/glossary/javascript/const)
- [Constructor](https://mimo.org/glossary/javascript/constructor)
- [Creating a p element](https://mimo.org/glossary/javascript/creating-a-p-element)
- [Data types](https://mimo.org/glossary/javascript/data-types)
- [Date getTime()](https://mimo.org/glossary/javascript/date-gettime)
- [Destructuring](https://mimo.org/glossary/javascript/destructuring)
- [DOM](https://mimo.org/glossary/javascript/dom)
- [Else](https://mimo.org/glossary/javascript/else)
- [Else if](https://mimo.org/glossary/javascript/else-if)
- [Enum](https://mimo.org/glossary/javascript/enum)
- [Environment](https://mimo.org/glossary/javascript/environment)
- [Equals operator](https://mimo.org/glossary/javascript/equality-operator)
- [Error Handling](https://mimo.org/glossary/javascript/error-handling)
- [ES6](https://mimo.org/glossary/javascript/es6)
- [Event listener method](https://mimo.org/glossary/javascript/event-listener-method)
- [Event loop](https://mimo.org/glossary/javascript/event-loop)
- [Events](https://mimo.org/glossary/javascript/events)
- [Export statement](https://mimo.org/glossary/javascript/export-statement)
- [Extends](https://mimo.org/glossary/javascript/extends)
- [Fetch API](https://mimo.org/glossary/javascript/fetch-api)
- [Filter](https://mimo.org/glossary/javascript/filter)
- [For loop](https://mimo.org/glossary/javascript/for-loops)
- [forEach()](https://mimo.org/glossary/javascript/foreach)
- [Function](https://mimo.org/glossary/javascript/function)
- [Function bind()](https://mimo.org/glossary/javascript/function-bind-method)
- [Function name](https://mimo.org/glossary/javascript/function-name)
- [Greater than](https://mimo.org/glossary/javascript/greater-than)
- [Head element](https://mimo.org/glossary/javascript/head-element)
- [Hoisting](https://mimo.org/glossary/javascript/hoisting)
- [If statement](https://mimo.org/glossary/javascript/if-statement)
- [Import statement](https://mimo.org/glossary/javascript/import-statement)
- [includes()](https://mimo.org/glossary/javascript/includes-method)
- [Infinity property](https://mimo.org/glossary/javascript/infinity-property)
- [isNaN function](https://mimo.org/glossary/javascript/isnan-function)
- [Iterator](https://mimo.org/glossary/javascript/iterator)
- [JSON](https://mimo.org/glossary/javascript/json)
- [Less than](https://mimo.org/glossary/javascript/less-than)
- [Let](https://mimo.org/glossary/javascript/let)
- [Local storage](https://mimo.org/glossary/javascript/local-storage)
- [Map](https://mimo.org/glossary/javascript/map)
- [Methods](https://mimo.org/glossary/javascript/methods)
- [Module](https://mimo.org/glossary/javascript/module)
- [Modulo operator](https://mimo.org/glossary/javascript/modulo-operator)
- [Node.js](https://mimo.org/glossary/javascript/nodejs)
- [null](https://mimo.org/glossary/javascript/null)
- [Numbers](https://mimo.org/glossary/javascript/numbers)
- [Object](https://mimo.org/glossary/javascript/object)
- [Object.keys()](https://mimo.org/glossary/javascript/object-keys-method)
- [Optional chaining](https://mimo.org/glossary/javascript/optional-chaining)
- [Overriding methods](https://mimo.org/glossary/javascript/overriding-methods)
- [Parameters](https://mimo.org/glossary/javascript/parameters)
- [Promises](https://mimo.org/glossary/javascript/promises)
- [Prototype](https://mimo.org/glossary/javascript/prototype)
- [Random](https://mimo.org/glossary/javascript/random)
- [Reduce](https://mimo.org/glossary/javascript/reduce)
- [Regex](https://mimo.org/glossary/javascript/regex)
- [Regular expressions](https://mimo.org/glossary/javascript/regular-expressions)
- [Removing an element](https://mimo.org/glossary/javascript/removing-an-element)
- [Replace](https://mimo.org/glossary/javascript/replace)
- [Scope](https://mimo.org/glossary/javascript/scope)
- [Session storage](https://mimo.org/glossary/javascript/session-storage)
- [setInterval](https://mimo.org/glossary/javascript/setinterval)
- [setTimeout() method](https://mimo.org/glossary/javascript/settimeout)
- [Sleep() function](https://mimo.org/glossary/javascript/sleep-function)
- [Sort](https://mimo.org/glossary/javascript/sort)
- [Splice](https://mimo.org/glossary/javascript/splice)
- [Spread operator](https://mimo.org/glossary/javascript/spread-operator)
- [String](https://mimo.org/glossary/javascript/strings)
- [String concat()](https://mimo.org/glossary/javascript/string-concatenation)
- [String indexOf()](https://mimo.org/glossary/javascript/string-indexof-method)
- [String slice() method](https://mimo.org/glossary/javascript/string-slice)
- [Substring](https://mimo.org/glossary/javascript/substring)
- [Switch statement](https://mimo.org/glossary/javascript/switch-statement)
- [Template literals](https://mimo.org/glossary/javascript/template-literals)
- [Ternary operator](https://mimo.org/glossary/javascript/ternary-operator)
- [throw Statement](https://mimo.org/glossary/javascript/throw-error)
- [Title](https://mimo.org/glossary/javascript/title)
- [Try catch](https://mimo.org/glossary/javascript/try-catch)
- [Type conversion](https://mimo.org/glossary/javascript/type-conversion)
- [undefined](https://mimo.org/glossary/javascript/undefined)
- [var](https://mimo.org/glossary/javascript/var)
- [void Operator](https://mimo.org/glossary/javascript/void-operator)
- [While loop](https://mimo.org/glossary/javascript/while-loops)
JAVASCRIPT
# JavaScript Function: Create and Call Functions in JS
In JavaScript, a function is a block of code that performs a specific task. By calling a function, you execute the function's code block.
## How to Use JavaScript Functions
### Defining Functions in JavaScript
To create a function in JavaScript, you need the `function` keyword, a name, and parentheses that may include parameters. Then, curly braces (`{}`) mark out the beginning and end of the function's body.
## Learn JavaScript on Mimo
[CAREER PATHFull-Stack Developer Become a full-stack developer. Learn HTML, CSS, JavaScript, and React as well as NodeJS, Express, and SQLBeginner friendly](https://mimo.org/courses/full-stack-development)
[COURSEJavaScript Master the language of the web. Learn variables, functions, objects, and modern ES6+ featuresBeginner friendly](https://mimo.org/courses/learn-javascript)
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
function functionName(parameter1, parameter2) {
// Block of reusable code
return returnValue; // Optional return statement
}
```
- `function`: The keyword to initiate the function statement.
- `functionName`: A unique identifier to name your function, following the JavaScript naming conventions.
- parameter(s): Any number of variables listed inside the parentheses help pass data into the function (optional).
- `return`: The keyword that exits the function and usually returns the result of the function to its caller (optional).
- `returnValue`: A value or variable to return from the function (optional).
### Calling Functions in JavaScript
To execute a function's code block, you need to call it by using its name along with parentheses.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
functionName(argument1, argument2);
```
- `function`: The keyword to start the function declaration.
- argument(s): Values or variables to pass data into the function (if possible or required).
## When to Use Functions in JavaScript
Functions in JavaScript encapsulate code that performs a specific task, making your code more readable, maintainable, and reusable. Here are several use cases:
### Handling Events
You can use functions to handle events like clicks or key presses in web applications.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
```
### Organizing Complex Code
Using a function, you can organize complex code into a single code block you can call at any time.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
function calculateArea(radius) {
return Math.PI * radius * radius;
}
console.log(calculateArea(5)); // Output: 78.53981633974483
```
### Repeating Actions
Functions are particularly great for grouping code you need to execute multiple times throughout your web application.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
function repeatLog(message, times) {
for (let i = 0; i < times; i++) {
console.log(message);
}
}
repeatLog("Hello!", 3);
```
## Examples of JavaScript Functions
Functions are everywhere in JavaScript. Below are examples showcasing their common applications:
### Form Validation
Functions can validate user inputs in forms, providing feedback or processing the data.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
function validateEmail(email) {
const re = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
return re.test(email);
}
console.log(validateEmail("user@example.com")); // Output: true
```
### Callbacks
You can pass functions as arguments to other functions, known as callbacks, allowing for asynchronous operations.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
function processData(callback) {
let data = fetchData(); // Assume fetchData gets data from an API
callback(data);
}
processData(function(data) {
console.log("Data received:", data);
});
```
### Array Operations
Functions are essential when working with [arrays](https://mimo.org/glossary/javascript/arrays), especially with methods like `map`, `filter`, and `reduce`.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(number) {
return number * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8, 10]
```
### Timeout and Interval
Functions manage timing through [`setTimeout`](https://mimo.org/glossary/javascript/settimeout) and `setInterval`, allowing delayed and repeated actions.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
setTimeout(function() {
console.log("This message is shown after 3 seconds.");
}, 3000);
let count = 0;
const intervalId = setInterval(function() {
count++;
console.log("Interval tick", count);
if (count >= 5) {
clearInterval(intervalId);
}
}, 1000);
```
## Learn More About Functions in JavaScript
### Async Function in JavaScript
Async functions can help you handle asynchronous operations. An async function enables pausing execution until a specific operation within its body is completed.
To create an async function, add the `async` keyword in front of the function's declaration.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
return data;
}
```
### Anonymous Function in JavaScript
Unlike regular functions, anonymous functions in JavaScript code have no name attached to them. Anonymous functions are useful for performing a quick operation where naming the function is unnecessary. A common use case for anonymous functions is in event listeners and timers.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
setTimeout(function() {
console.log("This runs after 1 second.");
}, 1000);
```
### **Arrow Function in JavaScript**
JavaScript arrow functions are anonymous functions with a simpler syntax than traditional function expressions. An arrow function definition uses a pair of parentheses with the parameter list, an arrow (`=>`), and the function's body.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
const sum = (a, b) => a + b;
console.log(sum(5, 3)); // Output: 8
```
If the function takes no parameters, you need to use an empty pair of parentheses before the arrow. Also, if the function body spans multiple lines, you need to use curly braces (`{}`) around it.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
const sayHelloHowAreYou = () => {
console.log("Hello!");
console.log("How are you?");
};
```
### Callback Function in JavaScript
A callback function is a function you pass into another function as an argument. The callback function is then called from inside the outer function to complete some kind of action. In JavaScript, callback functions are often anonymous functions or arrow functions.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
function loadScript(src, callback) {
let script = document.createElement('script');
script.src = src;
script.onload = () => callback(script);
document.head.append(script);
}
loadScript('script.js', function() {
console.log('Script loaded successfully.');
});
```
### Parameter Handling
JavaScript functions are flexible in how they handle parameters. Using the `arguments` object or rest parameters, functions can accept any number of parameters without specifying them individually in the function definition. This feature makes functions versatile for handling varying amounts of data.
JSX
[Open in Mimo](https://app.adjust.com/1bbdlllf)
[Open in Mimo](https://mimo.org/web/register)
Copy Code
```
function sumAll(...args) {
return args.reduce((acc, val) => acc + val, 0);
}
console.log(sumAll(1, 2, 3, 4)); // Output: 10
```
Join 35M+ people learning for free on Mimo



35M+
[CAREER PATHFull-Stack Developer Become a full-stack developer. Learn HTML, CSS, JavaScript, and React as well as NodeJS, Express, and SQLBeginner friendly](https://mimo.org/courses/full-stack-development)
[COURSEJavaScript Master the language of the web. Learn variables, functions, objects, and modern ES6+ featuresBeginner friendly](https://mimo.org/courses/learn-javascript)
4\.8 out of 5 across 1M+ reviews
Check us out on Apple [AppStore](https://itunes.apple.com/us/app/mimo-learn-how-to-code-through/id1133960732?mt=8&at=1000lpyT), [Google Play Store](https://play.google.com/store/apps/details?id=com.getmimo), and [Trustpilot](https://www.trustpilot.com/review/mimo.org)
All Terms & Concepts
- [What is JavaScript?](https://mimo.org/glossary/javascript)
- [Array() find](https://mimo.org/glossary/javascript/array-find)
- [\-- operator](https://mimo.org/glossary/javascript/minus-minus-operator)
- [\-= operator](https://mimo.org/glossary/javascript/minus-equal-operator)
- [\++ operator](https://mimo.org/glossary/javascript/plus-plus-operator)
- [\+= operator](https://mimo.org/glossary/javascript/+=-operator)
- [Accessing and setting content](https://mimo.org/glossary/javascript/accessing-and-setting-content)
- [AND operator](https://mimo.org/glossary/javascript/and-operator)
- [Array concat() method](https://mimo.org/glossary/javascript/array-concatenation)
- [Array indexOf()](https://mimo.org/glossary/javascript/array-indexof-method)
- [Array length](https://mimo.org/glossary/javascript/array-length)
- [Array pop()](https://mimo.org/glossary/javascript/array-pop)
- [Array shift](https://mimo.org/glossary/javascript/array-shift)
- [Array slice() method](https://mimo.org/glossary/javascript/array-slice)
- [Arrays](https://mimo.org/glossary/javascript/arrays)
- [Arrow function](https://mimo.org/glossary/javascript/arrow-function)
- [Async await](https://mimo.org/glossary/javascript/async-await)
- [Booleans](https://mimo.org/glossary/javascript/booleans)
- [Braces](https://mimo.org/glossary/javascript/braces)
- [Callback function](https://mimo.org/glossary/javascript/callback-function)
- [Calling the function](https://mimo.org/glossary/javascript/calling-the-function)
- [Class](https://mimo.org/glossary/javascript/class)
- [Closure](https://mimo.org/glossary/javascript/closure)
- [Code block](https://mimo.org/glossary/javascript/code-block)
- [Comment](https://mimo.org/glossary/javascript/comment)
- [Conditions](https://mimo.org/glossary/javascript/conditions)
- [Console](https://mimo.org/glossary/javascript/console)
- [const](https://mimo.org/glossary/javascript/const)
- [Constructor](https://mimo.org/glossary/javascript/constructor)
- [Creating a p element](https://mimo.org/glossary/javascript/creating-a-p-element)
- [Data types](https://mimo.org/glossary/javascript/data-types)
- [Date getTime()](https://mimo.org/glossary/javascript/date-gettime)
- [Destructuring](https://mimo.org/glossary/javascript/destructuring)
- [DOM](https://mimo.org/glossary/javascript/dom)
- [Else](https://mimo.org/glossary/javascript/else)
- [Else if](https://mimo.org/glossary/javascript/else-if)
- [Enum](https://mimo.org/glossary/javascript/enum)
- [Environment](https://mimo.org/glossary/javascript/environment)
- [Equals operator](https://mimo.org/glossary/javascript/equality-operator)
- [Error Handling](https://mimo.org/glossary/javascript/error-handling)
- [ES6](https://mimo.org/glossary/javascript/es6)
- [Event listener method](https://mimo.org/glossary/javascript/event-listener-method)
- [Event loop](https://mimo.org/glossary/javascript/event-loop)
- [Events](https://mimo.org/glossary/javascript/events)
- [Export statement](https://mimo.org/glossary/javascript/export-statement)
- [Extends](https://mimo.org/glossary/javascript/extends)
- [Fetch API](https://mimo.org/glossary/javascript/fetch-api)
- [Filter](https://mimo.org/glossary/javascript/filter)
- [For loop](https://mimo.org/glossary/javascript/for-loops)
- [forEach()](https://mimo.org/glossary/javascript/foreach)
- [Function](https://mimo.org/glossary/javascript/function)
- [Function bind()](https://mimo.org/glossary/javascript/function-bind-method)
- [Function name](https://mimo.org/glossary/javascript/function-name)
- [Greater than](https://mimo.org/glossary/javascript/greater-than)
- [Head element](https://mimo.org/glossary/javascript/head-element)
- [Hoisting](https://mimo.org/glossary/javascript/hoisting)
- [If statement](https://mimo.org/glossary/javascript/if-statement)
- [Import statement](https://mimo.org/glossary/javascript/import-statement)
- [includes()](https://mimo.org/glossary/javascript/includes-method)
- [Infinity property](https://mimo.org/glossary/javascript/infinity-property)
- [isNaN function](https://mimo.org/glossary/javascript/isnan-function)
- [Iterator](https://mimo.org/glossary/javascript/iterator)
- [JSON](https://mimo.org/glossary/javascript/json)
- [Less than](https://mimo.org/glossary/javascript/less-than)
- [Let](https://mimo.org/glossary/javascript/let)
- [Local storage](https://mimo.org/glossary/javascript/local-storage)
- [Map](https://mimo.org/glossary/javascript/map)
- [Methods](https://mimo.org/glossary/javascript/methods)
- [Module](https://mimo.org/glossary/javascript/module)
- [Modulo operator](https://mimo.org/glossary/javascript/modulo-operator)
- [Node.js](https://mimo.org/glossary/javascript/nodejs)
- [null](https://mimo.org/glossary/javascript/null)
- [Numbers](https://mimo.org/glossary/javascript/numbers)
- [Object](https://mimo.org/glossary/javascript/object)
- [Object.keys()](https://mimo.org/glossary/javascript/object-keys-method)
- [Optional chaining](https://mimo.org/glossary/javascript/optional-chaining)
- [Overriding methods](https://mimo.org/glossary/javascript/overriding-methods)
- [Parameters](https://mimo.org/glossary/javascript/parameters)
- [Promises](https://mimo.org/glossary/javascript/promises)
- [Prototype](https://mimo.org/glossary/javascript/prototype)
- [Random](https://mimo.org/glossary/javascript/random)
- [Reduce](https://mimo.org/glossary/javascript/reduce)
- [Regex](https://mimo.org/glossary/javascript/regex)
- [Regular expressions](https://mimo.org/glossary/javascript/regular-expressions)
- [Removing an element](https://mimo.org/glossary/javascript/removing-an-element)
- [Replace](https://mimo.org/glossary/javascript/replace)
- [Scope](https://mimo.org/glossary/javascript/scope)
- [Session storage](https://mimo.org/glossary/javascript/session-storage)
- [setInterval](https://mimo.org/glossary/javascript/setinterval)
- [setTimeout() method](https://mimo.org/glossary/javascript/settimeout)
- [Sleep() function](https://mimo.org/glossary/javascript/sleep-function)
- [Sort](https://mimo.org/glossary/javascript/sort)
- [Splice](https://mimo.org/glossary/javascript/splice)
- [Spread operator](https://mimo.org/glossary/javascript/spread-operator)
- [String](https://mimo.org/glossary/javascript/strings)
- [String concat()](https://mimo.org/glossary/javascript/string-concatenation)
- [String indexOf()](https://mimo.org/glossary/javascript/string-indexof-method)
- [String slice() method](https://mimo.org/glossary/javascript/string-slice)
- [Substring](https://mimo.org/glossary/javascript/substring)
- [Switch statement](https://mimo.org/glossary/javascript/switch-statement)
- [Template literals](https://mimo.org/glossary/javascript/template-literals)
- [Ternary operator](https://mimo.org/glossary/javascript/ternary-operator)
- [throw Statement](https://mimo.org/glossary/javascript/throw-error)
- [Title](https://mimo.org/glossary/javascript/title)
- [Try catch](https://mimo.org/glossary/javascript/try-catch)
- [Type conversion](https://mimo.org/glossary/javascript/type-conversion)
- [undefined](https://mimo.org/glossary/javascript/undefined)
- [var](https://mimo.org/glossary/javascript/var)
- [void Operator](https://mimo.org/glossary/javascript/void-operator)
- [While loop](https://mimo.org/glossary/javascript/while-loops)
You can code, too.
##### Company
[Careers](https://jobs.mimo.org/)
[Blog](https://mimo.org/blog)
[Jobs](https://jobs.mimo.org/#jobs-1d547bc0)
##### Product
[App](https://mimo.org/mimo-coding-app)
[Courses](https://mimo.org/courses)
[Certifications](https://mimo.org/certifications)
[Glossary](https://mimo.org/glossary/html)
[Code Compilers](https://mimo.org/code-compilers)
[Learning Experience](https://mimo.org/learn-to-code-with-ai)
[Building Experience](https://mimo.org/learn-to-code-and-build-apps-with-ai)
##### Useful
[Press Kit](https://mimo.org/press-kit)
[Imprint](https://mimo.org/legal)
[Help](https://getmimo.zendesk.com/hc/en-us)
[Terms of Use](https://mimo.org/terms)
[Privacy Policy](https://mimo.org/privacy)
##### Follow us
© 2026 Mimo GmbH |
| Readable Markdown | ## JavaScript Function: Create and Call Functions in JS
In JavaScript, a function is a block of code that performs a specific task. By calling a function, you execute the function's code block.
## How to Use JavaScript Functions
### Defining Functions in JavaScript
To create a function in JavaScript, you need the `function` keyword, a name, and parentheses that may include parameters. Then, curly braces (`{}`) mark out the beginning and end of the function's body.
JSX
```
function functionName(parameter1, parameter2) {
// Block of reusable code
return returnValue; // Optional return statement
}
```
- `function`: The keyword to initiate the function statement.
- `functionName`: A unique identifier to name your function, following the JavaScript naming conventions.
- parameter(s): Any number of variables listed inside the parentheses help pass data into the function (optional).
- `return`: The keyword that exits the function and usually returns the result of the function to its caller (optional).
- `returnValue`: A value or variable to return from the function (optional).
### Calling Functions in JavaScript
To execute a function's code block, you need to call it by using its name along with parentheses.
JSX
```
functionName(argument1, argument2);
```
- `function`: The keyword to start the function declaration.
- argument(s): Values or variables to pass data into the function (if possible or required).
## When to Use Functions in JavaScript
Functions in JavaScript encapsulate code that performs a specific task, making your code more readable, maintainable, and reusable. Here are several use cases:
### Handling Events
You can use functions to handle events like clicks or key presses in web applications.
JSX
```
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
```
### Organizing Complex Code
Using a function, you can organize complex code into a single code block you can call at any time.
JSX
```
function calculateArea(radius) {
return Math.PI * radius * radius;
}
console.log(calculateArea(5)); // Output: 78.53981633974483
```
### Repeating Actions
Functions are particularly great for grouping code you need to execute multiple times throughout your web application.
JSX
```
function repeatLog(message, times) {
for (let i = 0; i < times; i++) {
console.log(message);
}
}
repeatLog("Hello!", 3);
```
## Examples of JavaScript Functions
Functions are everywhere in JavaScript. Below are examples showcasing their common applications:
### Form Validation
Functions can validate user inputs in forms, providing feedback or processing the data.
JSX
```
function validateEmail(email) {
const re = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
return re.test(email);
}
console.log(validateEmail("user@example.com")); // Output: true
```
### Callbacks
You can pass functions as arguments to other functions, known as callbacks, allowing for asynchronous operations.
JSX
```
function processData(callback) {
let data = fetchData(); // Assume fetchData gets data from an API
callback(data);
}
processData(function(data) {
console.log("Data received:", data);
});
```
### Array Operations
Functions are essential when working with [arrays](https://mimo.org/glossary/javascript/arrays), especially with methods like `map`, `filter`, and `reduce`.
JSX
```
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(number) {
return number * 2;
});
console.log(doubled); // Output: [2, 4, 6, 8, 10]
```
### Timeout and Interval
Functions manage timing through [`setTimeout`](https://mimo.org/glossary/javascript/settimeout) and `setInterval`, allowing delayed and repeated actions.
JSX
```
setTimeout(function() {
console.log("This message is shown after 3 seconds.");
}, 3000);
let count = 0;
const intervalId = setInterval(function() {
count++;
console.log("Interval tick", count);
if (count >= 5) {
clearInterval(intervalId);
}
}, 1000);
```
## Learn More About Functions in JavaScript
### Async Function in JavaScript
Async functions can help you handle asynchronous operations. An async function enables pausing execution until a specific operation within its body is completed.
To create an async function, add the `async` keyword in front of the function's declaration.
JSX
```
async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
return data;
}
```
### Anonymous Function in JavaScript
Unlike regular functions, anonymous functions in JavaScript code have no name attached to them. Anonymous functions are useful for performing a quick operation where naming the function is unnecessary. A common use case for anonymous functions is in event listeners and timers.
JSX
```
setTimeout(function() {
console.log("This runs after 1 second.");
}, 1000);
```
### **Arrow Function in JavaScript**
JavaScript arrow functions are anonymous functions with a simpler syntax than traditional function expressions. An arrow function definition uses a pair of parentheses with the parameter list, an arrow (`=>`), and the function's body.
JSX
```
const sum = (a, b) => a + b;
console.log(sum(5, 3)); // Output: 8
```
If the function takes no parameters, you need to use an empty pair of parentheses before the arrow. Also, if the function body spans multiple lines, you need to use curly braces (`{}`) around it.
JSX
```
const sayHelloHowAreYou = () => {
console.log("Hello!");
console.log("How are you?");
};
```
### Callback Function in JavaScript
A callback function is a function you pass into another function as an argument. The callback function is then called from inside the outer function to complete some kind of action. In JavaScript, callback functions are often anonymous functions or arrow functions.
JSX
```
function loadScript(src, callback) {
let script = document.createElement('script');
script.src = src;
script.onload = () => callback(script);
document.head.append(script);
}
loadScript('script.js', function() {
console.log('Script loaded successfully.');
});
```
### Parameter Handling
JavaScript functions are flexible in how they handle parameters. Using the `arguments` object or rest parameters, functions can accept any number of parameters without specifying them individually in the function definition. This feature makes functions versatile for handling varying amounts of data.
JSX
```
function sumAll(...args) {
return args.reduce((acc, val) => acc + val, 0);
}
console.log(sumAll(1, 2, 3, 4)); // Output: 10
``` |
| Shard | 154 (laksa) |
| Root Hash | 8895701236557990354 |
| Unparsed URL | org,mimo!/glossary/javascript/function s443 |