Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
27 views30 pages

Functions in JSES6

This document provides an overview of functions in JavaScript, focusing on the enhancements introduced in ES6, such as default parameters, arrow functions, and block scoping. It explains the differences between function declarations and expressions, the use of callbacks, and the behavior of 'this' in traditional versus arrow functions. Additionally, it discusses practical applications of rest parameters and the integration of arrow functions in modern frameworks like React and Next.js.

Uploaded by

waqasiqbal1177
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views30 pages

Functions in JSES6

This document provides an overview of functions in JavaScript, focusing on the enhancements introduced in ES6, such as default parameters, arrow functions, and block scoping. It explains the differences between function declarations and expressions, the use of callbacks, and the behavior of 'this' in traditional versus arrow functions. Additionally, it discusses practical applications of rest parameters and the integration of arrow functions in modern frameworks like React and Next.js.

Uploaded by

waqasiqbal1177
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

4/27/2024

Functions in ES6
4/27/2024

Welcome to JavaScript
Functions
• Today, we'll explore how functions have evolved with ES6 to
make coding more efficient and readable
4/27/2024

Introduction to Functions in
JavaScript
• Definition: In JavaScript, a function is a reusable block of code designed to perform a specific
task. Functions are executed when they are called or invoked.
• Purpose: Functions allow you to define code once and use it many times. They can be used to
perform calculations, manipulate data, and handle repetitive tasks efficiently.
• Scope and Closure: Functions provide scope and help manage data privacy through closures,
allowing programmers to protect variables within the function from being accessed externally.

/// Function declaration


function greet() {
console.log("Hello, world!");
}

// Calling the function


greet(); // Output: Hello, world!
4/27/2024

Types of Functions: Declarations


vs. Expressions
• Function Declarations: A traditional way of defining functions. They are hoisted,
meaning they can be called before they are defined in the script.
• Function Expressions: Created by assigning a function to a variable. They are not
hoisted, so they cannot be called before they are defined.

// Function Declaration
function sayHello() {
console.log("Hello from a function declaration!");
}

// Function Expression
const sayGoodbye = function() {
console.log("Goodbye from a function expression!");
};
4/27/2024

Choosing Between Function


Declarations and Function
Expressions
• Function Declarations:
 Use when you need a function to be available throughout its scope before its
actual declaration.
 Ideal for top-level function definitions and when functions need to be called
from different parts of your script due to their hoisting behavior.

• Function Expressions:
 Preferable when functions need to be defined conditionally or as part of an
expression.
 Useful in cases where the function's definition should only be available after
the script execution reaches the function expression, such as event handlers
or closures within loops.
4/27/2024

// Function Declaration
function calculateArea(radius) {
return Math.PI * radius * radius;
}

// Function Expression
const logResult = function(result) {
console.log(`The area is: ${result}`);
};
4/27/2024

ES6 Enhancements to JavaScript


Functions
• Default Parameters: Allows functions to have default values for parameters if none are provided
during the call.

• Arrow Functions: Provides a concise syntax for writing functions and does not have its own this
context, making it ideal for scenarios where functions are used as callbacks.

• Block Scoping: Introduced let and const for declaring variables with block-level scope, reducing
issues associated with variable hoisting and global namespace pollution.
4/27/2024

ES6 Enhancements to JavaScript


Functions
// Default Parameters
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
// Arrow Functions - inline
const double = num => num * 2;

