Concept Flow - Arrow functions
Start
Define arrow function
Call arrow function
Execute function body
Return result
End
This flow shows how an arrow function is defined, called, executed, and returns a result.
const add = (a, b) => a + b; const result = add(2, 3); console.log(result);
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Define arrow function 'add' | const add = (a, b) => a + b; | Function 'add' created |
| 2 | Call 'add' with arguments 2 and 3 | add(2, 3) | Function body executes with a=2, b=3 |
| 3 | Calculate a + b | 2 + 3 | 5 |
| 4 | Return result from function | return 5 | 5 |
| 5 | Assign returned value to 'result' | result = 5 | result is 5 |
| 6 | Print 'result' to console | console.log(result) | Output: 5 |
| Variable | Start | After Step 2 | After Step 5 | Final |
|---|---|---|---|---|
| add | undefined | function (a, b) => a + b | function (a, b) => a + b | function (a, b) => a + b |
| result | undefined | undefined | 5 | 5 |
Arrow functions use a short syntax: (params) => expression They automatically return the expression value if no braces are used. No 'function' keyword needed. Useful for concise functions. Example: const add = (a, b) => a + b;
arrow functions in JavaScript?a and b?(a, b) => a + b is valid.=> operator, syntax error. C: misses parentheses around parameters. D: lacks return statement inside braces.const numbers = [1, 2, 3]; const squares = numbers.map(n => n * n); console.log(squares);
map method applies the arrow function n => n * n to each element, squaring each number.const greet = name => {
console.log('Hello, ' + name);
};
greet();greet() without argument means name is undefined, so output will be 'Hello, undefined'. This is likely unintended.greet without an argument causes name to be undefined. -> Option Cfunction Counter() {
this.count = 0;
setInterval(() => {
this.count++;
console.log(this.count);
}, 1000);
}
const c = new Counter();setInterval works correctly to update this.count?this in arrow functionsthis. Instead, they use this from the surrounding function or object.setInterval, the arrow function uses this from Counter instance, so this.count correctly refers to the instance property.this, so they use this from the surrounding context. -> Option APass the test and this pattern moves unknown