Js Arrow Function in JavaScript
? JavaScript Arrow Functions
What is an Arrow Function?
A concise syntax for writing functions introduced in ES6.
Automatically binds the
thisvalue to the surrounding context.Ideal for short functions and callbacks.
Basic Syntax
// Traditional functionfunction add(a, b) { return a + b;}// Arrow functionconst add = (a, b) => { return a + b;};More Concise Variants
1. Single Expression — Implicit Return
If the function body is a single expression, you can omit {} and return:
const add = (a, b) => a + b;console.log(add(2, 3)); // 52. Single Parameter — Parentheses Optional
const square = x => x * x;console.log(square(4)); // 163. No Parameters
const greet = () => console.log("Hello!");greet(); // Hello!Differences From Regular Functions
Arrow functions do not have their own
this,arguments, orsuper.Useful to avoid common
thispitfalls in callbacks.Cannot be used as constructors (
newkeyword).No
prototypeproperty.
Examples
const nums = [1, 2, 3];// Using arrow function with forEachnums.forEach(n => console.log(n * 2)); // 2, 4, 6// Arrow function in object method (this refers to outer context)const obj = { value: 42, method: () => console.log(this.value) // 'this' is NOT obj};obj.method(); // undefined (or global this.value)Want examples showing arrow functions vs regular functions with this?