Is the "for" command used often by professional developers?

How often is the “for” command (e.g. for( j = 0; j < arr.length; j++)) used by professional JavaScript developers? The reason I ask is because it’s the single aspect of JavaScript that I’m still having trouble with even after many months of coding.

If it’s not something that’s used often by development companies then I was thinking of placing more emphasis on other commands that can achieve similar results.

Often. You’ll see for in a handful of other languages. Languages such as C, C#, Java, etc. share that same for syntax.

1 Like

I once read that beginners use a bunch of ifs, and experienced developers use a bunch of loops.

You choose the right tool for the job, but knowing the basics of the language is a must.

The for-loop is probably one of the most used control flow statements. It is the primary way to iterate through data, so you will have to get used to it.

Of course there are other kinds of loops - the while loop, and the Array.prototype.forEach loop - but in the end all of these operate under the same paradigm. Learn the standard for-loop first.

I suggest practising them more, if you can be specific about what trouble you are having we can offer more help.

2 Likes

I agree to answers above, yet in a nutshell if you dont undestand for loop I’m gonna try explain it…
First loop is repetition of command, so if you have some code that has to repeat - loops are for that.
Now for loop is primarily used when you have definitive number of repetitions - for example 10. Then for loop is your choice. Let’s dissect syntax :slight_smile:

  1. First you need variable that will be used as counter ex. to count to 20
  2. You need a condition until the loop will repeat for instance if counter < 20, so it will repeat until condition is met.
  3. Last part is changing value of counter so that condition will finally be met and loop will end.

In code :slight_smile:

!) var counter = 0;
2) counter < 20
3) counter = counter + 1

If you put these three code snippets into for it will look smth like this :slight_smile:

for(var counter = 0; counter < 20; counter = counter + 1) {
// code that repeats
}

Javascript as many other C-like laguages have a short version of counter = conter + 1 and it spells conter ++.

So when you put all this together you will have final syntax :slight_smile:

for(var counter = 0; counter < 20; counter++){
console.log(counter);
}

This example above will produce output : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

All in all you will find lot of for loops on net and in every code almost. But basic idea of loops in general is - if you have code that repeats use loops. Hope that clear air a little bit :wink:

What is it about the for loop that you have issue with?

Do you also have issues with the while loop?

More advanced style is to use e.g. map, filter, reduce etc. but if you don’t understand for loops, you’ll really have a tough time with those. You have to know this. But don’t worry it will “click” eventually.

2 Likes

My main issue was simply that I found using a lot of ‘if’ and ‘else if’ statements easier than using for loops (something that Oxyrus mentioned a few posts above). I understand the mechanics of ‘for’ loops, it’s simply that I find the logic too complicated when it comes to implementing such loops in my code (be it for algorithms or anything else). Hence why I opt for the ‘if’ path.

For loops and Ifs are totally unrelated.

One usually use Switch/Case statements if there’s a lot of IFs involved.

For…Next loops are usually used if you know in advance how many iterations you need to do. Otherwise, languages usually have a Do (condition)… Loop, or While (condition), or Repeat Until (condition) types that are more commonly used.

I’ve been coding professionally for over 20 years. Here’s my take, for what it’s worth…

Working with collections (or lists) of things is very common. Needing to apply some logic to every item in a list is also extremely common. Generally, there are two ways to approach this:

  1. Recursion
  2. Iteration

Recursion means you have a function that calls itself. For example:

function countdownFrom(n) {
  if(n <= 0) {
    return
  }
  console.log(n)
  countdownFrom(n-1)
}

Notice that the last line of the function above calls itself. This is recursion. There are two common problems with recursion:

  1. It tends to be hard to read and understand.
  2. Many programming languages are not optimized for this kind of code and will perform poorly when attempting to recurse. Interestingly, in 2015 the standard that JavaScript is based on introduced something called “tail call optimisation” which makes recursion fast, BUT most modern browsers STILL don’t support it.

Iteration is when you have a function that loops over a collection in some way. The for loop is usually the first type of Iteration that most developers learn. It is generally taught in the form:

for (i = 0; i < collection.length; i++) {
// do something with collection[i]
}

Our countdown example from earlier could be written as follows:

for (i = 10; i > 0; i--) {
  console.log(i)
}

Performing iteration with a for loop has the following drawbacks:

  1. It requires the programmer to explicitly create and manage a loop counter. In the case of the above functions the i is our loop counter. Notice that we declare it, set its value, and increment it.
  2. for loops can be difficult to read and understand.

A for loop is an example of what is called Imperative Programming.

Imperative programming is a style of programming where the code provides explicit instructions for how to achieve the desired result. Imperative code tends to be longer and more difficult to decipher. For this reason, experienced programmers tend to avoid the imperative style whenever possible.

The preferred style for most experienced programmers these days is Declarative Programming.

