1
var jFunc = function() {

    var q;
    var p = 0;

    q = (typeof(q) === "undefined") ? 0 : q;

    p += 1;
    q += p; 

    console.log(q);

};

In the console of chrome developer tools, the output of console.log(q) is q + 1 (1, 2, 3, 4, and so on..) every subsequent iteration of running the entire block of code within jFunc independently of invoking jFunc. However, when invoking jFunc (so as to conveniently avoid copying and pasting the code block within the console), the output is always 1 everytime. Why is this the case?

The goal is to essentially save a numeric value to a variable, add 1 to it, and return it without the use of global variables.

2 Answers 2

2

What you need is a function with its own persistent scope to keep track of the counter. You can use an IIFE while defining jFunc:

const jFunc = (() => {
  let p = 0;
  return () => {
    p++;
    return p;
  }
})();
console.log(jFunc());
console.log(jFunc());
console.log(jFunc());

This can be simplified a bit by just returning the ++, but it's a bit more confusing if you're not familiar with it:

const jFunc = (() => {
  let p = 0;
  return () => ++p;
})();
console.log(jFunc());
console.log(jFunc());
console.log(jFunc());

Or, if you need to create multiple counter functions, instead define a higher-order function that can create a counting function when called:

const makeJFunc = () => {
  let p = 0;
  return () => {
    p++;
    return p;
  }
};
const jFunc1 = makeJFunc();
const jFunc2 = makeJFunc();
console.log(jFunc1());
console.log(jFunc1());
console.log(jFunc2());
console.log(jFunc1());

Sign up to request clarification or add additional context in comments.

Comments

0

Probably you are looking for Closures

You have to return your repeating functionality as a function so that only that part can be invoked. Rest will be declared only once and will be local to that function scope.

    var jFunc = (function() {
        var q;
        var p = 0;
        return function(){
        q = (typeof(q) === "undefined") ? 0 : q;
        p += 1;
        q += p; 
        console.log('q',q);
        return q;
        }
    })();
    
    jFunc();
    jFunc();
    jFunc();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.