0% found this document useful (0 votes)
7 views

JS Functions 2

The document discusses different types of functions in JavaScript including function declarations, function expressions, arrow functions, and constructor functions. It also covers functional programming concepts like pure functions and function composition.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

JS Functions 2

The document discusses different types of functions in JavaScript including function declarations, function expressions, arrow functions, and constructor functions. It also covers functional programming concepts like pure functions and function composition.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Welcome

to JSConf!

Fantastic functions &


where to find them
Part 2

The crimes of JavaScript

CONFIDENTIAL | © 2022 EPAM Systems, Inc.


AGENDA

1 WHAT WE’VE LEARNED SO FAR

2 TYPES OF FUNCTIONS

3 FUNCTIONAL PROGRAMMING

4 PURE FUNCTIONS

5 FUNCTION COMPOSITION

6 RECURSION

7 MEMOIZATION

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 2


W H AT W E ’ V E L E A R N E D S O FA R

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 3


IN JAVASCRIPT, FUNCTIONS ARE ACTUALLY FUNCTION OBJECTS

• In JavaScript, functions are called Function Objects because they are objects:

• Just like objects, functions have properties and methods

• Functions can be stored in a variable or an array

• Functions can be passed as arguments to other functions

• Functions can be returned from functions

This concept is called ‘functions as first-class citizens`

first-class citizenship simply means “being able to do what everyone else can do”

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 4


CALLBACK FUNCTIONS

• As we’ve just learned, in JS we can pass functions as


arguments to other functions

• Functions that do this are called higher-order


functions

• Any function that is passed as an argument is called


a callback function

• A callback is a function that is to be


executed after another function has finished
executing

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 5


HOISTING IN JS

• These 2 phases of the Execution Context allow for a phenomena of hoisting

• Hoisting (or, in other, words, raising up) means that function declarations &
variable declarations can be used in the code before the parser reaches the
line where they are actually written:
BOTH CAN
WORK!

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 6


VARIABLE HOISTING IN JS

• Variable hoisting can happen only if you’re using the key word ‘var’

• Hoisting can happen only to variable declaration, NOT initialization

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 7


SCOPE IN JAVASCRIPT

• Scope is a region of the program


where a variable can be accessed

• In other words, scope is where a


variable can be ‘seen’ by JS interpreter
when parser when running the
programme in execution phase

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 8


FUNCTION DECLARATION VS FUNCTION EXPRESSION

Function Declaration (FD) Function Expression (FE)

• FD declares a function and is subject to


hoisting

• FE stores a function as a variable’s value,


but only variable declaration is subject to
hoisting, NOT initialling with a value

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 9


CLOSURE

Closure means an inner function has access to variables in its surrounding block of code (it’s
reference to an outer lexical environment) even after the surroundings are gone.

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 10


TYPES OF FUNCTIONS

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 11


THERE’RE SEVERAL WAYS TO DECLARE A FUNCTION IN JAVASCRIPT

• Function Declaration (+ anonymous function)

• Function Expression (+ named function expression)

• IIFE – Immediately Invoked Function Expression

• Arrow Function

• Constructor Function

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 12


FUNCTION DECLARATION

NAMED ANONYMOUS

• We can use anonymous functions only:


• In callbacks
• When assigned to a variable
• In IIFE

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 13


FUNCTION EXPRESSION

NAMED ANONYMOUS

• In FE, function name can only be • We’re using an anonymous function


referenced inside the function! declaration & assigning it to a variable!

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 14


IIFE (IMMEDIATELY INVOKED FUNCTION EXPRESSION)

IIFE SYNTAX:

• As the name implies, we’re declaring AND immediately calling(invoking) the function

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 15


ARROW FUNCTION

• Arrow functions support a shortened syntax:

• We can drop the () if there is only 1 argument

• We can drop the { return…} if the function only returns a statement

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 16


ARROW FUNCTION & THIS

• Arrow functions do NOT have:

• Their own ‘this’


• Access to ‘arguments’
• Compatibility with `bind`, `call`, `apply`

For more details, you can read this article:
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Functions/A
rrow_functions

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 17


CONSTRUCTOR FUNCTION

name arguments body

• Function constructor creates functions which execute in the global scope only
• Functions created this way suffer from security and performance issues
• 99,99% of the time we do not use this method of function creation
• https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 18


FUNCTIONAL PROGRAMMING

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 19


WHAT IS FUNCTIONAL PROGRAMMING (FP)

• FP is a programming paradigm where programs are


constructed by applying and composing functions

• FP is juxtaposed to OOP (Object Oriented Progamming),


where programs are constructed by creating & inheriting
objects

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 20


CORE FUNCTIONAL PROGRAMMING CONCEPTS

• Pure functions • Avoid shared state

• Higher-order functions • Avoid mutating state

• Function composition • Avoid side effects

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 21


FUNCTIONAL PROGRAMMING IS DECLARATIVE

IMPERATIVE DECLARATIVE

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 22


Imperative =
HOW to achieve the result

Declarative =
WHAT do I want to achieve
CONFIDENTIAL | © 2022 EPAM Systems, Inc. 23
PURE FUNCTIONS

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 24


SIDE EFFECTS

A side effect is any application state change that is observable outside the
called function other than its return value

Side effects include:


• Modifying any external variable or object property (e.g., a global variable,
or a variable in the parent function scope chain)
• Logging to the console
• Writing to the DOM
• Writing to a file
• Writing to the network
• Triggering any external process
• Calling any other functions with side-effects
CONFIDENTIAL | © 2022 EPAM Systems, Inc. 25
PURE FUNCTIONS

Given the same input, pure function will always return the same output.
Pure function produces no side effects.

Pure functions are all about mapping. Functions map input arguments to
return values, meaning that for each set of inputs, there exists an output. A
function will take the inputs and return the corresponding output.

const double = x =>x * 2;

Referential transparency: double(5) 10

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 26


BENEFITS OF USING PURE FUNCTIONS

✓ read
✓ compose
✓ reuse
✓ test
EASIER TO: ✓ move
✓ extract
✓ refactor
✓ reorganize
CONFIDENTIAL | © 2022 EPAM Systems, Inc. 27
FUNCTION COMPOSITION

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 28


FUNCTION COMPOSITION

Function composition is the process of combining two or more functions to


produce a new function. Composing functions together is like snapping
together a series of pipes for our data to flow through.

Put simply, a composition of functions `f` and `g` can be defined


as `f(g(x))`, which evaluates from the inside out — right to left. In other words,
the evaluation order is:

`x`
`g`
`f`

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 29


INHERITANCE IN OOP

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 30


COMPOSITION IN FP

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 31


COMPOSITION EXAMPLE

• We can easily achieve


`single responsibility` by
composing functions

• Composing improves
reusability – we can
create small, reusable
functions and chain
them together to
achieve a more complex
logic

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 32


HIGHER ORDER FUNCTIONS

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 33


IN JAVASCRIPT, FUNCTIONS ARE ACTUALLY FUNCTION OBJECTS

• In JavaScript, functions are called Function Objects because they are objects:

• Just like objects, functions have properties and methods

• Functions can be stored in a variable or an array

• Functions can be passed as arguments to other functions

• Functions can be returned from functions

This concept is called ‘functions as first-class citizens`

