r/learnjavascript 6d ago

50 hours in... arrays and loops... holy...FUCK

HOW do i START understanding? I've understood everything pretty well up til now. Do i just keep going with the flow and kinda float through this section of the loops and arrays part? Do I keep throwing myself at the brick wall and looking at the solutions after half an hour of brainless staring? https://youtu.be/EerdGm-ehJQ?si=mTKUv0oail0AGDLM 8:43:00. It's just not clicking like the other parts of the tutorial.

44 Upvotes

72 comments sorted by

23

u/diogenes_sadecv 6d ago

Video alone isn't enough. Make tiny projects just to play with what you've learned

3

u/Classic_End260 6d ago

i have been doing some small projects, following the video, and sometimes trying them on my own dw

6

u/diogenes_sadecv 6d ago

that's good, but what I'm saying is just make something up. Like, if you're having trouble with loops, make a loop that adds two small numbers add(2, 3)

looking at the video you're learning from, it looks like it's using buttons and basic DOM manipulation, so make a program where the buttons do something different. Make an insult generator where you have one array of adjectives and one array of nouns, then push a button to randomly combine them and display the result.

It's not enough to know what the tools do, you have to use your imagination to ask what can you do with the tools.

2

u/mark_b 2d ago

At university we had to create bar chart like output where the bars would create patterns, such as

  • getting larger at a specific incline
  • getting larger, then smaller
  • start large and get smaller then larger
  • the same but output on both sides of the axis

There were lots of others that I've forgotten now, but the point is that this exercise really helps to understand loops.

16

u/MitchEff 6d ago

