Function Definitions in JavaScript
? Function Definitions in JavaScript
Ways to Define Functions in JavaScript
JavaScript supports several ways to define functions, each with its own use cases.
1. Function Declaration
function greet(name) { return "Hello, " + name;}Hoisted — can be called before definition.
Named function.
2. Function Expression
const greet = function(name) { return "Hello, " + name;};Not hoisted — only available after the assignment.
Can be anonymous or named.
3. Arrow Function (ES6+)
const greet = (name) => { return "Hello, " + name;};// Shorter syntax for single expressionconst greetShort = name => "Hello, " + name;No own
this,arguments, orsuper.Cannot be used as constructors.
Always anonymous.
4. Named Function Expression
const greet = function sayHello(name) { return "Hello, " + name;};Useful for recursion or better debugging.
Differences Summary
| Feature | Function Declaration | Function Expression | Arrow Function |
|---|---|---|---|
| Hoisted | Yes | No | No |
this binding | Dynamic | Dynamic | Lexical (from surrounding) |
| Can be constructor | Yes | Yes | No |
| Syntax | function name() {} | const f = function() {} | const f = () => {} |
Example Usage
function add(a, b) { return a + b;}const multiply = function(a, b) { return a * b;};const divide = (a, b) => a / b;console.log(add(2,3)); // 5console.log(multiply(2,3)); // 6console.log(divide(6,3)); // 2Want me to explain function scopes, hoisting in detail, or differences between this in functions vs arrow functions?