Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

jonpeter

macrumors member
Original poster
Sep 19, 2013
42
0
MI
So I'm trying to get through this "javascript for absolute beginners book."

One of the first programs is to determine if a ice cream is in a top 10 list... An array.

So the code is
Code:
Var rankflavor=function(flavor) {
For var i= rankflavor.len; i--;)  {
If (rankflavor[i]===flavor)  {
Return flavor + "is number " + (I +1) + ".";
}
}
Return flavor + "is not among my top 10."}

A few questions.
Can a variable have a value and a function or it it merely a function?

In the for loop, why does it end with "I--" instead of I++?

And finally, during the if loop, does the rankflavor equate to a number or a text based comparison. I'm confused as to how rankflavor compares to flavor.

Any help would be greatly appreciated.
 
Last edited by a moderator:

GimmeSlack12

macrumors 603
Apr 29, 2005
5,403
12
San Francisco
I myself am learning JavaScript too but I have some basics down. Hopefully I can help you out. If anyone wants to correct me I'm all about it :)

One of the first programs is to determine if a ice cream is in a top 10 list... An array.

Code:
Var rankflavor=function(flavor) {
For var i= rankflavor.len; i--;)  {
If (rankflavor[i]===flavor)  {
Return flavor + "is number " + (I +1) + ".";
}
}
Return flavor + "is not among my top 10."}

Can a variable have a value and a function or it it merely a function?
A variable can be anything. The thing about JS is that everything is an object. This means you can define a variable for anything whether it's a function, a string, an integer, a hash/dictionary, etc. So when you do "var value" you can put anything you want after it. This is a big advantage for JS in the sense that you don't have to bother with what type of variable you're defining.

In the for loop, why does it end with "I--" instead of I++?
Using "i--" is an increment down in the same sense that "i++" is increment up. Your iterating from the last array index ("rankflavor.len") to the first, hence the "i--".

And finally, during the if loop, does the rankflavor equate to a number or a text based comparison. I'm confused as to how rankflavor compares to flavor.

You are iterating through an array of flavors, for example the array "rankflavor" probably looks something like this:
Code:
rankflavor = ['chocolate chip', 'raspberry', 'strawberry', etc. ]

The location of each flavor in the array can be called by their index starting from 0. Therefore from my example above, rankflavor[0] == 'chocolate chip'.

What this means is the value "i" in your loop represents the index values of the array. When you loop through each index value you are then comparing a rankflavor (which is a string) to the string "flavor". So you are comparing a string to a string.

Let's use these variables for example and run through your loop once.

Code:
i = 4
flavor = "strawberry" (just imagine this is the value)
rankflavor = ['chocolate chip', 'raspberry', 'strawberry', 'mint', 'orange']
An example flow of your loop does this:
i = 4
rankflavor[4] does not equal 'flavor'

i = 3
rankflavor[3] does not equal 'flavor'

i = 2
rankflavor[2] does equals 'flavor' EXIT LOOP

You don't do the last two iterations of "i" because you found your value, it is returned, and you're done.
 

jonpeter

macrumors member
Original poster
Sep 19, 2013
42
0
MI
Oh shoot. Maybe I was mis-understanding.

During the for loop. Does the ice cream.length stand for the number of characters in the element or the number representing the element in the array?

Either way, thank you!

----------

'm quoting you so you see the notification haha. Hopefully.
I'm attempting to understand the context of ice cream.length.

. . .




I myself am learning JavaScript too but I have some basics down. Hopefully I can help you out. If anyone wants to correct me I'm all about it :)

I'm quoting you so you see the notification haha. Hopefully.
I'm attempting to understand the context of ice cream.length.

. . .


A variable can be anything. The thing about JS is that everything is an object. This means you can define a variable for anything whether it's a function, a string, an integer, a hash/dictionary, etc. So when you do "var value" you can put anything you want after it. This is a big advantage for JS in the sense that you don't have to bother with what type of variable you're defining.


Using "i--" is an increment down in the same sense that "i++" is increment up. Your iterating from the last array index ("rankflavor.len") to the first, hence the "i--".


You are iterating through an array of flavors, for example the array "rankflavor" probably looks something like this:
Code:
rankflavor = ['chocolate chip', 'raspberry', 'strawberry', etc. ]

The location of each flavor in the array can be called by their index starting from 0. Therefore from my example above, rankflavor[0] == 'chocolate chip'.

What this means is the value "i" in your loop represents the index values of the array. When you loop through each index value you are then comparing a rankflavor (which is a string) to the string "flavor". So you are comparing a string to a string.

Let's use these variables for example and run through your loop once.