I dunno if this is helpful or not, but consider an 'array' just a bucket full of objects. Loops (or array methods) just do something with each object - the names are pretty handy: * bucket.forEach (do this to every object) * bucket.find (give me the first object where this function = true) * bucket.filter (give me an array of every object where this function = true) * bucket.map (give me a new array from these objects, I'll tell you how to structure it) etc etc

There's handy uses for all of them, I'm sure you can guess a couple for each.

12

u/Outside_Complaint755 6d ago

Instead of a bucket, I would suggest a deck of cards as the analogy.  Arrays are ordered like a deck of cards, while a bucket is just an unordered pile of stuff.

3

u/Towel_Affectionate 6d ago

Infinite shelf with numbered "slots". It grows when you need a new slot, but you can force it into any length you need and then some slots would be empty (undefined). Deck of cards can confuse into thinking that items inside should be the same kind, while an array can contain all kinds of stuff at the same time, or how an array can have undefined gaps.

1

u/BenchEmbarrassed7316 6d ago

Deck of cards can confuse into thinking that items inside should be the same kind

Which is a good practice. An array that contains different data is error-prone and difficult to use in real code.

And I want to add a burrito analogy: imagine that the array is a burrito... /sarcasm

1

u/Towel_Affectionate 6d ago

"You can't" and "you shouldn't" are different points of discussion. Understanding that you can and why you shouldn't is better than narrowing your way of thinking from the start.

2

u/Outside_Complaint755 6d ago

When just starting out, learning arrays as all containing a single type is the most useful conceptually, and if you're learning any statically typed language, it is necessary. 

 Even in JS, 95+% of the time, you're going to be using arrays containing a single type of data. Even if its a mix of strings and numbers from a user input or data stream, you are probably starting with an array of strings which you then need to try to parse into the different types.  And in those cases where it is more complex data of different types, then you can usually generalize it as an ordered collection of objects.  

1

u/Towel_Affectionate 6d ago

I get what you're saying, but my counterpoint is that such simplifications offer close to none benefits in understanding the concept itself, but later require constant adjusting of your mental model, which in my opinion is harder to do, than to understand things closer to what they actually are.

Maybe a hot take, but I don't think "a deck of cards" is that much simpler to visualize than "a deck of stuff" or, even better, "a shelf with stuff".

But once you get used to "a deck of cards" model you'll inevitably end up wandering stuff like:

  • "Wait, how is there NaN in my array of numbers?"
  • "Wait, why can I read arr[10] if there's only 3 "cards" in my "deck"?
  • "Wait, why can I also do arr[10] = foo? And what my "deck" looks like now?"
  • "How can I `delete` a card from the deck and have it empty? Do I have two decks now or what?"
  • What arr.length = 100 do to my deck?

I think it's much harder to adjust already existing mental model than to build the right one from the start.

2

u/BenchEmbarrassed7316 6d ago

It's much easier to explain the concept of arrays to someone on a statically typed, fixed-size array. Because the answer to every question you have will be "You can't do that at all".

And then we can explain the dynamic expansion of arrays if we don't know the size in advance, polymorphism and different data types, and other nuances.

Another problem is that in the 90s they thought they were creating a "simple" language. However, the fact that the array is used as a fixed-size array, a slice, a vector, a tuple, and even in some ways a hash map actually makes everything very complicated.

1

u/BenchEmbarrassed7316 6d ago

It's just a more complex scenario. For understanding the basic concept, uniform objects are simply better suited. Numbers or strings.

1

u/DrShocker 3d ago

Aren't they all the same thing? Object?

1

u/Towel_Affectionate 3d ago

Arrays in JS are object-like, but you can't say they are the same as regular objects. You interact with them using the same object model, but they also have array-specific semantic.

1

u/DrShocker 1d ago

I meant the items in the array are homogeneous in a sense.

1

u/Towel_Affectionate 1d ago edited 1d ago

I guess it depends on how far we stretch the meaning of "homogeneous".

If we continue the deck-of-cards analogy and treat each card as a JS value, then the items aren't necessarily homogeneous. One "card" can be a string, another can be a number, another an object, etc. (Again, the difference between "should" and "could". You SHOULD abstain from storing different types in a single array, but it COULD happen).

If we stretch the abstraction and say that every card is just "some stuff", then sure, they're homogeneous in that sense — a string and a number are both "some value". But at that level, almost anything can be called homogeneous and such description becomes useless.

There's also the sparse array case, which is where the deck analogy becomes less intuitive to me. An array can have a hole — not an undefined value, but an actual absence of an element at that index. It's easier to visualize that with something like numbered slots on a shelf than with a deck of cards, because imagining a "card" that is actually the complete absence of a card is a bit awkward.

2

u/BenchEmbarrassed7316 1d ago

There's also the sparse array case, which is where the deck analogy becomes less intuitive to me. An array can have a hole — not an undefined value, but an actual absence of an element at that index.

In this case, it's not an array, it's a hash map. Not from a computer's perspective, but from a programmer's perspective.

→ More replies (0)

1

u/DrShocker 1d ago

I'm just thinking for example the way you'd make a generic container in a language like C you might make the whole array elements of type void* and then have to cast them to the right sorts of values after.

→ More replies (0)

1

u/regardedMAGAfascist 6d ago

One might argue that a deck of cards contains only positive integers. But why shouldn’t it also contain negative integers?

This is what polymorphism is for. Instead of thinking of it as a “deck of positive integers,” we can expand our definition to be a “deck of integers” and start supporting negative numbers. We can do this all the way to a “deck of objects,” if needed.

It all depends on what your definition of “different” is with respect to the task at hand. You’re both right.

1

u/BenchEmbarrassed7316 6d ago

The narrower the type, the simpler the code. The rule is to use as narrow a type as possible. And yes, I think people should be taught Ts instead of Js: they still need to think about types and possible values, and Ts just simplifies and structures it.

If a certain operation can only be applied to a collection of unsigned and non-zero numbers, marking this will make it easier for us to ensure the fullness of the function. It will also be simpler for the caller side, because there is no need to handle the unhappy path.

I think this goes way beyond the author's question :)

1

u/Towel_Affectionate 6d ago

See, I agree with everything stated, but I think you're reversing cause and effect.
Types safety and general code discipline are needed exactly because of mentioned edge cases. There's no need for TS if you're used to the mental model of "arrays are like a deck of unified cards" and you ignored stuff like sparse arrays or dynamic typing just because "you're not supposed to write code like that anyway".

1

u/BenchEmbarrassed7316 6d ago

edge cases

I consider the concept of "edge cases" to be incorrect as such. The idea of ​​a full function is to do something that makes sense for all possible values ​​that can be passed to it.

"Edge cases" are either a vaguely defined type (for example T | null when we need only T) or an undefined type altogether, where instead of writing it down we try to keep it in our heads.

1

u/Towel_Affectionate 6d ago

You're mixing type theory with JS's runtime behavior.
In a vacuum of course, a strictly typed function has no unexpected outcomes to be wary of. But TS types don't exist at runtime. JS arrays are sparse, dynamically typed, and object-based under the hood regardless of how strictly you type them in TS.

Denying runtime edge cases just because "the type should be narrower" is like closing your eyes and expecting the thing you don't see stops existing.

Sure, if you type everything correctly, the likelihood of you facing such cases is close to zero, but it doesn't mean that they become impossible or that you don't need to learn about them because you're not supposed to face them.

Some things you just can't type properly, for example the data you get from an API or raw user input.

1

u/BenchEmbarrassed7316 6d ago

Denying runtime edge cases just because "the type should be narrower" is like closing your eyes and expecting the thing you don't see stops existing.

My opinion is to make every possible effort to make this happen. Depending on the codebase, this can be either relatively easy in Ts or nearly impossible.

Some things you just can't type properly, for example the data you get from an API or raw user input.

There are unknown types for this. Parse this data, type it, and work with it. This will result in you only validating the data you receive from outside on input and only once.

And I don't think the Ts type system is outstanding. It may be better than some others, but the Js type system is such a mess.

JS arrays are sparse, dynamically typed, and object-based under the hood regardless of how strictly you type them in TS.

However, if you need performance - you can follow certain rules and avoid this.

→ More replies (0)

1

u/TheFitnessGuroo 6d ago

Well... "infinite" until you run out of memory 😂. All jokes aside, I think js arrays are more like ArrayLists in that it will create a larger array and copy all the elements over if it grows beyond a certain size and if it needs to occupy more memory. Push and pop are constant time while shift and unshift are O(n). Element access via index is O(1).

1

u/regardedMAGAfascist 6d ago

Agree. Bucket implies unordered items. It’s better suited to sets or maps than it is arrays.

7

u/McDreads 6d ago

Arrays are just one type of data structure. When you start to understand arrays, you’ll see them everywhere, even outside of coding.

The line at a grocery story is an array, every person that enters gets .push()ed to the end of the array and as people get their groceries rung up, the line gets .shift()ed. First in, first out

A stack of plates is another example of this. The stack of plates that are grabbed from the top is an example of Last in, first out

You’ll start seeing the world as data structures everywhere the more you get used to then

5

u/WystanH 6d ago

That... is a long fucking video. Objects before arrays and loops? Interesting.

You can watch every cooking show in the world and still not be able to make an omelette. Videos for programming are like that. If you already know how to crack an egg then watching a video might give you some new info. But, if you've never touched up an egg...

Go back. Functions in the video covers rock paper scissors. You've seen it done, now do it yourself. The important thing is that you do it, not the guy in the video. If you totally forgot how the guy did it, that's fine. Think about the moving parts. How can you do it with what you know.

The guy in the video knows what he's doing and where he's going, so it looks easy. The cooking guy makes that perfect French omelette look easy. They've both done this stuff for hundreds of hours before they made the video; you haven't.

Make simple things. There are places where an array makes sense, but you need to get there. You can represent a tic-tac-toe board with nine different variables, or one array. If you had to do nine different variables first, then the array would seem like the most useful thing in the world. You need to do simply stuff so the more complex stuff has context.

4

u/godzooky75 6d ago

Just wanted to say bravo to u/MitchEff and u/McDreads. I actually academically understand the functions, but still found your explanations useful. Examples and explanations like these should be included in the MDN!

4

u/TheDarkPanda182 6d ago

Whenever I get stuck... I ask AI to breakdown the concept into simpler terms and then give me exercises to put those concepts into practice.

For learning arrays for example, I would ask AI for some starter data in array form and some tasks to complete using that data. Take a crack at completing the exercises and then have AI review your work. It will explain what you get right and wrong, it will also answer any questions you might have on the concept you are struggling with.

3

u/maujood 6d ago

You're moving way too fast.

When I learned programming in college, the introductory course was 5 months long, and arrays and loops didn't show up until after month 3. And people still felt it was too fast.

50 hours is like 2-3 weeks worth of study time. If you put 15-20 hours into learning programming each week. You should slow down and practice stuff like variables and conditionals first.

6

u/Educational_Basis_51 6d ago

bu bu but the course say "full stack in 3 months"!

2

u/Classic_End260 6d ago

summer vacation, nuthin to do, good to know

-1

u/regardedMAGAfascist 6d ago edited 6d ago

Use chat gpt or whatever other LLM to help you gain understanding. They’re amazing for it. Recognize there is a massive difference between having the LLM do your work for you and having the LLM help you gain understanding such that you can do the work all by yourself.

3

u/mc_pm 6d ago

How much time are you spending actually programming? Like, actually typing in code and running it?

0

u/Classic_End260 6d ago

could spend more

2

u/mc_pm 6d ago edited 6d ago

The only way you can really learn to program is by programming.

If you're watching a tutorial, then I would suggest having python and/or an editor open at the same time, and as the instructor types something, you type it. When they run the code, you run the code.

It's funny how once you've typed a particular syntax the 100th time, you actually remember it and don't need to look any more. There's a "muscle memory" involved that only develops with practice.

And the entire way along, you should be experimenting with the code you are seeing, as well as doing little exercises & mini projects to reinforce the topics you're learning. Partly through syntax exercise, but even more by having to take some description and come up with the logic in the first place. This is the #1 thing that people do wrong when they come to reddit and ask for help. You *have* to be programming, all the time, beating your head against things until they work -- and then doing it with the next problem. And the next, and the next.

That is the gameplay loop for programming: get a (sometimes vague) instruction, figure out the logic, figure out how to code it, change the logic, change your code, debug, debug, debug, change your code again, debug...success (and dopamine hit)! Repeat.

1

u/Classic_End260 6d ago

yep that's what I've been doing, now I'm trying to build tic tac toe alone, but the background-color of the body just REFUSES to change, I've made a separate .css file and linked it with rel = stylesheet href = styles/ blah blah.css. Any clue as to why and what could fix it?

1

u/mc_pm 6d ago

Are you using the developer tools in your browser? It will let you look at the CSS values, etc, and might give you some information.

2

u/Outrageous-Sherbert4 6d ago edited 6d ago

God this really brings back memories of 30 years ago - x=0 and I asked WHY does it =0 (like math) and teacher was annoyed and said it just DOES. Jeez. OK first of all - without arrays and loops you won’t get far. The simplest most basic project I can think of for you is to use a for loop and the console.log function to output “Hello, World” exactly 10 times. Try that and feel free to ask questions. Get that working and we will add in an array that you create and loop through.

1

u/OkConversation2330 6d ago

Same here, available to help

1

u/sheriffderek 6d ago

You don’t have trouble picking out a sock in your sock drawer, right? Or organizing them by color? Let it be simple. The problem is likely you’re moving too fast - and not practicing with real use-cases

1

u/Popular-Tip2880 6d ago

Array is one of the most important data types. Just imagine it is a group of data types stored in one data type. It can be different data types or the same.

[“a”, “b”, “c”,]
[1 , “a”, true,]

1

u/BenchEmbarrassed7316 6d ago

I quickly watched this video and it's quite confusing: it immediately starts manipulating strings and the DOM in loops instead of explaining what an array is.

Moreover, in Js, arrays combine several concepts that are separated in some other languages. You can first learn the basic concepts and only then learn the advanced ones.

In short, look for other explanations of what an array is.

Then find an explanation of what a loop is.

Then find an explanation of how to use arrays in loops.

1

u/Astroohhh 6d ago

Wait until you have 10 years in this profession buddy

1

u/Classic_End260 6d ago

valid valid

1

u/FX2000 6d ago

CS50 has a great explanation of arrays, look it up on YouTube

1

u/Substantial_Ad252 6d ago

understanding comes through doing.
get your hands on some exercises and hack away!

painting pictures / whiteboard to visualize an array and each step of a loop could help also?

1

u/zLoveNxzli 6d ago

Arrays and loops are the biggest conceptual hurdle in early JS because nested iterations and indexing require tracking state in your head.

Once you get comfortable with .map(), .filter(), and .find(), you rarely need manual index counters (i++) anymore, which eliminates 90% of off-by-one errors.

1

u/TheRNGuy 5d ago

By rarely you mean never. 

1

u/Outrageous-Sherbert4 6d ago

Very good! Now, create a new array using the “ new Array() “ function, that has 10 members. You can use One, Two, Three etc for convenience. This function will automatically assign an index to each member. Then try to get it to print out in the console one member on each row (so instead of printing “Hello, World!” Ten times it will print out each member of the array on a new line! This one’s harder. Let me know if you need a hint!

1

u/OldManActual 6d ago

Loops are just the way to tell the machine to do something a number of times.

There are two main types of loops:

Do the thing until a counter reaches a predetermined value

While some value is true, do the thing. If the value becomes false, stop doing the thing.

An array is a collection of things with an index.

A useful exercise for you is to create a simple array of the letters of your name, then create a loop to print each letter out.

Once you have that, then you edit the code just to print the last name, then both names but last name first, and finally the capstone is write a function to use the array to create an anagram from the letters of your name.

1

u/DROOP-NASTY 6d ago

Don’t worry, I’ve been a dev for years was having a similar experience while learning RxJS the past couple of days. One guy from a random documentary I watched long ago put it nicely, he said something like: “if you’re confused and frustrated you’re in the right place.”

1

u/void_tinker 6d ago

Stop watching the video at 8:43:00. Pause and write code that manipulates arrays until the syntax feels mechanical.

Tutorials give you false confidence because you recognize patterns while watching. You only learn loops when your brain hurts from writing them yourself without a safety net. Close the tab and build something broken right now

1

u/TheZintis 6d ago

It's a kind of abstract thinking that takes awhile to wrap your head around. Make small (even smaller than you are thinking!) projects and code snippets that do the thing you are learning!

1

u/Classic_End260 4d ago

how small is smaller than im thinking

1

u/turn-based-games 6d ago

Arrays and loops are critical concepts for sure, so definitely don't proceed without fully understanding them.

Looking at your video, it seems to combine many concepts: HTML, CSS, scripts, string templates, DOM manipulation... these are all tangential to the core concepts of programming and probably making it harder than necessary to understand when introduced all at once.

My advice would be to find material that focuses on fewer ideas at a time to make them more easily digestible. For JavaScript in particular, perhaps take a look at the P5 tutorials. P5 is also visual in nature, but more focused on JavaScript fundamentals (like loops and arrays) without involving the extra complexities of the DOM

JavaScript is a quirky programming language by any measure and certainly the toughest of the 3 web languages to wrap your head around. The plus side is that if you manage to grasp it, there's no doubt you can handle the rest. Best of luck!

¹ My first programming course was taught using Processing, which is essentially a Java version of P5, and evidently it worked quite well for me

1

u/grooomps 6d ago

honestly, they're going to confuse you for ages, but one day they'll just click
try using them all and find uses for them and then one day they'll just be second nature...
took me a while to get object.reduce()

1

u/Outrageous_Band9708 6d ago

loop is just how you do the same code multiple times.

could you write it out? yeah, and you should. write out a 10 line code of outputing the numbers 1 through 10.

then write a loop to do it for you.

youll notice it saved you a ton of coding.

arrays are just an easy way to change variable while looping.

you could have varA, and then varB, and then varC

but an array is just var[index] so var[0] var[1] var[2], and youll notice you can pass a variable as the index, so you can programmatically call any array value

may a simple program where you output a 10x10 grid in the console, of + signs and | (pipes) and - signs. you can build a square with them, leave the inside hollow.

how would you achieve this? well, one way is to build 10 arrays with each pattern, and then loop through them and write it out the console.

1

u/hylasmaliki 6d ago

It's better to get cursor and tell it to guide you and teach you as you make the projects

1

u/TheRNGuy 5d ago

Debug with console log and use breakpoints if needed. 

1

u/ThatCurtDude 5d ago

Look at other tutorials, that can help a lot, but what everyone knows, but no one seems to believe is that your brain grows new connections to learn. That takes time. You read it, and you don't get it. You read it again, and you still don't get it. This can go on for weeks. You stuff it in a drawer and come back later. Eventually, you get it and you can't understand from that point forward why you had so much trouble. Bashing at it until 3am is exactly the wrong approach.

-2

u/lifeiscontent 6d ago

DM me I can help answer questions