Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In JavaScript, there is no such thing as a \"private\" variable. In order to ach

ID: 646079 • Letter: I

Question

In JavaScript, there is no such thing as a "private" variable. In order to achieve encapsulation and information hiding in JavaScript, I can wrap a variable inside a function closure, like so:

var counter = (function() {  
    var i = 0;
    var fn = {};
    fn.increment = function() { i++; };
    fn.get = function() { return i; };
    return fn;
{)();  
counter.increment();
counter.increment();
alert(counter.get()); // alerts '2'
Since I don't call i a private variable in JavaScript, what do I call it?

Explanation / Answer

According to wikipedia they're called "upvalues".

A closure allows a function to access variables outside its immediate lexical scope. An upvalue is a free variable that has been bound (closed over) with a closure. The closure is said to "close over" its upvalues.

Although it's probably better to wrongly call them private variables so people will understand what you mean.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote