JS Functions 2
JS Functions 2
to JSConf!
2 TYPES OF FUNCTIONS
3 FUNCTIONAL PROGRAMMING
4 PURE FUNCTIONS
5 FUNCTION COMPOSITION
6 RECURSION
7 MEMOIZATION
• In JavaScript, functions are called Function Objects because they are objects:
first-class citizenship simply means “being able to do what everyone else can do”
• 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!
• Variable hoisting can happen only if you’re using the key word ‘var’
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.
• Arrow Function
• Constructor Function
NAMED ANONYMOUS
NAMED ANONYMOUS
IIFE SYNTAX:
• As the name implies, we’re declaring AND immediately calling(invoking) the function
• 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
IMPERATIVE DECLARATIVE
Declarative =
WHAT do I want to achieve
CONFIDENTIAL | © 2022 EPAM Systems, Inc. 23
PURE FUNCTIONS
A side effect is any application state change that is observable outside the
called function other than its return value
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.
✓ read
✓ compose
✓ reuse
✓ test
EASIER TO: ✓ move
✓ extract
✓ refactor
✓ reorganize
CONFIDENTIAL | © 2022 EPAM Systems, Inc. 27
FUNCTION COMPOSITION
`x`
`g`
`f`
• Composing improves
reusability – we can
create small, reusable
functions and chain
them together to
achieve a more complex
logic
• In JavaScript, functions are called Function Objects because they are objects:
first-class citizenship simply means “being able to do what everyone else can do”
• A recursive function
is a function which
calls itself
• In mathematics, factorial is the product of a positive integer with all of the whole
numbers lower than it
• 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
• JS in single-threaded
• We have
stored results
of every
calculation
we’ve done!
D O YO U H AV E A N Y Q U E S T I O N S ?