Can someone help me understand how to assign variable for this javascript?

Task: Create a program in any language that starts by assigning the alphabet (“abcde…z”) to a variable and then uses other variables, loops, string functions, and conditionals to output this:

A
AB
ABC
ABCD
ABCD3
ABCD3F
ABCD3FG
ABCD3FGH

etc.

ABCD3FGHIJKLMNOPQRSTUVWX
ABCD3FGHIJKLMNOPQRSTUVWXY
ABCD3FGHIJKLMNOPQRSTUVWXYZ

Note that the letter E should be replaced with an “3” in each line.

Sounds like homework. What have you tried and where are you stuck?

I just don’t know where to begin…

Would it be something like this?

var alphabet = “abcdefghijklmnopqrstuvwxyz”.split(“”);
_.each(alphabet, function(letter) {
console.log(letter);
});

it;s not really homework, I;m just trying to understand javascript and I don’t know how to start it… I;m self-learning it.

Well that would be relying on a library to provide the _.each

Also that only gets you the individual letters displayed in the console (assuming _.each does the same as the forEach method for arrays).

You can do what you asked about using regular JavaScript like this (note I didn’t bother assigning the alphabet to a variable as it only needs to be referenced once):

<div id="result"></div>
<script>
document.getElementById('result').innerHTML =
'ABCD3FGHIJKLMNOPQRSTUVWXYZ'.split('').map(
  function(a,b,c) {return c.join('').substr(0,b+1)+'<br>';}).join('');
</script>

As felgal says, _.each is provided by underscore. There’s no reason not to use the library per se (it’s great), but in this case, it’s not strictly necessary.

What I would do is declare the alphabet as a string, then iterate over it using a for loop. Within the for loop, you can then use JavaScript’s native substr method to slice off an ever increasing part of the alphabet and output it to the screen.

var alphabet = 'ABCD3FGHIJKLMNOPQRSTUVWXYZ';
for(var i=0; i<26; i++) {
  console.log( alphabet.substr(0, i+1) );
}

This will log the output to the browser’s console. If you want to output something to a webpage, here’s a more complete example:

<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8 />
    <title>Output alphabet incrementally</title>
  </head>

  <body>
    <div id="result"></div>

    <script>
      var result = document.getElementById('result');
      var alphabet = 'ABCD3FGHIJKLMNOPQRSTUVWXYZ';

      for(var i=0; i<26; i++) {
        var content = alphabet.substr(0, i+1);
        result.innerHTML = result.innerHTML + content + '<br>';
      }
    </script>
  </body>
</html>

This uses innerHTML to concatenate and set the result div’s content.

Just to be complete, I suppose you could use map() as felgall has done, but I’m not sure what it buys you here. Personally, I’d avoid this (unless I missed something @felgall?)

1 Like

Not really - I just tend to avoid using for loops now that JavaScript has all the array methods that were added in 2009. So just an alternative way of doing the processing.

Of course if the requirement changed to get rid of some of the letters of the alphabet then my version only needs to be amended in one place where your more readable version would need to have changes made in two places.

Cool thanks!

Im trying to understand javascript but there’s so much complex things!

I think I understand java more because it’s a little more simpler. I know they are similar in lots of ways, but java seems to stick to my head a bit better for some reason.

So var alphabet = A-Z is the alphabet is being outputted that I get.

For is the loop and it counts to 26 letters of the alphabet. I know i++ means increment.
So we always have to use this if we are counting up?

Now that I sorta get it but what does var content = alphabet.substr(0, i+1)
And what does result.innerHTML = result.innerHTML + content + ‘
’; mean and do?

Sorry if I’m not very smart. Javascript was never my favorite. I want to learn each part of it so I can understand it next time I do something as simple as this.

Thank you for all your help though guys!

where “c” instead of “0” works as well…
i am trying to figure that out. Beginner as well :slight_smile:

