1

I've been fiddling with a hash counter in js, and I'm having trouble understanding why predefining the key to be null makes the accumulator work.

var totCounts = {};
Object.keys(repoCollection).forEach((x) => {
    Object.keys(repoCollection[x]).forEach((y) => {
        // If I remove this totCounts becomes a collection of Nans
        // why do I need this
        if(!totCounts[y]){
            console.log('undef');
            totCounts[y] = null;
        }
        totCounts[y] += repoCollection[x][y]
    });
});

repoCollection looks like this, in this case many times abbreviated:

{
  "HSchmale16/AccelLib": {
    "C++": 4915,
    "Arduino": 1580,
    "Makefile": 786
  },
  "HSchmale16/better-nfsn-dotfiles": {
    "Shell": 459,
    "VimL": 241
  },
  "HSchmale16/CustomComputerChair": {
    "C": 62477,
    "C++": 52760,
    "Assembly": 11862,
    "Eagle": 10410,
    "Prolog": 1297,
    "Arduino": 500,
    "Shell": 120
  },
  "HSchmale16/CalculusProject": {
    "C++": 7661,
    "TeX": 5870,
    "Makefile": 828
  },
  "HSchmale16/econsim": {},
  "HSchmale16/BoostVpthread": {
    "C++": 2527,
    "Perl": 2124,
    "Makefile": 770
  },
  "HSchmale16/ConsoleMP": {
    "C": 12525,
    "Shell": 2109,
    "C++": 1854,
    "Makefile": 1359
  },
  "HSchmale16/ElectronChargeSim": {
    "C++": 14588,
    "C": 3188,
    "Makefile": 736
  },
  "HSchmale16/GenericMakefile": {
    "Makefile": 12223,
    "C++": 164,
    "C": 147
  }
}
HSchmale
  • 1,838
  • 2
  • 21
  • 48

1 Answers1

3

Because a number plus undefined is NaN, but a number plus null is the number. JS coerces null into 0, but undefined into NaN.

See What exactly is Type Coercion in Javascript? for more information.

console.log( undefined + 1 );
console.log( null + 1 );

It'd make more sense to initialize your value to 0 instead of null, but JS treats them the same (in this scenario).

Community
  • 1
  • 1
JDB
  • 25,172
  • 5
  • 72
  • 123