Monday, June 30, 2025

javascript Module 21

  Module 21 : Function Expressions and Arrow Functions 

๐Ÿง  1. Introduction to Function Expressions

๐Ÿ”น What is a Function Expression?

A function expression is a way to define a function and assign it to a variable.








javascript code

const greet = function() { console.log("Hello from a function expression!"); }; greet(); // Output: Hello from a function expression!

๐Ÿ” Key Concepts:

Anonymous : Function expressions can be unnamed.

Assigned to Variables : They're stored in a variable.

Not Hoisted : Unlike function declarations, function expressions are not hoisted.


⚖️ 2. Function Declarations vs Function Expressions

Feature

Function Declaration

Function Expression

Syntax

function greet() {}

const greet = function() {}

Hoisting

Yes

No

Name

Required

Optional

Can be Immediately Invoked?

No

Yes (with IIFE)


๐Ÿ’ก Example:

javascript code

// Function Declaration sayHello(); function sayHello() { console.log("Hello!"); } // Function Expression // greet(); // ❌ Error: Cannot access before initialization const greet = function() { console.log("Hi!"); }; greet(); // ✅

 3. Arrow Functions (ES6)

Arrow functions are a concise way to write function expressions.











✅ Syntax:

javascript code

const greet = () => { console.log("Hello from arrow function!"); };

๐Ÿงช Shorter versions:

javascript code

const add = (a, b) => a + b; console.log(add(2, 3)); // Output: 5


๐Ÿ”ฅ 4. Arrow Function vs Function Expression

Feature

Arrow Function

Function Expression

Syntax

Shorter

Longer

this

Lexical this

Dynamic this

arguments object

Not available

Available

Usage in Classes

Not recommended for methods

Recommended


๐ŸŽฏ Lexical this Example:

javascript code

function Timer() { this.seconds = 0; setInterval(() => { this.seconds++; console.log(this.seconds); }, 1000); } new Timer(); // Works because arrow uses outer `this`

javascript code

function TimerBroken() { this.seconds = 0; setInterval(function() { this.seconds++; // `this` is undefined or global! console.log(this.seconds); }, 1000); } new TimerBroken(); // ❌


๐Ÿ› ️ 5. Methods and Use Cases











๐Ÿ“Œ Case 1: Filtering an Array

javascript code

const numbers = [1, 2, 3, 4, 5]; const even = numbers.filter(num => num % 2 === 0); console.log(even); // [2, 4]

๐Ÿ“Œ Case 2: Mapping to New Values


javascript code

const names = ['Alice', 'Bob', 'Charlie']; const nameLengths = names.map(name => name.length); console.log(nameLengths); // [5, 3, 7]


6. Explanation

 Build a calculator with function expressions and arrow functions

Objective: Implement basic calculator operations using both function expressions and arrow functions.

javascript code

// Function expressions const add = function(a, b) { return a + b; }; const subtract = function(a, b) { return a - b; }; // Arrow functions const multiply = (a, b) => a * b; const divide = (a, b) => (b !== 0 ? a / b : "Cannot divide by zero"); console.log(add(5, 3)); // 8 console.log(subtract(9, 4)); // 5 console.log(multiply(3, 7)); // 21 console.log(divide(10, 2)); // 5

Explanation:

Uses both styles to show their differences.

Demonstrates scope, return behavior, and usability.


๐Ÿ”ฌ 7. Advanced Concepts & search for Understanding








๐Ÿ“˜ search Insight: Why Arrow Functions Don’t Have Their Own this

Arrow functions were introduced in ES6 to simplify function syntax. But more importantly:

Arrow functions capture the this value of the enclosing context.

This is crucial in callbacks (e.g., setTimeout, array methods).

Research Snippet:

According to MDN: “An arrow function does not have its own bindings to this or super, and should not be used as methods.”

๐Ÿง  Use in React:

React developers often use arrow functions for inline handlers:

jsx code

<button onClick={() => this.handleClick()}>Click</button>

This avoids binding this manually in the constructor.


๐Ÿง‘‍๐Ÿซ 8. Exercises with Explanation

✅ Exercise 1: Convert function declaration to arrow function

javascript code

// Original function greet(name) { return "Hello " + name; } // Convert to arrow const greet = name => "Hello " + name;

✅ Exercise 2: Write a function that returns square of a number

javascript code

const square = n => n * n; console.log(square(4)); // 16

✅ Exercise 3: Create a custom map function using function expression

javascript code

const customMap = function(arr, fn) { const result = []; for (let i = 0; i < arr.length; i++) { result.push(fn(arr[i], i)); } return result; }; console.log(customMap([1, 2, 3], x => x * 10)); // [10, 20, 30]


 9. Summary

Function expressions assign functions to variables.

Arrow functions offer concise syntax and inherit this.

Arrow functions are excellent for short functions and callbacks.

Use function expressions or declarations when:

You need hoisting.

You need your own this or arguments object.


 10. Activity Summary

Create a program with:

           


Function expression for string manipulation.

Arrow function for numeric operations.

Callback usage with arrow functions in map, filter, etc.


๐Ÿ“š Resources

MDN: Function Expressions

MDN: Arrow Functions

JavaScript.info: Arrow functions


No comments:

Post a Comment

Javascript Module 24

  Javascript Module 24 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test A...