UECS2094_UECS_2194_-_Topic_4_part_9
UECS2094_UECS_2194_-_Topic_4_part_9
3
~MORE DETAILED EXPL ANATIONS~
1
Functional Programming
JavaScript is a multi-paradigm language that supports functional programming, among
other paradigms.
Functional programming is a programming paradigm that emphasizes the use of functions
to create programs.
In functional programming, functions are treated as first-class citizens, which means they
can be used just like any other value, such as a number or a string.
This makes functional programming a very powerful paradigm for creating complex,
modular programs that are easy to reason about and test.
Here are some key concepts in functional programming that are applicable to JavaScript:
2
1. Functions as first-class
citizens
In JavaScript, functions are first-class citizens, which means they can be
assigned to variables,
passed as arguments to other functions, and
returned as values from functions.
This makes it easy to create reusable, modular code that can be composed
together in different ways.
3
1. Functions as first-class
citizens
// Assigning a function to a variable
const add = function(a, b) {
return a + b;
};
4
1. Functions as first-class
citizens
function multiplyByTwo(num) {
return num * 2;
}
Functions can be passed around as values, and how they can be used to create more
complex behavior by combining them in different ways.
5
2. Pure functions
In functional programming, pure functions are functions that don't have any
side effects and always return the same output for the same input.
Pure functions are easy to reason about and test, because they don't have
any hidden dependencies or state that can affect their behavior.
6
2. Pure functions
// Example of a pure function
const square = function(x) {
return x * x;
};
7
2. Pure functions
function calculateCircleArea(radius) {
return Math.PI * radius ** 2;
}
console.log(calculateCircleArea(5)); // Output:
78.53981633974483
console.log(calculateCircleArea(10)); // Output:
314.1592653589793
Because calculateCircleArea is a pure function, it will always return the same output
for the same input. This makes it easier to reason about and test our code, since we don't
have to worry about any unexpected side effects.
8
3. Immutability
In functional programming, data is typically treated as immutable, which
means that it can't be changed once it's created.
Instead, new data structures are created by applying transformations to
existing data structures.
9
3. Immutability
// Example of immutable data
const list1 = [1, 2, 3];
const list2 = list1.concat(4); // returns a new array
[1, 2, 3, 4]
10
3. Immutability
const originalArray = [1, 2, 3, 4, 5];
We use the map()method to create a new array called newArray that contains the elements of the
original array multiplied by 2.
We did not modify the original array, but rather created a new one with the updated values. This
demonstrates the concept of immutability, where we avoid changing data directly and instead create
new copies of it.
Immutability is a key principle in functional programming, as it helps prevent unexpected changes to
data and makes it easier to reason about and test our code.
11
4. Higher-order functions
Higher-order functions are functions that take other functions as
arguments or return functions as values.
Higher-order functions are a key concept in functional programming,
because they allow you to create complex behavior by composing simple
functions together.
12
4. Higher-order functions
// Example of a higher-order function
const times = function(n, operation) {
for (let i = 0; i < n; i++) {
operation(i);
}
};
times(3, function(n) {
console.log(`Hello ${n}`);
}); // logs "Hello 0", "Hello 1", "Hello 2"
13
4. Higher-order functions
function multiplyBy(factor) {
return function(number) {
return number * factor;
}
}
const double = multiplyBy(2);
const triple = multiplyBy(3);
console.log(double(5)); // Output: 10
console.log(triple(5)); // Output: 15
we have a function called multiplyBy() that returns another function. It takes a number as input and returns
the result of multiplying that number by the factor passed into multiplyBy().We then use multiplyBy() to
create two new functions, double and triple, which multiply their input by 2 and 3, respectively.
Notice how multiplyBy() is a higher-order function because it returns another function. This allows us to create new
functions with different factors without duplicating the code for the multiplication operation.
14
Functional Programming
In summary, functional programming in JavaScript is about treating
functions as
first-class citizens,
creating pure functions that don't have side effects,
using immutable data structures, and
creating complex behavior by composing simple functions together.
These concepts can help you create more modular, testable, and
maintainable code in JavaScript.
15
JavaScript and ES6
ES6 stands for ECMAScript 6, which is the sixth version of the ECMAScript standard.
ECMAScript is the official name for the language that JavaScript is based on.
16
ES6: arrow function
A shorter syntax for writing functions
// Traditional JavaScript syntax In this example, the greet function uses traditional
function greet(name) { JavaScript syntax to concatenate a greeting string with
return "Hello, " + name + "!"; the name parameter using the + operator.
}
The greetArrow function uses ES6 arrow function
// ES6 arrow function syntax
const greetArrow = (name) => { syntax to achieve the same thing, but with a shorter
return `Hello, ${name}!`; and more concise syntax using template literals instead
} of string concatenation.
17
ES6: Template literals
A new way to create strings that allows for easier variable interpolation and multiline strings
// ES6 // ES6
const name = "John"; const value = 10;
const message = `Hello, ${name}!`; const message = `The value is ${value * 2}`;
we can see that template literals provide a cleaner and more concise way of creating strings with variables
and expressions.
18
ES6: Destructuring
A new syntax for extracting values from objects and arrays
19
ES6: Destructuring
// Destructuring parameters
// JavaScript
function greet(person) {
var name = person.name;
var age = person.age;
console.log(`Hello, ${name}. You are ${age} years old.`);
}
greet({ name: "John", age: 30 });
// ES6
function greet({ name, age }) {
console.log(`Hello, ${name}. You are ${age} years old.`);
}
greet({ name: "John", age: 30 });
We can see that destructuring provides a cleaner and more concise way of extracting values from arrays and
objects. It can also make function parameters more readable and easier to work with.
20
ES6: Spread and rest operators
New syntax for working with arrays and objects
21
ES6: Spread and rest operators
// Rest parameters
// JavaScript
function sum() {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function (a, b) {
return a + b;
});
}
var result = sum(1, 2, 3, 4);
// ES6
function sum(...args) {
return args.reduce((a, b) => a + b);
}
const result = sum(1, 2, 3, 4);
We can see that the spread operator provides a more concise way of combining or copying arrays, while the
rest operator allows for more flexible and readable function parameters. Overall, these operators can
simplify and improve the readability of code.
22
Good practices in writing
JavaScript
1. Use meaningful variable and function names: Choose names that accurately reflect the
purpose of the variable or function. Avoid using single-letter variable names or generic
names like temp or data.
// Bad:
let x = 10;
function a() {}
// Good:
let age = 10;
function calculateTotal() {}
23
Good practices in writing
JavaScript
2. Use const and let instead of var: Use const when you don't plan on reassigning the
variable, and use let when you do plan on reassigning it. Avoid using var as it can have
unexpected behavior with scoping and hoisting.
// Bad:
var x = 10;
// Good:
const age = 10;
let name = "John";
24
Good practices in writing
JavaScript
3. Use strict equality (===) instead of loose equality (==): The strict equality operator (===)
compares both value and type, while the loose equality operator (==) performs type
coercion before comparing. Using strict equality can help prevent bugs caused by
unexpected type coercion.
// Bad:
if (x == 5) {}
// Good:
if (x === 5) {}
25
Good practices in writing
JavaScript
4. Use array and object destructuring: Destructuring allows you to extract values from arrays
and objects and assign them to variables in a concise way. This can help make your code
more readable and maintainable.
// Bad:
const myArray = [1, 2, 3];
const x = myArray[0];
const y = myArray[1];
// Good:
const [x, y, z] = [1, 2, 3];
// Bad:
const myObj = { name: "John", age: 30 };
const name = myObj.name;
const age = myObj.age;
// Good:
const { name, age } = { name: "John", age: 30 };
26
Good practices in writing
JavaScript
5. Avoid global variables: Global variables can make your code difficult to reason about and can
lead to unexpected behavior. Instead, use local variables and pass data between functions
explicitly.
// Bad:
let x = 10;
function addNumbers(y) {
return x + y;
}
// Good:
function addNumbers(x, y) {
return x + y;
}
27
Good practices in writing
JavaScript
6. Use arrow functions for short, anonymous functions: Arrow functions provide a more
concise syntax for writing functions and can make your code more readable. However, avoid
using them for longer, more complex functions that require multiple lines of code.
// Bad:
const sum = function(x, y) {
return x + y;
}
// Good:
const sum = (x, y) => x + y;
28
Good practices in writing
JavaScript
7. Use template literals instead of string concatenation: Template literals provide a more
concise and readable way to interpolate variables into strings. They also allow for multi-line
strings.
// Bad:
const message = "Hello, " + name + "!";
// Good:
const message = `Hello, ${name}!`;
29