If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Enjoy an ad free experience by logging in. Not a member yet? Register.

I am also learning JavaScript and I think I have some idea what you are asking.

For a very simple example, suppose there is a page with many '<p>' tags and you want to change text color or background color of them depending upon if they are odd or even.
You can collect all row elements in an array and then using for loop over it change styles of alternate rows.

please look at following example. we are collecting all 'P' tags in HTML Colection which is an array.

I am also learning, so not sure if it is right way to do it. var paras = document.getElementsByTagName('p');
var plength = paras.length;
for (var i=0; i<=plength; i++){
if(i%2==0 )
paras[i].style.color = '#ff0000';
else
paras[i].style.color = '#0000ff';
}

try to run it in console on some webpages.
In Firefox you can open console usinf 'CTRL+Shift+K',
in chrome 'Ctrl+Shift+J' or 'F12'
'F12' in Firefox opens firebug console if you have installed it.

in programming, you often need to store information. We put little chunks of info behind nicknames we refer to as variables. Sometimes we have not just one chunk, but many chunks of info. When you have a lot of info that is similar and related, an array can be used to group it all together behind a single nickname.

Going back to the CD audio days, an apt analogy can be had considering an album vs a single, the album being an array of single tracks. Sometimes you want the whole album to just sit back and relax, and sometimes you want to jump right to a certain song. The array provides both capabilities; random-access and sequential access. This is much handier than having to swap 10 different disks to hear 10 different singles, or using 10 different variables to refer to that entire collection. It's so much better that folks began to construct/burn their own arrays of tracks under variable names like "driving mix", "dinner", "80s", etc...

that's the motivation behind arrays: organization. Sometimes the data in them is unique, sometimes its "copied" into an "array" for convenience, like getElementsByClassName("hidden"). Sometimes arrays actually duplicate thier contents from other places and sometimes they act like tiny re-directs to the actual info contained in other places, but the commonality is that they make it easier to apply verbs to related nouns.

traditionally those verbs were applied procedural-aly using loops, but as felgall mentions, there are much better 21st-century ways of handling such collections. Take a look at jQuery to see this power in action. jQuery's CSS selectors make it easy to grab a custom collection of tags from the DOM. Speaking loosely, a jQuery call returns an array of tags, but that's only half the magic. The real power is how it can apply verbs to all of the single tags at once. For example, we can express the behavioral outcome of skywave's code in much less code as higher-level terms using jQuery:

as you can see, the code is almost all nouns and verbs; no conjunctions, conditionals, or pronouns like you have with loops.

you can use the same power on data as jQuery provides on tags by using the newer (5 years old at this point; time flies!) Array methods like [].map, [].filter, [].forEach, [].reduce, [].some, and [].every. I won't get into what each one does, but together they provide the modern programmer with a very slick and convenient way to express the intentions they have for data. If you want to leapfrog everyone around you, skip over procedural snooze fests like for loops and figure out how javascript's chaining works. It's different yes, but no more complicated than loops, and even if it were 50% harder to understand, it's 1000% better for you in the long run...

i use this native way (no vars, user-functions, or loops) of populating a numerical array :

Code:

Object.keys(new String(Array(11))).map(Number);

That works fine, but IMO it is difficult for a newcomer to understand. Especially Array(11) when 0-9 is wanted.
And there is still a var in the array name - var x = Object.keys(new String(Array(11))).map(Number);

Is there any real advantage in using such a construct as compared with the traditional (old-fashioned) loop which is pretty obvious?

var box = [];
for(i=0; i <=9; i++) {
box[i] = i;
}

Last edited by Philip M; 02-13-2014 at 08:57 AM.

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Is there any real advantage in using such a construct as compared with the traditional (old-fashioned) loop which is pretty obvious?

var box = [];
for(i=0; i <=9; i++) {
box[i] = i;
}

well, that snippet creates an implicit global, which is not obvious to newcomers. I know that's easily fixable, but it underscrores my concerns about for loops in JS in a more general kinda of way. of course, both routines work, as do 5 others i'm sure.

I would submit that there is nothing obvious about the for loop code; it's got a bunch of \W chars, some non verbs/nouns, a certain order of init params that's not obvious, and one only knows it because they learned a different language first. But prior familiarity works against them as well because they assume that it has it's own scope. I see loop issues comprising at least 10% of "why doesn't this work" type questions; the biggest single part of the JS core that actually screws people over and causes frustration.

Now, i'm not saying scope is an issue here, as long as you use locals, which even senior coders can forget. My point in posting is just to illustrate an alternative. If you can work out how the functional approach works, you'll not only know about some kick-*** native methods, you'll be on the way to custom chaining, which IMO is JS's best feature and one that sets it apart from most other languages in a developer-friendly way. If a simple counter can show how functional works, hopefully newcomers will start on the 21st-century path instead of using procedural constructs i learned in BASIC.

in short, there's little advantage either way; both have their ups and downs. But if you're gonna do it, why not do it in a way that encourages exploration into really powerful features rather than really boring and jargony features. I rarely use for-loops any more, and i guess this reflects with my newer problem-solving mindset rather than when i was wearing noob shoes. Maybe it's just a vain attempt to jump in front of the for-loop bullet that kills noob interest in JS and leads to mis-founded claims about the language being "broken".

plus i figured there would be like 15 billion for loop examples out there; so why not tease some good code...

It is a part of the current JavaScript standard released in 2011. Alll browsers that support JavaScript support those methods other than really antiquated browsers such as Firefox 1.0 - which is long dead.

Microsoft didn't introduce support for JavaScript into Internet Explorer until version 9 which is why IE8 didn't support those JavaScript commands. IE8 only runs Microsoft's own JScript - which Microsoft discarded after IE9 so that language is now dead.

You can easily add the extra methods yourself so as to support people using really antiquated browsers while still using modern code. Then once you no longer need to support tha really antiquated browsers you can delete the code you added specifically for them and have modern code.

Anyway, there's no reason for anyone to still be running IE8. I had IE11 running on my Windows XP computer last year (before I replaced that somewhat antiquated computer with a more modern one).

you can wait for folks to upgrade their browser and js, or you can bring the upgrades to them (and only them) with just a few kb of code. Tools added into JS since 2007 were added for a reason, a good reason. Personally, i can't imagine doing anything worthwhile without them. Sure one can code like it's 1999, but given the choice, why would any serious programmer not want to use a fourteen-year newer set of tools?

If such handy methods couldn't all be patched in <4kb of non-min'd code, i'd be very tempted to abandon IE8. It's dying pretty fast and i like to code for the future, not the past, because the future lasts longer and is more important. How do i know this? The image editor i wrote for "gran paradiso" in 2007 worked on the ipad when it came out years later... Had I insisted on catering to the Lowest Common Denominator, i wouldn't have an image editor, and a crucial job interview i had in 2009 might have gone very differently. It pays (literally in my case) to push the boundaries, especially when the risk is quantifiable. I just wish canvas was as easy to polyfill as [].map...

Since it's harmless and mindless to teach old browsers these great new tricks (without imposing on browsers produced in the last five years) my abandonment temptations are practically moot.