// Arrow Function
const displayWelcomeMessage = () => { console.log("Welcome to our
website!"); };

// Block Scoping
if (true) {
let blockScoped = "I'm only available here!";
const alsoBlockScoped = "Me too!";
}
4/27/2024

Syntax and Usage of Traditional


Functions
• Function Declaration: Define a function with the function keyword followed by a name,
parentheses (optionally containing parameters), and a body in curly braces.

• Function Expression: Define a function by assigning a function to a variable. Function


expressions can be named or anonymous.
4/27/2024

The arguments Object in


Traditional Functions
• Definition: An array-like object accessible within functions that contains the values of the
arguments passed to that function.

• Not an Array: Although it behaves like an array, it does not have array methods unless converted.
function concatenateStrings(string1, string2) {
return Array.prototype.join.call(arguments, ' ');
}
console.log(concatenateStrings('Hello', 'world')); // Output: "Hello world"

function concatenateStrings() {
return Array.prototype.join.call(arguments, ' ');
}
console.log(concatenateStrings('Hello', 'world', "!")); // Output: "Hello world !"
4/27/2024

Introduction to Arrow Functions


• Arrow functions provide a concise syntax for writing function expressions.

const greet = () => console.log("Hello, World!");


4/27/2024

Arrow Functions - Examples


Example 1
const addTwoNumbers = (a, b) => {
const sum = a + b; // Calculate the sum of the two arguments
return sum; // Return the result
};

// Usage example
console.log(addTwoNumbers(5, 7)); // Output: 12
Example 2
const displayWelcomeMessage = () => {
const message = "Welcome to our program!"; // Define a message
console.log(message); // Log the message to the console
};

// Usage example
displayWelcomeMessage(); // Output: Welcome to our program!
4/27/2024

Callback - Understanding
Callbacks in JavaScript
Definition:
• A callback is a function passed into another function as an argument, which is then invoked inside
the outer function to complete some kind of routine or action.
Purpose:
• To execute code after another function has finished its execution, hence the name 'callback'.
• Commonly used in asynchronous operations like API calls, event handling, or any operations
where you need to wait for an operation to complete before proceeding.
4/27/2024

Practical Callback Examples


with Arrow Functions
Example 1: Timer Callback:

setTimeout(() => {
console.log("This message is shown after 3 seconds");
}, 3000);

Example 2: Array Processing Callback:

const numbers = [1, 2, 3, 4, 5];


const doubled = numbers.map(number => number * 2);
console.log(doubled);
4/27/2024

Lexical this in Arrow Functions


• Behavior of this:
 Traditional Function: this refers to the context in which the function was called.
 Arrow Function: this is lexically bound to the context where the function is
defined, not where it is called.

function Person() {
this.age = 0;
setInterval(() => {
this.age++; // `this` properly refers to the Person object
}, 1000);
}
const p = new Person();
4/27/2024

Behavior of this in traditional


functions
const user = {
name: "John",
activities: ['work', 'play', 'eat'],
showActivities: function() {
// Using a traditional function inside forEach
this.activities.forEach(function(activity) {
console.log(`${this.name} likes to ${activity}`);
});
}
};

user.showActivities(); // Output may not be as expected


4/27/2024

Behavior of this in arrow


functions
const user = {
name: "John",
activities: ['work', 'play', 'eat'],
showActivities: function() {
// Using an arrow function inside forEach
this.activities.forEach((activity) => {
console.log(`${this.name} likes to ${activity}`);
});
}
};

user.showActivities(); // Output as expected


4/27/2024

Limitations of Arrow Functions


• Non-Suitable Scenarios:
 Object methods: May lead to incorrect this context when used inside a
method of an object.
 Constructors: Arrow functions cannot be used as constructors; they will throw
an error if used with new.
 arguments Object: Arrow functions do not have their own arguments object.
4/27/2024

Practical Use Cases for Arrow


Functions
• Ideal Use Cases:
 Short callbacks or event handlers.
 Functional programming where this needs to be bound to the context of the
execution scope.
4/27/2024

Using Arrow Functions in Event


Handlers
• Event Handler with Traditional Function:
document.getElementById('myButton').addEventListener('click', function() {
console.log(this.innerHTML);
});

• Arrow Function Event Handler:


document.getElementById('myButton').addEventListener('click', () => {
console.log(this.innerHTML);
});
4/27/2024

Enhancing Readability with Arrow


Functions in Array Methods
(traditional vs arrow fn)
• Using map
const numbers = [1, 2, 3];
const squares = numbers.map(function(number) {
return number * number;
});
const arrowSquares = numbers.map(number => number * number);

• Using filter

const oddNumbers = numbers.filter(function(number) {


return number % 2 !== 0;
});
const arrowOdds = numbers.filter(number => number % 2 !== 0);
4/27/2024

Converting Traditional
Functions to Arrow Functions
Function with Multiple Parameters:

function add(a, b) {
return a + b;
}
const arrowAdd = (a, b) => a + b;

Function Returning an Object

function getObject() {
return {value: 10};
}
const arrowObject = () => ({value: 10});
4/27/2024

Understanding Rest Parameters


in JavaScript
• Definition: Rest parameters allow a function to accept an indefinite number of arguments as an
array.

function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
4/27/2024

Comparing Rest Parameters


with the arguments Object
• Rest Parameters:
 True array: Can use array methods directly.
 Clear and predictable: Defined explicitly in the function's signature.

• arguments Object:
 Array-like: Does not have array methods unless converted.
 Less intuitive: Automatically available inside functions, but lacks clarity and
modern JavaScript features.
4/27/2024

Practical Applications of Rest


Parameters
Flexible Function Example

const concatenateWords = (...words) => words.join(' ');

console.log(concatenateWords('Hello', 'world', '!')); // "Hello world !"

Collecting Additional Arguments


function handleData(primaryData, ...otherData) {
console.log('Primary:', primaryData);
console.log('Other:', otherData);
}
handleData('Main', 'Secondary', 'Tertiary');
4/27/2024

Using Arrow Functions for Event


Handlers in React
const MyComponent = () => {
const handleClick = () => {
console.log('Button clicked!');
};

return <button onClick={handleClick}>Click Me!</button>;


}
4/27/2024

Inline Arrow Functions in Render


Methods
Conditional Rendering:

• Arrow functions used inline in JSX for conditional rendering and event handling.
const ConditionalComponent = ({ isLoggedIn }) => (
<div>
{isLoggedIn ? (
<button onClick={() => console.log('Logging out...')}>Log Out</button>
) : (
<button onClick={() => console.log('Logging in...')}>Log In</button>
)}
</div>
);
4/27/2024

Arrow Functions with Hooks in


Functional Components
Using useState and useEffect:
• Arrow functions integrate easily with Hooks, simplifying state and lifecycle management in
functional components.
const TimerComponent = () => {
const [seconds, setSeconds] = React.useState(0);

React.useEffect(() => {
const interval = setInterval(() => {
setSeconds(prevSeconds => prevSeconds + 1);
}, 1000);

return () => clearInterval(interval);


}, []);

return <div>Timer: {seconds} Seconds</div>;


};
4/27/2024

Arrow Functions in Next.js API


Routes
Simple API Handler:
• Arrow functions make defining API routes in Next.js concise and clear.

// pages/api/hello.js
export default (req, res) => {
res.status(200).json({ message: "Hello from Next.js!" });
};
4/27/2024

Questions and Feedback


• Feel free to send your queries in course group and/or at
[email protected]

You might also like