The_Exile

The_Exile

Need A Lot of Assistance From An Actual js Dev

I am new to programming.

I started reading Eloquent Javascript 3rd Edition, as the book comes highly recommended as a good place for beginners to start. Like every book that makes this claim, it seems to not be the case.

I already ran into problems in Chapter 2.

This is the same problem I run into in every language I’ve tried to use in my attempt to learn how to program.

I never quite understand how to properly construct loops. And it seems every dev making a book to help “beginners” always leaves out important details and assumes that the beginner isn’t a beginner, which is understandable, they are developers not teachers and Pedagogy is it’s own field, still, because of the lack of understanding I am stuck.

They explain the concept of a loop just fine, what it does, and why I’d use one but, they always fail to properly explain how to properly create one and the pieces it uses to do what it does, and how those pieces work with whatever interpreter, etc.

Moving on to where I am stuck…

Chapter 2 - Exercise 2 - FizzBuzz
Write a program that uses console.log to print all the numbers from 1 to 100,
with two exceptions. For numbers divisible by 3, print “Fizz” instead of the
number, and for numbers divisible by 5 (and not 3), print “Buzz” instead.
When you have that working, modify your program to print “FizzBuzz”
for numbers that are divisible by both 3 and 5 (and still print “Fizz” or
“Buzz” for numbers divisible by only one of those).

This was my solution for the Chapter 2 - Exercise 2 problem…


/*
for ( let indexCounter = 1; indexCounter <=100; indexCounter++){
  if ( indexCounter % 3 == 0)
    console.log("Fizz");
  else if ( indexCounter % 5 == 0)
    console.log("Buzz");
  else if ( indexCounter % 3 == 0 && indexCounter % 5 == 0)
    console.log("FizzBuzz");
    else ( indexCounter == Number )
  console.log(indexCounter);
}
*/

It works… Kind of… It generates output but, it’s not the correct output after I compared my solution to the author’s. There is a semantic error and I can’t understand why. I am bashing my head against the wall feeling like a total failure in life, and I am, wanting to jump off my roof, and end my existence for being such a failure. For those who might be concerned with my statement, don’t worry, I won’t but, I feel like it.

The author’s solution is here…

/*
for (let n = 1; n <= 100; n++) {
  let output = "";
  if (n % 3 == 0) output += "Fizz";
  if (n % 5 == 0) output += "Buzz";
  console.log(output || n);
}
*/

When I look at the author’s solution… I just can’t understand what it’s doing or even how it’s doing it. I’ve re-read the chapter 3 times now and it’s just not clicking. The way the author explains it does not stick or make sense to me. I am extremely bad with memorization and it seems the author wants me to memorize a ton of stuff.

I understand the for loop and understand that for loops are great for iteration on a set of values and that if I run into a scenario like this I should use a for loop rather than a while loop. In this case the range of 1-100 are the numbers I am iterating over.

for (let n = 1; n <= 100; n++)

One other thing that throws me off is…
Why define the variable inside the for loop? Why not before?
Is this done because of scope? Aka Local variable being safer than a global? Am I even understanding that?
The author uses “let n = 1” which I am assuming acts as an index counter but, I am not sure.
Another thing is how does the JavaScript know that the variable I set, in this case I used indexCounter, that it’s referring to a range if I never defined a range?

I am assuming n++ is just short hand for n = n + 1. Am I correct?

I am so lost, the author creates a variable called output.
Why? Why is the variable empty? How does an empty string and a number generate any sort of output?

Then he does…

if (n % 3 == 0) output += "Fizz";
if (n % 5 == 0) output += "Buzz";

The way I read that is…

If (expression result) * output += “Fizz”?

What is “+=” ?

I have no idea how that works. Output is null/nill, it’s just an empty string.
How does the result of the previous expression and the variable output even do anything with each other as they are two totally different value types? Better yet, how are they even interacting at all?

Then the author uses this line… console.log(output || n);

