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
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));
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.