Intern
In what cases can a function be used?
sobes.tech AI
Answer from AI
- When it is necessary to reuse a block of code without duplication.
- For structuring a program by dividing it into logical parts.
- To encapsulate logic, hiding implementation details.
- When working with asynchronous operations or events (e.g., callbacks).
- To create closures that retain access to variables from an outer scope.
- When defining methods of objects or classes.
- For data processing, for example, in array methods (
map,filter,reduce).
// Reuse
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('World');
greet('User');
// Callback for asynchronous operation
setTimeout(function() {
console.log('Executed after 1 second');
}, 1000);