Console.log( output or n ) is how I read that. I don’t even know if that’s right or even why he did that. Lol. ( Bashes head into desk )

This is all extremely confusing and JavaScript is making me want to claw my eyes out. The syntax of the language is overly complex compared to others I’ve tried in the past and it’s seemingly for no reason. Yet the world at large has decided to make it the face of the web, which is making me question my faith in humanity. What sadistic group of people thought making JavaScript this integral part of the world wide web? I curse them, I curse them all. Lol.

/js

Marked As Solved

mindriot

mindriot

Looking at your answer, the loop structure itself is pretty good and indexCounter will count from 1 to 100 running the block (between { and } symbols) for each value of indexCounter.

This isn’t a great place to be, when you get stuck like this you do really need to walk away for a bit, take a break and try come back with a fresh mind. Sometimes you will see the answer, other times you might need to ask for help, but continuing on when you feel like this is only going to make it worse. In terms of the actual problem, it is to do with your if/else. A couple of important things about if/else:

  • Only one part (branch) will be evaluated when its matching condition is true. It could be the if, it could be the else or it could be an else if.
  • Each of the possible conditions will be checked from top to bottom to determine which branch to run. Combined with the previous point, this means when multiple conditions are true then only the first branch with a condition which is true is run.
  • Else does not have a condition, it runs in the case that all previous conditions have evaluated to false.

The problem with your version is the sequence of conditions that are checked means the FizzBuzz case can never happen. I’ll leave it as an exercise to work out how to fix this based on the points above, if you are still struggling I can help further.

I haven’t read the book so it is hard to comment much on the way the content is provided. It does feel like there are a couple of things in this solution that for a beginner in chapter 3 are adding some noise / confusion, regardless lets walk through the basic elements of what is going on here and address your questions.

So basically the for loop is a short hand for a common pattern and has become the idiomatic way to express that pattern. You are correct that the author is using n as the index counter, sometimes people frequently use “I” as a short name as well, you are also correct that n++ is a shorthand for n = n + 1. With those things in mind here is a while loop that has exactly the same semantic structure as your for loop here.

let n = 1; // initialise the start of the range before the loop
while (n <= 100) { // check the current value of n before entering the loop body if it is within 1-100
    /// do the stuff
    n++; // increment the counter at the end of the loop body to move to the next number in the range
}

What is happening in the for loop version is the 3 elements used to manage working through the range (the start, the check and the increment) are brought together in the for loop version. This makes the for loop version much easier to see that it is working over a range and what that range is.

The += is another one of those short hands similar to ++. It combines the plus and the assignment together so output = output + "Fizz" and output += "Fizz" are the same. Also + when used on numbers does addition, but when used on strings (like here) joins them together (concatenates).

You seem to roughly understand this correctly. It is really common to see in javascript but is not something I’d personally throw at a beginner. To go a little bit deeper into this, many things in javascript are not true/false but are often “truthy”. If you do a comparison with === or !== then it is strictly comparing true/false values but in most other cases if it has a value then it is interpreted as true and if it does not then it is interpreted as false. In particular, empty strings are considered false, 0 is also considered false, while a string with some letters in it "hello" is considered true and a number other than 0 is also considered true. In addition to this fuzzy version of true and false, javascript also doesn’t care much about types of values and will in many cases try to force the type of a value into one that works. So this output || n thing evaluates to the value of output if the value of output is truthy or the value of n if the value of n is truthy and the value of output is not, otherwise it evaluates to false. The result of evaluating output || n is used as the input to the console log. A clearer way of writing this particular example would be something like:

if (output) {
    console.log(output);
} else {
    console.log(n);
}

Lets go through this authors loop with some comments…

for (let n = 1; n <= 100; n++) // starting at 1, run the block (from { to } ) for each number n up to and including 100
{ 
  // for this particular n
  let output = ""; //  start with an empty output string
  if (n % 3 == 0) output += "Fizz"; // if this n is divisible by 3, join "Fizz" to the output string
  if (n % 5 == 0) output += "Buzz"; // if this n is divisible by 5, join "Buzz" to the output string
  console.log(output || n); // log the output if it isn't empty, log n if the output is empty
}  // move on to the next n

