Joe Moore
Joe Moore

Reputation: 2023

How do I detect undefined variables within an array?

I am currently working on a project where some records for wpm are displayed. It currently works so that if any elements in the array are undefined it sets them to "" so that on output they are not displayed. My version is clunky and too big, and I was wondering how I would make it smaller with a function.

Code:

var fifteenSecond = `Your 15s highscore: ${maxesTime[15]}wpm`
var thirtySecond = `Your 30s highscore: ${maxesTime[30]}wpm`
var sixtySecond = `Your 60s highscore: ${maxesTime[60]}wpm`

  if (maxesTime[15] === undefined) {
    fifteenSecond = ""
  } else if (maxesTime[30] === undefined) {
    thirtySecond = ""
  } else if (maxesTime[60] === undefined) {
    sixtySecond = ""
  }

console.log(`${sixtySecond}}\n${thirtySecond}\n${fifteenSecond}`);

Thanks in advance,

Any and every answer is greatly appreciated

Upvotes: 1

Views: 42

Answers (2)

tdphut
tdphut

Reputation: 94

Here is my aproach:

function getRecord(seconds, maxesTime) {
  return maxesTime[seconds] ? 
    `Your ${seconds}s highscore: ${maxesTime[seconds]}wpm`
    : '';
}

Upvotes: 2

Alessio Cantarella
Alessio Cantarella

Reputation: 5201

You could simply use a for to check every property i in maxesTime. In this way if you add a new "max time" (e.g. "45"), you don't have to change your code.

let maxesTime = {
  '15': 100,
  '30': null,
  '45': undefined,
  '60': 400
};
for (let i in maxesTime) {
  if (maxesTime[i]) {
    console.log(`Your ${i}s highscore: ${maxesTime[i]}wpm`);
  }
}

Upvotes: 2

Related Questions