var _tmp = 0;
for (var i = 0; sys.cores()[i]["sn"] != null; i++) { _tmp++; alert(_tmp); }
alert ("Pretty sure, you have " + _tmp + " virtual cores.");

This is the code that I'm working on. The loop itself is very simple. The output is: 1, 2, 3, 4. Just like expected, 4 virtual cores. But the alert() after it, is not executed. Reason behind it is that:

os.cpus()[0]["model"] // TRUE, _tmp = 1;
os.cpus()[1]["model"] // TRUE, _tmp = 2;
os.cpus()[2]["model"] // TRUE, _tmp = 3;
os.cpus()[3]["model"] // TRUE, _tmp = 4;
os.cpus()[4]["model"] // FALSE/NULL -> ERROR -> HALT!

So interpreter skips further code execution. I'd still like to know ways to solve that kind of issue.

The error:

Uncaught TypeError: Cannot read property 'model' of undefined.

Dani AI

Generated

The error is not a mysterious VM bug but unsafe property access: in an expression like sys.cores()[i]['sn'] != null the engine first evaluates sys.cores(), then the [i] lookup, then ['sn']. When i reaches past the last element, sys.cores()[i] is undefined, so attempting to read ['sn'] throws a TypeError before the != null comparison can run.

's fix (reading .length once and using it) is the simplest robust approach because it prevents out‑of‑range indexing. Here are two safe patterns that avoid the exception — one modern and concise, one explicit and backwards compatible:

const cores = sys.cores();
let count = 0;
for (const c of cores) {
  if (c?.sn != null) count++;
}
console.log('Pretty sure, you have ' + count + ' virtual cores.');
const cores = sys.cores();
let i = 0, count = 0;
while (cores[i] && cores[i].sn != null) {
  count++;
  i++;
}
console.log('Pretty sure, you have ' + count + ' virtual cores.');

Notes and cautions:

  • Optional chaining (?.) requires ES2020+ runtimes; use the explicit guard form for older environments.
  • != null intentionally checks both null and undefined; use !== or typeof checks if strictness is required.
  • Avoid calling sys.cores() inside the loop condition repeatedly — cache the result to prevent extra work or inconsistent results.

In short: the symptom is an out‑of‑bounds access. Bounds or guard checks (or optional chaining) are the proper fix.

I have solution on my personal problem.

var i = 0;
var _tmp;
var cpuCores;

_tmp = sys.cores().length;
cpuCores = _tmp;

alert ("Pretty sure, you have " + cpuCores + " virtual cores.");

But I can't escape forever. The request on answer on how to perform this with for() or while() still remains.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.