One thing of note beyond your questions here, unlike your version this author is using 2 independent ifs. Your version uses if with else if meaning only the if or else if will be run, but these two ifs will both be checked every time because they do not have else linking them together so they can both run if their conditions both evaluate to true. This means that when n is 15 for example, it can join both Fizz and Buzz to the output string.

You aren’t the only one that feels that way. What is worse is many of the things that create confusion or end up biting you pretty hard were actually intended to make it easier for people to get started with :man_facepalming: It is also worth remembering that it was intended to be easy to add fairly trivial little snippets to web pages and is now being used to build desktop class applications with many millions of lines of code. Along the way some things have improved, but the old things are still there and improvements have to work with them, so even though much of the evolution looks like improvements there is all kinds of hidden spicy bits in there.

Popular Frontend topics Top

PragmaticBookshelf
WebAssembly fulfills the long-awaited promise of web technologies: fast code, type-safe at compile time, execution in the browser, on emb...
New
PragmaticBookshelf
Upgrade your skill set, succeed at work, and avoid the many headaches that come with modern front-end development. Simplify your codebase...
New
PragmaticStudio
Let’s get real. As in really knowing—clearly and practically—what’s up with Phoenix LiveView. What is it? How does it work? What can I ...
New
DevotionGeo
Dart is not the first language with that mistake, but it’s newer. It shouldn’t have repeated this mistake.
New
AstonJ
Wondering if anyone has any thoughts on choosing between these two languages for WebAssembly? I definitely want to explore wasm, and rea...
New
PragmaticBookshelf
Tailwind CSS is an exciting new CSS framework that allows you to design your site by composing simple utility classes to create complex e...
New
mrmurphy
The situation Hi there! I’m working on a live view app right now that encrypts sensitive user content (text and images) using the browser...
New
Sally_san
So I’ve got a client that wants to build a site like this: Specifically 3 things from the website: The fullscreen sections that chang...
New
JesseSkinner
I’ve developed a video course called The Joy of Svelte, where I go in depth on Svelte features, especially different ways to manage state...
New
Reinis
For the last few months I’ve been (re)-learning vanilla CSS. Initially I did not ‘get’ how to structure CSS to take advantage of the ‘cas...
New

Other popular topics Top

axelson
I’ve been really enjoying obsidian.md: It is very snappy (even though it is based on Electron). I love that it is all local by defaul...
New
brentjanderson
Bought the Moonlander mechanical keyboard. Cherry Brown MX switches. Arms and wrists have been hurting enough that it’s time I did someth...
New
foxtrottwist
Here’s our thread for the Keyboardio Atreus. It is a mechanical keyboard based on and a slight update of the original Atreus (Keyboardio ...
New
AstonJ
Just done a fresh install of macOS Big Sur and on installing Erlang I am getting: asdf install erlang 23.1.2 Configure failed. checking ...
New
AstonJ
This looks like a stunning keycap set :orange_heart: A LEGENDARY KEYBOARD LIVES ON When you bought an Apple Macintosh computer in the e...
New
AstonJ
Do the test and post your score :nerd_face: :keyboard: If possible, please add info such as the keyboard you’re using, the layout (Qw...
New
dimitarvp
Small essay with thoughts on macOS vs. Linux: I know @Exadra37 is just waiting around the corner to scream at me “I TOLD YOU SO!!!” but I...
New
DevotionGeo
The V Programming Language Simple language for building maintainable programs V is already mentioned couple of times in the forum, but I...
New
wmnnd
Here’s the story how one of the world’s first production deployments of LiveView came to be - and how trying to improve it almost caused ...
New
Help
I am trying to crate a game for the Nintendo switch, I wanted to use Java as I am comfortable with that programming language. Can you use...
New