What ways of creating functions do you know?
sobes.tech AI
Answer from AI
-
Function Declaration
// Function definition function greet(name) { return `Hello, ${name}!`; }Functions declared this way are available before the line where they are declared (hoisting).
-
Function Expression
// Assigning an anonymous function to a variable const greet = function(name) { return `Hello, ${name}!`; };The function is created at runtime, hoisting does not apply to the variable holding the function. It can be named or anonymous.
-
Arrow Function
// Concise function syntax const greet = (name) => { return `Hello, ${name}!`; }; // For a single parameter, parentheses can be omitted const greet = name => { return `Hello, ${name}!`; }; // If the function body consists of a single return, parentheses and return can be omitted const greet = name => `Hello, ${name}!`;Arrow functions lexically bind
this, do not have their ownarguments. They cannot be used as constructors. -
Function Constructor
// Using the Function constructor const greet = new Function('name', 'return "Hello, " + name + "!";');Functions are created dynamically from a string. Not recommended for regular use due to performance issues (double parsing) and security concerns (similar to eval).
-
Object Methods
// Function as an object property const person = { name: 'Ivan', greet: function() { // Function Expression as a method return `Hello, ${this.name}!`; }, sayHello() { // Concise method syntax (ES6) return `Hello, ${this.name}!`; } };Functions defined as object properties. The concise syntax (
sayHello()) is syntactic sugar forsayHello: function(). -
Generator Function
// A function that can pause and resume execution function* generateNumbers() { yield 1; yield 2; yield 3; }Uses
yieldto return intermediate values and create iterators. Defined with the syntaxfunction*. -
Async Functions
// Function working with promises async function fetchData() { const response = await fetch('...'); const data = await response.json(); return data; }Simplifies working with asynchronous code, allowing the use of
awaitto wait for promises in a non-blocking manner. Defined with the syntaxasync function.