DEV Community

Discussion on: 2 Examples To Help You Understand JS Closures Once And For All 🙃

Collapse
 
harrison_codes profile image
Harrison Reid

Hey hey, thanks for reading 🍻

createElection() does indeed return an object. Which is why this line works to destructure the object into const values:

const {
  voteForCandidateOne, 
  voteForCandidateTwo, 
  getResults 
} = createElection("password123")

What's important here is that the returned object doesn't expose the vars candidateOneVoteCount & candidateTwoVoteCount directly - these are only accessible via the returned functions in that object. For example:

const election = createElection("password")

console.log(election.candidateOneVoteCount)
// => undefined

console.log(election.candidateTwoVoteCount)
// undefined

Similarly, you're not able to overwrite those variables by setting properties on the returned object:

const election = createElection("password")

console.log(election.getResults("password")
//  { candidateOne: 0, candidateTwo: 0 }

election.candidateOneVoteCount = 1000000
election.candidateTwoVoteCount = 2000000

// Still no votes for either candidate...
console.log(election.getResults("password")
//  { candidateOne: 0, candidateTwo: 0 }
Collapse
 
aminmansuri profile image
hidden_dude

Its an example of functional programming being able to represent OO programing (as in the SICP text book). Even if Javascript didn't support objects, using closures and currying can give you "objects" with pure functional constructs.