In declarative programming, we write code that describes what we want to do, instead of how we want to do it. JavaScript provides a number of ways to perform iteration using a declarative style.

In particular, the Array type in JavaScript exposes many Declarative style methods, the most popular are map, reduce, and filter.

Typically, an experienced programmer will prefer one of these methods to a basic for loop. Depending on what the program is trying to accomplish, a different method will be appropriate.

Let’s look at each one.

Map

Suppose we want to capitalize each word in an Array of words. With a for loop we would write:

for (i = 0; i < words.length; i++) {
  capitalizedWords.push(words[i].toUpperCase())
}

Using map this becomes:

const capitalizedWords = words.map((word) => word.toUpperCase())

Reduce

Suppose we wanted to add all the numbers in an Array. With a for loop we would write:

for (i = 0; i < numbers.length; i++) {
  total += numbers[i]
}

Using reduce this becomes:

const total = numbers.reduce((subTotal, number) => subTotal += number)

Filter

Suppose we wanted to remove all vowels from a word. for:

for (i = 0; i < word.length; i++) {
  if (!vowels.includes(word[i])) {
     noVowels.push(word[i])
  }
}

filter:

const noVowels = word.split('')
                     .filter((letter) => !vowels.includes(letter))

Also of note, the declarative methods I described above are all what we call “higher order functions” and higher order functions are the gateway drug to a type of declarative programming known as functional programming which has seen a real rise in popularity over the last few years.

So, to re-iterate (see what I did there? ;)) the answer to your question is, most professionals prefer to avoid for when a more declarative or functional option presents itself.

12 Likes

Excellent explanation! I’m bookmarking this one for later use.

1 Like

That’s a great explanation - thanks.

I’m struck with the question: How is the declarative structure better? I’m not disagreeing, just curious.

Is it faster? My understanding is that it’s still going to do an iterative loop, it’s just going to be shrouded in a method.

I suppose one can argue that it’s a little easier to read once you get used to it. (Although having programmed in C, I’m always a little wary of cramming too much programming in one statement.)

1 Like

Declarative programming is not necessarily faster than Imperative programming. Nor is it necessarily always better. I use it and recommend it because it generally makes code more readable and easier to reason about.

A straightforward example is the JavaScript code for reversing a string.

Imperatively we have:

function reverseString (str) {
  var reversed = ''
  for (i = str.length - 1 ; i >= 0 ; i--) {
    reversed += str[i]
  }
  return reversed
}

The same thing declaratively is:

function reverseString (str) {
  return str.split('')
            .reverse()
            .join('')
}

Like all recommendations, there will always be exceptions. You may come across a case where the imperative version is more readable or less brittle.

Also, your point about “cramming too much programming in one statement” is well taken. I think we have to consider two things when we write compact code.

  1. Has the compactness enhanced or diminished the readability of the code?
  2. Are we introducing intermediate steps that may fail and if so, should they be handled independently?

Point 1 is pretty easy to understand. The following is very compact, but god help us if we’re stuck maintaining this kind of code.

function r(s){var x='';for(i=s.length-1;i>-1;i--){x+=s[i]};return x}

Point 2 is a bit trickier.

In our declarative string reversal example, if the call to str.split('') returns null or undefined, the call to reverse() will raise an Exception and hang our program. So is it worthwhile to separate the calls and introduce a check?

Like, is this better?

function reverseString (str) {
  var strArray
  var reversedArray
  var reversed
  
  if(typeof str !== 'string') {
    throw Error('parameter, "str" must be a string')
  } 
  
  strArray = str.split('')
  
  if (Array.isArray(strArray)) {
    reversedArray = strArray.reverse()
  }
  
  if (Array.isArray(reversedArray)) {
    reversed = reversedArray.join('')
  }
  
  return reversed
}

And if we do that, what about Array.isArray if that returns something other than a boolean, we’re toast. So should we break that out too?

In this case, I think the answer is “no”. We stick to the original declarative version.

Why? Because we trust the intermediate functions AND (more importantly) our checks don’t really allow us to recover gracefully or return a significantly clearer error message. The custom error message is better, but not so much so that it’s worth the extra code (IMHO).

There will be cases where it is worth breaking things apart, but it really depends.

My criteria tends to be, if a check would allow us to do something decidedly better than the default behaviour, then seperate the code. Otherwise, we should be as concise as possible without sacrificing readability.

I hope all of that makes sense.

P.S. I write about this kind of stuff and provide lots of interesting links in my weekly newsletter. Feel free to check it out below…

https://upscri.be/b1334e

2 Likes

My advice is if you’re finding the logic a bit complicated, keep working with them. When you get a more complicated if statement, after it’s working try to write a for loop that does the same thing. Then test them both to verify you’re getting the same results.

When I started out I used more if statements myself, but found that they were getting long and complicated. They were requiring a lot of typing and taking up a lot of space. Also as they grew it was taking more effort to tweak them. I gradually found myself transitioning to using more for loops.