first-class citizenship simply means “being able to do what everyone else can do”

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 34


HIGHER ORDER FUNCTIONS

A higher order function is any function which takes a function as


an argument, returns a function, or both. Higher order functions
are often used to:

• Abstract or isolate actions, effects, or async flow control using callback


functions, promises, monads, etc…
• Create utilities which can act on a wide variety of data types
• Partially apply a function to its arguments or create a curried function for the
purpose of reuse or function composition
• Take a list of functions and return some composition of those input functions

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 35


RECURSION

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 36


RECURSIVE FUNCTIONS

• A recursive function
is a function which
calls itself

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 37


HIGHER ORDER FUNCTION EXAMPLE

• In mathematics, factorial is the product of a positive integer with all of the whole
numbers lower than it

• For example, 4! = 4x3x2x1 = 24

• Therefore, to implement such logic (multiplying repeatedly), we can use recursion so


that the multiplier function calls itself

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 38


HIGHER ORDER FUNCTION EXAMPLE

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 39


MAXIMUM CALL STACK EXCEEDED ERROR

• If we call a function way too many times, the call stack will grow until it hits a limit:
the browser hardcoded stack size or memory exhaustion

• At this point, the code execution will stop & we’ll receive an error like above

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 40


CALL STACK

• JS in single-threaded

• Our code is run line-by-line

• Each time parser


encounters a function, it is
put on a call stack

• Recursion can easily


overflow the callstack
unless we take precautions

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 41


RECURSION RULES

• In order to avoiding an infinite loop overflowing the call stack, we


need to have an ‘escape condition’ for our recursion

• specifying when we get out of the loop, telling the function to


stop calling itself

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 42


HIGHER ORDER FUNCTION EXAMPLE

• In our factorial example, `escape


condition` will be the factorial
argument reaching 0, at which point
we just return 1 and return the result,
thus ending the recursion loop

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 43


M E M O I Z AT I O N

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 44


WHAT IS MEMOIZATION?

• In programming, memoization is an optimization technique that


makes applications more efficient and hence faster

• It does this by storing computation results in cache, and


retrieving that same information from the cache the next time
it's needed instead of computing it again

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 45


HOW DOES MEMOIZATION WORK?

• The concept of memoization in JavaScript relies on two concepts:

• Closures: The combination of a function and the lexical


environment within which that function was declared. You can
read more about them here and here.
• Higher Order Functions: Functions that operate on other functions,
either by taking them as arguments or by returning them. You can
read more about them here.

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 46


MEMOIZATION USAGE EXAMPLE

• The Fibonacci sequence is a set of numbers that starts with a one


or a zero, followed by a one, and proceeds based on the rule that
each number (called a Fibonacci number) is equal to the sum of
the preceding two numbers.

• It looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 47


FIBONNACCI SEQUENCE CALCULATION

• We can use recursion to easily achieve the result:

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 48


FIBONNACCI SEQUENCE CALCULATION

• We can use recursion to easily achieve the result:

• But what will happen if we decide to calculate fib(150)?

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 49


FIBONNACCI SEQUENCE CALCULATION EXCEEDING CALLSTACK

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 50


HOW RECURSIVE FIBONACCI CALCULATION ACTUALLY WORKS

• We are doing the same calculations


multiple times!

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 51


MEMOIZATION TO THE RESCUE

• Now we are storing the


calculations’ results in the `memo`
object!

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 52


WHAT IS STORED IN THE MEMO OBJECT?

• We have
stored results
of every
calculation
we’ve done!

CONFIDENTIAL | © 2022 EPAM Systems, Inc. 53


T H A N K YO U !

D O YO U H AV E A N Y Q U E S T I O N S ?

CONFIDENTIAL | © 2022 EPAM Systems, Inc.

You might also like