0

I'm new to JavaScript and since I'm trying to learn thru some exercises I'm having some problem understanding how to make this simple thing to work:

var person = {
  name: 'John Potato',
  age: 31,
  weight: '145kg',
  birthday: 'Some day mid July'
}

Then, after studying some things about Loops..

let counter = 0;

while(counter.length < person){
  counter++;
}
console.log('The person has ' + counter + ' properties')

do{
  console.log(counter++)
} while(counter.length < person[prop]);
console.log('The person has ' + counter + ' properties')

Thing is, neither of them work the way I'm expecting. All I want to do is to make it count the amount of properties there are inside the object 'person'

  • `counter` is a number. A number has no `length` property. `person` is an object. How do you think `while(counter.length < person)` would work (when `counter.length` would exist)? – Andreas Mar 27 '21 at 12:48
  • [Working with objects - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) – Andreas Mar 27 '21 at 12:50

1 Answers1

1

counter.length is undefined.

You can use Object.keys() to get all the keys and get the length property form that:

var person = {
  name: 'John Potato',
  age: 31,
  weight: '145kg',
  birthday: 'Some day mid July'
}
let counter = Object.keys(person).length;
console.log('The person has ' + counter + ' properties');

You can also use for...in like the following way:

var person = {
  name: 'John Potato',
  age: 31,
  weight: '145kg',
  birthday: 'Some day mid July'
}

let counter = 0;
for(var i in person){
  counter++;
}
console.log('The person has ' + counter + ' properties');
Mamun
  • 58,653
  • 9
  • 33
  • 46
  • 1
    _"Why don't use..."_ - Why don't you spent the time searching for a duplicate to a really easy problem which will definitely already have an answer, instead of adding yet another answer... – Andreas Mar 27 '21 at 12:50