Sunday, July 3, 2011

Samrter & better than "loop statements" With JavaScript Join() function


Al salam alikom ("hi all")
   Today we'll talking about amazing JavaScript function it's the "Join()" function, and I'll explain it with an easy example & little words

before the example let's see what is the definition of (join()) 

The join() method joins all elements of an array into a string, and returns the string.
The elements will be separated by a specified separator. The default separator is comma (,).

Syntax
----------------
 
Join(separator);

separator: Optional. The separator to be used. If omitted, the elements are separated with a comma

So, if we have an array and wee need to display it in html list ("ul")
we have to options

First solution:
--------------------


var arr = ["Cairo", "Alex", "Aswan"];
var list = "<ul><li>";
for (var i = 0; i < arr.length; i++) {
    if (i !== (arr.length - 1)) {
        list += arr[i] + "</li><li>";
    }
    else {
        list += arr[i];
    }
}
list += "</li></ul>"
;

Second solution:
-------------------
 which i recommend it and it's very easy & smart

var arr = ["Cairo", "Alex", "Aswan"];      
var list = "<ul><li>" + arr.join ("</li><li>") + "</li></ul>";

The two solutions have the same out and you have the choice to use any one of them, but i think (2) lines of code are better than (11) ;)