-
@ Marth
2024-10-04 21:50:01JavaScript for Cats: Lesson 2 - Loops and Arrays
Introduction
Welcome back, curious cats! In this lesson, we'll explore two fundamental concepts in JavaScript: loops and arrays. These tools will help you become an efficient and lazy programmer – every cat's dream!
Loops: The Art of Repetition
Loops allow you to perform the same action multiple times without having to write the same code over and over. It's like having a automatic laser pointer that keeps moving without you having to lift a paw!
Here's a simple loop using the
times
method from Underscore.js:javascript function logANumber(someNumber) { console.log(someNumber) } _.times(10, logANumber)
This code will print numbers from 0 to 9. It's much easier than writing
console.log()
ten times!Arrays: Organizing Your Cat Friends
An array is like a list where you can keep multiple items. Imagine you're keeping track of all your cat buddies:
javascript var myCatFriends = ["Fluffy", "Whiskers", "Mittens"]
You can access individual items in the array using their position (index). Remember, in JavaScript, we start counting from 0:
javascript console.log(myCatFriends[0]) // Outputs: "Fluffy" console.log(myCatFriends[1]) // Outputs: "Whiskers"
To add a new friend to your list, use the
push
method:javascript myCatFriends.push("Socks")
To check how many friends you have, use the
length
property:javascript console.log(myCatFriends.length) // Outputs: 4
Combining Loops and Arrays
Now, let's use a loop to greet all your cat friends:
```javascript function greetCat(catName) { console.log("Hello, " + catName + "!") }
myCatFriends.forEach(greetCat) ```
This will greet each cat in your
myCatFriends
array.Objects: Storing More Information
Sometimes you want to store more information about each cat friend. That's where objects come in handy:
```javascript var fluffy = { name: "Fluffy", favoriteFood: "Tuna", age: 3 }
console.log(fluffy.name + " loves " + fluffy.favoriteFood) ```
Objects allow you to store multiple pieces of related information together.
Conclusion
Great job! You've learned about loops, arrays, and objects – powerful tools in any cat programmer's toolkit. In our next lesson, we'll explore more advanced concepts like callbacks and asynchronous programming. Until then, practice creating arrays of your favorite toys and looping through them!