2

A basic function:

function myStuff(a,b,c){
    var _c = _c || c || {};
    console.log(_c);
}

The idea is to use a cached value if used before, or a new value if new/different.

The question is: if the function invoke does not include the third property why the console.log(_c) shows undefined or how can I write this line var _c = _c || c || {}; better?

Thanks

thednp
  • 4,401
  • 4
  • 33
  • 45

4 Answers4

2

the scope of the variable you defined is the function itself, therefore, it is redefined every time you call the function.

the correct way to cache a variable, is to define it in the parent scope of the function:

var _c;
function myStuff(a,b,c){
    _c = c || _c || {};
    console.log(_c);
}

read more about js scopes here: What is the scope of variables in JavaScript?

Community
  • 1
  • 1
MoLow
  • 3,056
  • 2
  • 21
  • 41
1

You can store the cache inside the function itself

function myStuff(a,b,c){
    if (!myStuff.cache) {
        myStuff.cache = {};
    }

    var cache = myStuff.cache;
    c = cache.c = cache.c || c || {};

    console.log(c);
}
axelduch
  • 10,769
  • 2
  • 31
  • 50
1

If yout want to access _c external value you have to use the function like this:

function myStuff(a,b,c){
    var _c = window._c || c || {};
    console.log(_c);
}
deFreitas
  • 4,196
  • 2
  • 33
  • 43
1

I figured. Having this code if ( c === undefined ) { c = {}; } solves the issue with undefined c:

function myStuff(a,b,c){
  if ( c === undefined ) { c = {}; }
  var _c = _c || c || {};
  console.log(_c);
}

because

_c = c || _c || {};

does not count the last case for {}.

thednp
  • 4,401
  • 4
  • 33
  • 45