Jump to content


assembly21

Member Since 17 Jul 2015
Offline Last Active Jul 20 2015 01:30 PM
-----

Topics I've Started

Local Variables

20 July 2015 - 06:48 AM

The book insists on local variables, however they use plenty of global ones. 

I'd like to have seen for example this piece of code written without global variables at all. 
 

var avatar = "generic";
var skill = 1.0;
var pointsPerLevel = 1000;
var userPoints = 2008;

function getAvatar(points){
   var level = points / pointsPerLevel;
   if (level == 1) {
      return "Teddy bear";
} else if (level == 1) {
  return "Cat";
} else if (level >= 2) {
   return "Gorilla";
}
};
function updatePoints(bonus, newPoints) {
   var i = 0;
   while(i<bonus){
    newPoints = newPoints + skill * bonus;
   i = i + 1;
}
return newPoints + userPoints;
}
userPoints = updatePoints(2,100);
avatar = getAvatar(2112);

I try this, but it's not finished...

 

function getAvatar(points){
   var pointsPerLevel = 1000;
   var level = points / pointsPerLevel;
   if (level == 1) {
      return "Teddy bear";
} else if (level == 1) {
  return "Cat";
} else if (level >= 2) {
   return "Gorilla";
}
};
function updatePoints(bonus, newPoints) {
   var i = 0;
   var skill = 1.0;
   var userPoints = 2008;
   while(i<bonus){
    newPoints = newPoints + skill * bonus;
   i = i + 1;
}
return newPoints + userPoints;
}
userPoints = updatePoints(2,100);
var avatar = getAvatar(2112);

Would love to see this version finished. Thanks in advance. 


Functions Page 101

17 July 2015 - 02:51 AM

When I write the code in the book in the console, it gives me an error: points is not defined. 
 

Here's the code as it is on the book: 


var avatar = "generic";
var skill = 1.0;
var pointsPerLevel = 1000;
var userPoints = 2008;

function getAvatar(points){
   var level = points / pointsPerLevel;
   if (level == 1) {
      return "Teddy bear";
} else if (level == 1) {
  return "Cat";
} else if (level >= 2) {
   return "Gorilla";
}
};
function updatePoints(bonus, newPoints) {
   var i = 0;
   while(i<points){
    newPoints = newPoints + skill * bonus;
   i = i + 1;
}
return newPoints + userPoints;
}
userPoints = updatePoints(2,100);
avatar = getAvatar(2112);

 

It's not necessary to define a variable called points to then use it as a parameter to make it work, right? 

Thanks.