Code:
i = 4
flavor = "strawberry" (just imagine this is the value)
rankflavor = ['chocolate chip', 'raspberry', 'strawberry', 'mint', 'orange']
An example flow of your loop does this:
i = 4
rankflavor[4] does not equal 'flavor'

i = 3
rankflavor[3] does not equal 'flavor'

i = 2
rankflavor[2] does equals 'flavor' EXIT LOOP

You don't do the last two iterations of "i" because you found your value, it is returned, and you're done.
 

GimmeSlack12

macrumors 603
Apr 29, 2005
5,403
12
San Francisco
Oh shoot. Maybe I was mis-understanding.

During the for loop. Does the ice cream.length stand for the number of characters in the element or the number representing the element in the array?

Either way, thank you!


iceCream.len represents the number of values in the array.

array = [1,2,3,4,5]
array.len == 5
 

ohbrilliance

macrumors 65816
May 15, 2007
1,010
355
Melbourne, Australia
I see the point that the book's author is trying to make, but as a developer, that is dreadful code that only serves to confuse. I'm sure there are better resources for learning JavaScript for beginners.
 

jonpeter

macrumors member
Original poster
Sep 19, 2013
42
0
MI
I see the point that the book's author is trying to make, but as a developer, that is dreadful code that only serves to confuse. I'm sure there are better resources for learning JavaScript for beginners.

could you recommend a better piece of code?
 

ohbrilliance

macrumors 65816
May 15, 2007
1,010
355
Melbourne, Australia
could you recommend a better piece of code?

Here you go. I find the below more readable. It makes it clearer that rankThings has a list of items rather than rank being a function and a list. It also does away with the bogus len variable, instead using Array's built-in length.

Code:
<script type="text/javascript">
var rankThings = function(thing) {
	if (this.things == undefined) {
		return 'I don\'t have a list to compare to';
	}
	
	for(var i = 0; i < this.things.length; i++) {
		if (thing == this.things[i]) {
			return thing + ' is number ' + (i + 1) + ' in my list.';
		}
	}
	
	return thing + ' is not in my top ' + this.things.length + '.';
}

var things = ['one', 'two', 'three', 'four', 'five'];
rank.things = things;

document.writeln(rank('three'));
document.writeln(rank('seven'));

</script>
 

Dunmail

macrumors regular
Mar 27, 2009
224
4
Skipton, UK
Using Array.length inside a for loop (or indeed any form of iteration) is sub-optimal as the code has to work out the length of the array each time.

Here's your function written according to current best practices.

1. Use "use strict" at the start of each function.
2. Variables should be declared at the start of the function
3. Use '===' rather than '=='

Code:
var rankThings = function(thing) {
    "use strict";
    var i,
         len;
    if (this.things === undefined) {
        return "I don't have a list to compare to";
    }

    len = this.things.length;
	
    for(i = 0; i < len; i++) {
        if (thing === this.things[i]) {
            return thing + ' is number ' + (i + 1) + ' in my list.';
        }
    }
	
    return thing + ' is not in my top ' + len + '.';
}

Also: the rank object isn't declared so is attached to the global object which may be OK but could overwrite an existing object of the same name.

Document.write isn't particularly good practice either - it will only work while the page is loading so you can't use it to change or add elements according to user action for example.

To the OP:

Javascript has changed massively in the last few years. If I'm searching for a solution to a problem I generally discount anything older than two or three years as it will be invariably out of date - see my three points above.

----------

I see the point that the book's author is trying to make, but as a developer, that is dreadful code that only serves to confuse. I'm sure there are better resources for learning JavaScript for beginners.

The original code is an accident waiting to happen :eek:

Firstly there is no element at rankFlavour[len] as Javascript arrays are indexed from 0 to len - 1.

Secondly the code decrements the loop counter but never checks that it is still within the bounds of the array so if a flavour not in the list is passed to the function then it will just keep carrying on decrementing, potentially for ever :(
 

ohbrilliance

macrumors 65816
May 15, 2007
1,010
355
Melbourne, Australia
Using Array.length inside a for loop (or indeed any form of iteration) is sub-optimal as the code has to work out the length of the array each time.

Here's your function written according to current best practices.

1. Use "use strict" at the start of each function.
2. Variables should be declared at the start of the function
3. Use '===' rather than '=='

Also: the rank object isn't declared so is attached to the global object which may be OK but could overwrite an existing object of the same name.

Document.write isn't particularly good practice either - it will only work while the page is loading so you can't use it to change or add elements according to user action for example.

Some good advice in there, thanks. I don't claim to be much good at JavaScript, and was just trying to improve on what IMHO was an abomination of an example. I might be a bit more adept if I ever get time to read the Definitive Guide that's been sitting here for the last 6 months :)

rank object was a leftover - it should have been replaced with rankThings
Document.write was purely to demonstrate the result of the code.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.