Functions
How functions work in JavaScript, differences between function declarations, expressions, and arrow functions.
Short explanation
Functions are fundamental units of behavior in JavaScript. They can be declared,
expressed, or created as arrow functions β each with subtle semantics (like
this binding) that affect how they behave on invocation.
Syntax examples
// Declaration
function greet(name) {
return `Hello, ${name}`;
}
// Function expression
const multiply = function (a, b) {
return a * b;
};
// Arrow function
const add = (a, b) => a + b;
How JS handles it internally
When a function is called, JavaScript creates an execution context containing
the function's scope, arguments, and local variables. The function's
[[Environment]] (closure) determines which variables it can access. Arrow
functions differ by not creating their own this binding and inheriting this
from the outer scope.
Related
π Related:
FAQ
Q: What's the main difference between arrow functions and declarations?
A: Arrow functions don't have their own this, arguments object, or prototype.
They are best for concise callbacks and when you want lexical this.
Q: Are functions objects?
A: Yes β functions in JavaScript are first-class objects and can have properties and be passed around like values.