0

I try to understand why this works

// .......................................................

var hero = { 
  name: 'Joni', 
  type: 'blond',
  sayName: function() { 
    return this.name; 
  } 

  sayType: function() { 
    return this.type; } 
} 
document.write( hero.sayName()+ "</br>"); 
document.write( hero.sayType());

// .......................................................

but this doesn't works

// .......................................................

var hero = { 
  name: 'Joni', 
  type: 'blond',
  sayName: function() { 
    return this.name; 
  } 

  sayType: function() { 
    return this.type; 
    } 
} 
document.write( hero.sayName()+ "</br>"); 
document.write( hero.sayType());

// .......................................................

thanks

Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
joni
  • 41
  • 1

3 Answers3

1

You are missing a semi-colon at the end of the "var hero" statement. You are also missing some other commas.

var hero = { 
  name: 'Joni', 
  type: 'blond',
  sayName: function() { 
    return this.name; 
  }, // <<--- You missed the comma here

  sayType: function() { 
    return this.type; 
    } 
};  // <<--- You missed the semi colon!
document.write( hero.sayName()+ "</br>"); 
document.write( hero.sayType());

Going forward, you can completely avoid these issues by just running your code through JSLINT. Goto jslint.com, paste your code, and you'll see the answers revealed to you.//

selbie
  • 100,020
  • 15
  • 103
  • 173
  • The semi colon isn't required in this instance: http://stackoverflow.com/questions/42247/are-semicolons-needed-after-an-object-literal-assignment-in-javascript/42252#42252 – aiham Feb 22 '11 at 10:16
  • @aiham. It might not be "required", but you are relying on javascript's semi-colon insertion. Which, if you read Crawford's book, you'll learn is a bad thing and can't always be relied on. On my team, you wouldn't be allowed to check this in. – selbie Feb 22 '11 at 10:19
  • I wouldn't do it either, but it's not what was giving the error. – aiham Feb 23 '11 at 01:17
0

The difference is in the enter before the saytype function in the second block. Besides the comma i see no reason why it wouldn't work.

refro
  • 209
  • 1
  • 7
0

You are missing a comma after the sayName function. I couldn't see a difference between the two blocks of code, other than a new line character (Which doesn't make a difference). Both blocks of code were missing this comma.

var hero = { 
  name: 'Joni', 
  type: 'blond',
  sayName: function() { 
    return this.name; 
  },// <---  Missing Comma

  sayType: function() { 
    return this.type; 
    } 
} 
document.write( hero.sayName()+ "</br>"); 
document.write( hero.sayType());
aiham
  • 3,614
  • 28
  • 32