These are chat archives for codebar/tutorials

20th
Jul 2015
Carolina Sawney
@assembly21
Jul 20 2015 14:58

Hi everyone,
I'm practising Javascript with exercises from two books. They explain not to use global variables but then in the examples, they use them very often. So I'd like to rewrite this example from Javascript Head First, so that it's all done with locals. But my version is not completely right...So I'd appreciate your comments. Thanks in advance.

The code from 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<bonus){
newPoints = newPoints + skill * bonus;
i = i + 1;
}
return newPoints + userPoints;
}
userPoints = updatePoints(2,100);
avatar = getAvatar(2112);

My version with locals - but gives me undefined...

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;
}

function init(){
userPoints = updatePoints(2,100);
var avatar = getAvatar(2112);}

Denise Yu
@deniseyu
Jul 20 2015 17:28
@assembly21 could you please wrap code snippets in code tags? click the list icon at the bottom right of the textbox. it will make your code much easier to read :)
an aside, does anyone want to help QA test some new codebar app features? send me a private message
@assembly21 i think the book code is wrong. there are two conditions where level == 1. you should always use === not ==
Juyoung
@juyoungbang
Jul 20 2015 19:35
@assembly21 I am just wondering why there is the same condition as 'level == 1' twice....
Juyoung
@juyoungbang
Jul 20 2015 19:55

in the book,
there is the default value of 'avatar' so it seems to work well even though it is weird there is the same condition twice,
but in your version,
the return value of getAvatar() hasn’t the default one.
So if level is not equal to 1,2 or greater than 2, getAvatar() will return undefined…

you could code like following...
getAvatar(){
if(){..}
else if() {..}
return ‘generic’;
}

That is just my guess, so it might be wrong...