Yeah, but it’s not an array we’re dealing with. I think it’s a bit harsh to say “totally avoid for loops”, as they still have their uses.

Lol.

var content = 'ABCD3FGHIJKLMNOPQRSTUVWXYZ'.substr(0, i+1);

Yup. You could also count down using i-- (just to illustrate the point):

for(var i=27; i>0; i--) {
  console.log( alphabet.substr(0, i-1) );
}

The substr method is actually deprecated. On reflection, it’d be better to use substring():

for(var i=0; i<26; i++) {
  console.log( alphabet.substring(0, i+1) );
}

In the above example we are calling this method on the string we previously defined (so, a-z) and passing it the value of i + 1. The first time the for loop runs, i will be 0, so we are in effect saying:

‘ABCD3FGHIJKLMNOPQRSTUVWXYZ’.substring(0, 1)

which will return the part of the string between index 0 and 1 (i.e. “A”).
In the next iteration of the loop, i will be 1, so we are saying:

‘ABCD3FGHIJKLMNOPQRSTUVWXYZ’.substring(0, 2)

which will return the characters of the string between the index 0 and 2 (i.e. “A”, “B”) etc.

We are setting the inner HTML (the content) of the result div. We are setting it to be itself, plus the result of our substring() operation, plus a line break.

Initially, the content of the result div is nothing. When the loop runs for the first time, 'ABCD3FGHIJKLMNOPQRSTUVWXYZ'.substring(0, 1) returns “A”, so we set the content of the div to “A<br>”.

The second time the loop runs, 'ABCD3FGHIJKLMNOPQRSTUVWXYZ'.substring(0, 2) returns “AB”, so we are setting the content of the div to “A<br>” plus “AB<br>”. This will carry on until the loop has run its course.

Does that make things a little clearer?

I was thinking of a few other ways:

One way is to do it in reverse, where you just chopping off the last character after each line and then display the lines in reverse:

var letters = "ABCD3FGHIJKLMNOPQRSTUVWXYZ";
var list = [];
var result = document.getElementById("result");
while (letters.length > 0) {
    list.push(letters + "<br>");
    letters = letters.substring(0, letters.length - 1);
}
.innerHTML = list.reverse();

We could use the reduce method to achieve the same thing too:

var letters = "ABCD3FGHIJKLMNOPQRSTUVWXYZ";
var result = document.getElementById('result');
result.innerHTML = letters.split("").reduce(function(result) {
    result.push(letters + "<br>");
    letters = letters.substring(0, letters.length - 1);
    return result;
}, []).reverse().join("")

The only problem with these techniques though is that it destroys the letters string. It’s better if we don’t have such side-effects.

Instead of destroying the letters, we can recreate them by joining up the split array instead. And because the reduce function gives us among other things an index number and the array of chars, we can do it in forward order handily exploiting that index to our benefit:

var letters = "ABCD3FGHIJKLMNOPQRSTUVWXYZ";
var result = document.getElementById('result');
result.innerHTML = letters.split("").reduce(function(result, char, index, arr) {
    var chars = arr.join("");
    result.push(chars.slice(0, index + 1) + "<br>");
    return result;
}, []).join("");

Which brings us back to Felgall’s solution, where I present it again but with variable names to help aid with the understanding:

var letters = "ABCD3FGHIJKLMNOPQRSTUVWXYZ";
var result = document.getElementById("result");
result.innerHTML = letters.split("").map(function(char, index, arr) {
    var allChars = arr.join("");
    var chars = allChars.substr(0, index + 1);
    return chars + "<br>";
}).join("");

Hopefully being expanded out by clear variable names, the behaviour of the code will be easier to comprehend, allowing a clearer understanding of how the code with less variables behaves:

document.getElementById("result").innerHTML =
    "ABCD3FGHIJKLMNOPQRSTUVWXYZ".split("").map(function(char, index, arr) {
        return arr.join("").substr(0, index + 1) + "<br>";
    }).join("");

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.