JavaScript Functions Documentation
1. Introduction
Welcome to the documentation for JavaScript Functions. This section provides an overview of Javascript Functions and its functionality.
2. Regular Function Declaration
Regular functions are defined using the keyword function
.
They have a name, which in this case is getRandomInt
. These
functions can be called using their name and are often used for reusable
pieces of code.
function
getRandomInt (min
, max
) {
return
Math.floor(Math.random() * (max
+ 1
- min
) + min
);
}
Example usage:
const
regularFunctionResult = getRandomInt(1
, 100
);
console.log(regularFunctionResult);
3. Anonymous Function (Function Expression)
Anonymous functions, also known as function expressions, are defined without a name. They are often assigned to a variable. These functions can be useful when you need a function for a short-lived purpose or as an argument to another function.
const
getRandomIntAnonymousFunction = function
(min
, max
) {
return
Math.floor(Math.random() * (max
+ 1
- min
) + min
);
};
Example usage:
const
anonymousFunctionResult = getRandomIntAnonymousFunction(1
, 100
);
console.log(anonymousFunctionResult);
4. Arrow Functions
Arrow functions are a concise way to write functions in JavaScript. They have a shorter syntax compared to regular functions and do not bind their own 'this'.
4.1 Arrow Function Syntax
const
getRandomIntArrowFunction = (min
, max
) => {
return
Math.floor(Math.random() * (max
+ 1
- min
) + min
);
};
Example usage:
const
arrowFunctionResult = getRandomIntArrowFunction(1
, 100
);
console.log(arrowFunctionResult);
4.2 Arrow Function One-Liner
const
getRandomIntArrowFunctionOneLiner = (min
, max
) => Math.floor(Math.random() * (max
+ 1
- min
) + min
);
Example usage:
const
oneLinerResult = getRandomIntArrowFunctionOneLiner(1
, 100
);
console.log(oneLinerResult);
5. Async Functions
Async functions are a feature introduced in ECMAScript 2017 (ES8). They provide a cleaner and more concise way to work with asynchronous code in JavaScript. An async function returns a promise implicitly, allowing you to write asynchronous code that looks synchronous.
The syntax for defining an async function is similar to regular functions,
but with the async
keyword preceding the function
declaration. Inside an async function, you can use the
await
keyword to pause the execution and wait for a promise
to resolve before continuing.
async
function fetchData() {
const
response = await
fetch('https://api.example.com/data');
const
data = await
response.json();
return
data;
}
Example usage:
fetchData()
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Async functions are commonly used when working with asynchronous operations such as fetching data from a server, reading files, or making network requests.