Need quick explanation of javascript code

Discussion in 'Web Design and Development' started by jonpeter, Nov 7, 2013.

  1. jonpeter, Nov 7, 2013
    Last edited by a moderator: Nov 8, 2013

    jonpeter macrumors member

    Joined:
    Sep 19, 2013
    Location:
    MI
    #1
    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.
     
  2. GimmeSlack12 macrumors 603

    GimmeSlack12

    Joined:
    Apr 29, 2005
    Location:
    San Francisco
    #2
    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 :)

    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.
     
  3. jonpeter thread starter macrumors member

    Joined:
    Sep 19, 2013
    Location:
    MI
    #3
    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.

    . . .




     
  4. GimmeSlack12 macrumors 603

    GimmeSlack12

    Joined:
    Apr 29, 2005
    Location:
    San Francisco
    #4


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

    array = [1,2,3,4,5]
    array.len == 5
     
  5. ohbrilliance macrumors 6502a

    ohbrilliance

    Joined:
    May 15, 2007
    Location:
    Melbourne, Australia
    #5
    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.
     
  6. robvas macrumors 68020

    Joined:
    Mar 29, 2009
    Location:
    USA
    #6
  7. jonpeter thread starter macrumors member

    Joined:
    Sep 19, 2013
    Location:
    MI
    #7
    could you recommend a better piece of code?
     
  8. ohbrilliance macrumors 6502a

    ohbrilliance

    Joined:
    May 15, 2007
    Location:
    Melbourne, Australia
    #8
    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>
     
  9. Dunmail macrumors regular

    Joined:
    Mar 27, 2009
    Location:
    Skipton, UK
    #9
    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.

    ----------

    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 :(
     
  10. ohbrilliance macrumors 6502a

    ohbrilliance

    Joined:
    May 15, 2007
    Location:
    Melbourne, Australia
    #10
    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.
     

Share This Page