JS Array is undefined

this is from one JS Ninja book (which i like very much!). However,
the array in this function is not being defined as such, and the push method is not working.

not sure what the problem is?

function makeHero(event) {
  var hero = form.name.value;
  hero.realName = form.realName.value;
  var hero.powers = [];
  console.log(hero.powers); //undefined
  for (i = 0; i < form.powers.length; i++) {
    if (form.powers[i].checked) {
      hero.powers.push(form.powers[i].value) //doesn't work
  for (i = 0; i < form.type.lenght; i++) {
    if (form.type[i].checked) {
      hero.type = form.type[i].value;
  hero.age = form.age.value;
  hero.city = form.city.value;
  hero.origin = form.origin.value;

I tried the following to try to fix but none of them worked

adding var before hero.powers = ;
hero.powers = new Array();

Your problems are being caused by var hero. In the book, hero is an object

var hero={};
This allows you to establish properties like hero.realName and hero.powers.

In your for loop
for (i = 0; i < form.powers.length; i++) {
you are trying to use form.powers, which doesn’t exist. It is the array hero.powers that should be used here.

console.log(hero.powers); //undefined
will not be undefined if you make hero an object.


+1 @AllanP

You also shouldn’t use the var keyword before hero.powers, since you’re setting a property, not declaring a new variable. Similar to hero.realName.

1 Like

Aye! thank you

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.