Structured Programming - Lecture 5
Structured Programming - Lecture 5
PROGRAMMING
A. A. Datti
COURSE OUTLINE
1. Introduction to Structured Programming
2. What is functional programming?
3. Functional vs. Object-oriented programming
4. Functions
5. Closures, Currying and Partial Application
6. Understanding your application’s control flow
7. Method chaining and Function chaining
8. Reasoning about your code
9. Learning to think recursively
SWE4205 - STRUCTURED PROGRAMMING 2
CLOSURES
SCOPE
When you define a variable, you want it to exist within some boundaries.
The accessibility of variables is managed by scope. You are free to access the
variable defined within its scope. But outside of that scope, the variable is
inaccessible.
In JavaScript, a scope is created by a function or a code block.
SCOPE
count is freely accessed within the scope of foo().
However, outside of the foo() scope, count is inaccessible. If you try to access count
from outside anyways, JavaScript throws ReferenceError: count is not defined.
SCOPES NESTING
Let's play a bit more with scopes, and nest one scope into another. For example, the
function innerFunc() is nested inside an outer function outerFunc()
How would the 2 function scopes interact with each other? Can I access the variable
outerVar of outerFunc() from within innerFunc() scope?
SCOPES NESTING
Indeed, outerVar variable is
accessible inside innerFunc() scope.
The variables of the outer scope are
accessible inside the inner scope.
THE LEXICAL SCOPE
How does JavaScript understand that outerVar inside innerFunc()
corresponds to the variable outerVar of outerFunc()?
JavaScript implements a scoping mechanism named lexical scoping (or static
scoping). Lexical scoping means that the accessibility of variables is
determined by the position of the variables inside the nested scopes.
Simpler, the lexical scoping means that inside the inner scope you can access
variables of outer scopes.
It's called lexical (or static) because the engine determines (at lexing time)
the nesting of scopes just by looking at the JavaScript source code, without
executing it
THE CLOSURE
Let's make a change: innerFunc() to be invoked outside of its lexical scope: in a
function exec(). Would innerFunc() still be able to access outerVar?
THE CLOSURE
Now innerFunc() is executed outside of its lexical scope, but
exactly in the scope of exec() function. And what's important:
Even after newCounter() exits, the inner function still has access to count, but that
variable is not accessible to any other parts of your code.
This isn't a very good example of FP— a function (nc(), in this case) isn’t expected
to return different results when called with the same parameters
FUNCTION
FACTORIES
sayHi(), sayHello(), add5() and
add10() are all Closures.
Now logNow is log with fixed first argument, in other words “partially applied
function” or “partial” for short.