Javascript Loops help

Javascript Loops help
0

#1

Hello again! Once again I’ve got a Javascript task that I need help with if you’d be so kind! Here’s the instructions:

Make a function called onlyTruthy that takes in an object, loops through all its properties, and removes any that are falsy. Then return the object that was passed in.

and here’s my code:

var computer = {
  harddrive: null,
  graphics card: "on board",
  disk drive: undefined,
  power: "800 watts",
};

var onlyTruthy = function (obj) {
  for (var i in obj) {
if (!obj[i]) {
  delete obj[i];
}
  }
  return obj;
};

console.log(onlyTruthy));

Any suggestions? This one has been particularly difficult for me, I don’t 100% understand the concept of looping thru and removing the fasleys


#2

Couple of suggestions on your code.

  1. in your computer object you will need to put quotes around ‘graphics card’ and ‘disk drive’ since they have a space.
  2. remove the comma after ‘800 watts’ in your computer object
  3. your console.log where you call your function needs a parameter. change it to console.log(onlyTruth(computer)
  4. should work with these changes

#3

I see, i changed a couple things in the computer object and updated the console.log, here’s the updated code:

var computer = {
  hdd: null,
  gfx: "on board",
  ddr: undefined,
  power: "800 watts'
};

var onlyTruthy = function (obj) {
  for (var i in obj) {
    if (!obj[i]) {
      delete obj[i];
    }
  }
  return obj;
};

console.log(onlyTruthy));

I’m getting an Unexpected token ILLEGAL error


#4

Hi Andrew,

just a few things, your power property has needs either an opening “” or ‘’, here its "800 watts’, the quotes have to match, second you need to pass in an argument into onlyTruthy i.e console.log(onlyTruthy(computer));

Here is how the code should look:

var computer = {
  hdd: null,
  gfx: "on board",
  ddr: undefined,
  power: "800 watts"
};

var onlyTruthy = function (obj) {
  for (var i in obj) {
    if (!obj[i]) {
      delete obj[i];
    }
  }
  return obj;
};

console.log(onlyTruthy(computer));

now it should work.


#5

Ahh I see what I missed there, that was the fix =) Thank you!


#6

Here’s an improvement idea, which makes sense once you learn about immutability:

var onlyTruthy = function (obj) {
  var truthyObj = {};
  for (var i in obj) {
    if (obj[i]) {
      truthyObj[i] = obj[i];
    }
  }
  return truthyObj;
};

This way, you keep the original object untouched (i.e. you don’t “mutate” it: it is “immutable”), and you return a new object instead.

It’s thought of as advantageous to keep your data immutable where possible, which makes it easier to debug and to “reason about”, as the catch phrase goes.