Functions in JavaScript¶
Function declaration¶
This is the most common way to declare a function in JavaScript. The function keyword is used, followed by the name of the function.
function myFunction(a, b) {
return a + b;
}
Function expression¶
A function expression is similar to a function declaration, except that it can be anonymous and it can be used as part of larger expressions.
let myFunction = function(a, b) {
return a + b;
};
Arrow functions¶
Arrow functions were introduced in ES6. They are a shorter syntax for writing function expressions. They are not named and are best suited for non-method functions.
let myFunction = (a, b) => {
return a + b;
};
Generators¶
Generator functions are a special kind of function that can be exited and later re-entered, with their context (variable bindings) saved across re-entrances.
function* myGenerator() {
yield 1;
yield 2;
yield 3;
}
Async functions¶
An async function is a function declared with the async keyword. Async functions are instances of the AsyncFunction constructor, and the await keyword is permitted within them.
async function myAsyncFunction() {
//...
}
Default parameters¶
In JavaScript, default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
function greet(name = "World") {
return `Hello, ${name}!`;
}
console.log(greet()); // Outputs: Hello, World!
console.log(greet("User")); // Outputs: Hello, User!
In the above example, if no argument is passed to the greet function, or if it is undefined, the function uses ‘World’ as the default value for the name parameter.
Note: When declaring functions, it’s important to understand the concept of hoisting. In JavaScript, function declarations are hoisted to the top of their current scope, which means they can be used before they’re declared in the code. However, function expressions (including those involving the var, let, const, and arrow function syntaxes) are not hoisted, which means they can’t be used before they’re defined.