diff --git a/1-getting-started-lessons/1-intro-to-programming-languages/README.md b/1-getting-started-lessons/1-intro-to-programming-languages/README.md index 38cae15d..4c89030e 100644 --- a/1-getting-started-lessons/1-intro-to-programming-languages/README.md +++ b/1-getting-started-lessons/1-intro-to-programming-languages/README.md @@ -1,47 +1,60 @@ # Introduction to Programming Languages and Modern Developer Tools -Welcome to the exciting world of programming! This lesson will introduce you to the fundamental concepts that power every website, app, and digital experience you use daily. You'll discover what programming languages are, how they work, and why they're the building blocks of our digital world. +Hey there, future developer! 👋 Can I tell you something that still gives me chills every single day? You're about to discover that programming isn't just about computers – it's about having actual superpowers to bring your wildest ideas to life! -Programming might seem mysterious at first, but think of it as learning a new language – one that lets you communicate with computers and bring your creative ideas to life. Whether you want to build websites, create mobile apps, or automate everyday tasks, understanding programming languages is your first step toward digital creativity and problem-solving. +You know that moment when you're using your favorite app and everything just clicks perfectly? When you tap a button and something absolutely magical happens that makes you go "wow, how did they DO that?" Well, someone just like you – probably sitting in their favorite coffee shop at 2 AM with their third espresso – wrote the code that created that magic. And here's what's going to blow your mind: by the end of this lesson, you'll not only understand how they did it, but you'll be itching to try it yourself! -In this lesson, you'll explore the essential tools that modern web developers use every day. From code editors that help you write clean, efficient code to browsers that let you test and debug your creations, you'll get hands-on experience with the same professional tools used by developers at top tech companies worldwide. +Look, I totally get it if programming feels intimidating right now. When I first started, I honestly thought you needed to be some kind of math genius or have been coding since you were five years old. But here's what completely changed my perspective: programming is exactly like learning to have conversations in a new language. You start with "hello" and "thank you," then work up to ordering coffee, and before you know it, you're having deep philosophical discussions! Except in this case, you're having conversations with computers, and honestly? They're the most patient conversation partners you'll ever have – they never judge your mistakes and they're always excited to try again! + +Today, we're going to explore the incredible tools that make modern web development not just possible, but seriously addictive. I'm talking about the exact same editors, browsers, and workflows that developers at Netflix, Spotify, and your favorite indie app studio use every single day. And here's the part that's going to make you do a happy dance: most of these professional-grade, industry-standard tools are completely free! ![Intro Programming](../../sketchnotes/webdev101-programming.png) > Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac) -## Pre-Lecture Quiz -[Pre-lecture quiz](https://forms.office.com/r/dru4TE0U9n?origin=lprLink) +## Let's See What You Already Know! + +Before we jump into the fun stuff, I'm curious – what do you already know about this programming world? And listen, if you're looking at these questions thinking "I literally have zero clue about any of this," that's not just okay, it's perfect! That means you're in exactly the right place. Think of this quiz like stretching before a workout – we're just warming up those brain muscles! + +[Take the pre-lesson quiz](https://forms.office.com/r/dru4TE0U9n?origin=lprLink) -## What You'll Learn +## The Adventure We're About to Go On Together -In this comprehensive introduction, you'll discover: +Okay, I am genuinely bouncing with excitement about what we're going to explore today! Seriously, I wish I could see your face when some of these concepts click. Here's the incredible journey we're taking together: -- **What programming is and why it matters** – Understanding the role of programming in creating digital solutions -- **Types of programming languages and their uses** – Exploring the landscape of languages from JavaScript to Python -- **Basic elements of a program** – Learning the fundamental building blocks that make code work -- **Modern software and tooling for professional developers** – Getting hands-on with the same tools used in the industry +- **What programming actually is (and why it's the coolest thing ever!)** – We're going to discover how code is literally the invisible magic powering everything around you, from that alarm that somehow knows it's Monday morning to the algorithm that perfectly curates your Netflix recommendations +- **Programming languages and their amazing personalities** – Imagine walking into a party where each person has completely different superpowers and ways of solving problems. That's what the programming language world is like, and you're going to love meeting them! +- **The fundamental building blocks that make digital magic happen** – Think of these as the ultimate creative LEGO set. Once you understand how these pieces fit together, you'll realize you can literally build anything your imagination dreams up +- **Professional tools that'll make you feel like you just got handed a wizard's wand** – I'm not being dramatic here – these tools will genuinely make you feel like you have superpowers, and the best part? They're the same ones the pros use! -> 💡 **Learning Tip**: Don't worry about memorizing everything! Focus on understanding the concepts – you'll practice and reinforce these ideas throughout the entire curriculum. +> 💡 **Here's the thing**: Don't even think about trying to memorize everything today! Right now, I just want you to feel that spark of excitement about what's possible. The details will stick naturally as we practice together – that's how real learning happens! > You can take this lesson on [Microsoft Learn](https://docs.microsoft.com/learn/modules/web-development-101/introduction-programming/?WT.mc_id=academic-77807-sagibbon)! -## What is Programming? +## So What Exactly *Is* Programming? + +Alright, let's tackle the million-dollar question: what is programming, really? + +I'll give you a story that completely changed how I think about this. Last week, I was trying to explain to my mom how to use our new smart TV remote. I caught myself saying things like "Press the red button, but not the big red button, the small red button on the left... no, your other left... okay, now hold it for two seconds, not one, not three..." Sound familiar? 😅 -Programming (also known as coding or software development) is the process of creating instructions that tell a computer, smartphone, or any digital device exactly what to do. Think of it like writing a very detailed recipe – except instead of making cookies, you're creating websites, games, mobile apps, or even smart home controls. +That's programming! It's the art of giving incredibly detailed, step-by-step instructions to something that's very powerful but needs everything spelled out perfectly. Except instead of explaining to your mom (who can ask "which red button?!"), you're explaining to a computer (which just does exactly what you say, even if what you said isn't quite what you meant). -These instructions are written in special languages called **programming languages**, which act as a bridge between human thinking and computer processing. While computers only understand binary code (1s and 0s), programming languages let us write instructions in a way that's much more readable and logical for humans. +Here's what blew my mind when I first learned this: computers are actually pretty simple at their core. They literally only understand two things – 1 and 0, which is basically just "yes" and "no" or "on" and "off." That's it! But here's where it gets magical – we don't have to speak in 1s and 0s like we're in The Matrix. That's where **programming languages** come to the rescue. They're like having the world's best translator who takes your perfectly normal human thoughts and converts them into computer language. -Every digital experience you interact with started as someone's code: the social media app you scroll through, the GPS that guides your drive, even the simple calculator on your phone. When you learn to program, you're learning to create these digital solutions that can solve real problems and make life easier for millions of people. +And here's what still gives me actual chills every morning when I wake up: literally *everything* digital in your life started with someone just like you, probably sitting in their pajamas with a cup of coffee, typing code on their laptop. That Instagram filter that makes you look flawless? Someone coded that. The recommendation that led you to your new favorite song? A developer built that algorithm. The app that helps you split dinner bills with friends? Yep, someone thought "this is annoying, I bet I could fix this" and then... they did! -✅ **Quick Research Challenge**: Who is considered to have been the world's first computer programmer? Take a moment to look this up – the answer might surprise you! +When you learn to program, you're not just picking up a new skill – you're becoming part of this incredible community of problem-solvers who spend their days thinking, "What if I could build something that makes someone's day just a little bit better?" Honestly, is there anything cooler than that? -## Programming Languages +✅ **Fun Fact Hunt**: Here's something super cool to look up when you have a spare moment – who do you think was the world's first computer programmer? I'll give you a hint: it might not be who you're expecting! The story behind this person is absolutely fascinating and shows that programming has always been about creative problem-solving and thinking outside the box. -Just as humans speak different languages like English, Spanish, or Mandarin, computers can understand different programming languages. Each programming language has its own syntax (grammar rules) and is designed for specific types of tasks, making some languages better suited for certain jobs than others. +## Programming Languages Are Like Different Flavors of Magic -Programming languages serve as translators between human ideas and computer actions. They allow developers to write instructions that are both human-readable and computer-executable. When you write code in a programming language, special software converts your instructions into the binary code that computers actually understand. +Okay, this is going to sound weird, but stick with me – programming languages are a lot like different types of music. Think about it: you've got jazz, which is smooth and improvisational, rock that's powerful and straightforward, classical that's elegant and structured, and hip-hop that's creative and expressive. Each style has its own vibe, its own community of passionate fans, and each one is perfect for different moods and occasions. + +Programming languages work exactly the same way! You wouldn't use the same language to build a fun mobile game that you'd use to crunch massive amounts of climate data, just like you wouldn't play death metal at a yoga class (well, most yoga classes anyway! 😄). + +But here's what absolutely blows my mind every time I think about it: these languages are like having the most patient, brilliant interpreter in the world sitting right next to you. You can express your ideas in a way that feels natural to your human brain, and they handle all the incredibly complex work of translating that into the 1s and 0s that computers actually speak. It's like having a friend who's perfectly fluent in both "human creativity" and "computer logic" – and they never get tired, never need coffee breaks, and never judge you for asking the same question twice! ### Popular Programming Languages and Their Uses @@ -55,17 +68,28 @@ Programming languages serve as translators between human ideas and computer acti ### High-Level vs. Low-Level Languages -Programming languages exist on a spectrum from **low-level** (closer to machine code) to **high-level** (closer to human language): +Okay, this was honestly the concept that broke my brain when I first started learning, so I'm going to share the analogy that finally made it click for me – and I really hope it helps you too! + +Imagine you're visiting a country where you don't speak the language, and you desperately need to find the nearest bathroom (we've all been there, right? 😅): + +- **Low-level programming** is like learning the local dialect so well that you can chat with the grandmother selling fruit on the corner using cultural references, local slang, and inside jokes that only someone who grew up there would understand. Super impressive and incredibly efficient... if you happen to be fluent! But pretty overwhelming when you're just trying to find a bathroom. -- **Low-level languages** (like Assembly or C) require fewer translation steps but are harder for humans to read and write -- **High-level languages** (like JavaScript, Python, or C#) are more readable and have larger communities, making them ideal for most modern development +- **High-level programming** is like having that amazing local friend who just gets you. You can say "I really need to find a restroom" in plain English, and they handle all the cultural translation and give you directions in a way that makes perfect sense to your non-local brain. -> 💡 **Think of it this way**: Low-level languages are like speaking directly to the computer in its native dialect, while high-level languages are like having a skilled interpreter who translates your everyday language into computer-speak. +In programming terms: +- **Low-level languages** (like Assembly or C) let you have incredibly detailed conversations with the computer's actual hardware, but you need to think like a machine, which is... well, let's just say it's a pretty big mental shift! +- **High-level languages** (like JavaScript, Python, or C#) let you think like a human while they handle all the machine-speak behind the scenes. Plus, they have these incredibly welcoming communities full of people who remember what it was like to be new and genuinely want to help! +Guess which ones I'm going to suggest you start with? 😉 High-level languages are like having training wheels that you never actually want to take off because they make the whole experience so much more enjoyable! -### Comparing Programming Languages in Action -To illustrate the difference between high-level and low-level languages, let's look at the same task written in two different ways. Both code examples below generate the famous Fibonacci sequence (where each number is the sum of the two preceding ones: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...). +### Let Me Show You Why High-Level Languages Are So Much Friendlier + +Alright, I'm about to show you something that perfectly demonstrates why I fell in love with high-level languages, but first – I need you to promise me something. When you see that first code example, don't panic! It's supposed to look intimidating. That's exactly the point I'm making! + +We're going to look at the exact same task written in two completely different styles. Both create what's called the Fibonacci sequence – it's this beautiful mathematical pattern where each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13... (Fun fact: you'll find this pattern literally everywhere in nature – sunflower seed spirals, pinecone patterns, even the way galaxies form!) + +Ready to see the difference? Let's go! **High-level language (JavaScript) – Human-friendly:** @@ -160,16 +184,20 @@ Notice how the JavaScript version reads almost like English instructions, while - **Structure**: JavaScript's logical flow matches how humans think about problems step-by-step - **Maintenance**: Updating the JavaScript version for different requirements is straightforward and clear -✅ **A Fibonacci sequence** is [defined](https://en.wikipedia.org/wiki/Fibonacci_number) as a set of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. This mathematical pattern appears frequently in nature, from flower petals to spiral shells! +✅ **About the Fibonacci sequence**: This absolutely gorgeous number pattern (where each number equals the sum of the two before it: 0, 1, 1, 2, 3, 5, 8...) shows up literally *everywhere* in nature! You'll find it in sunflower spirals, pinecone patterns, the way nautilus shells curve, and even in how tree branches grow. It's pretty mind-blowing how math and code can help us understand and recreate the patterns that nature uses to create beauty! + + +## The Building Blocks That Make the Magic Happen +Alright, now that you've seen what programming languages look like in action, let's break down the fundamental pieces that make up literally every program ever written. Think of these as the essential ingredients in your favorite recipe – once you understand what each one does, you'll be able to read and write code in pretty much any language! -## Elements of a Program +This is kind of like learning the grammar of programming. Remember back in school when you learned about nouns, verbs, and how to put sentences together? Programming has its own version of grammar, and honestly, it's way more logical and forgiving than English grammar ever was! 😄 -Now that you understand what programming languages are, let's explore the fundamental building blocks that make up any program. Think of these elements as the grammar and vocabulary of programming – once you understand these concepts, you'll be able to read and write code in any language. +### Statements: The Step-by-Step Instructions -### Statements: The Basic Instructions +Let's start with **statements** – these are like individual sentences in a conversation with your computer. Each statement tells the computer to do one specific thing, kind of like giving directions: "Turn left here," "Stop at the red light," "Park in that spot." -A **statement** is a single instruction in a program, like a sentence in human language. Each statement tells the computer to perform one specific action. Just as sentences end with periods, statements have specific ways to indicate where one instruction ends and the next begins (this varies by programming language). +What I love about statements is how readable they usually are. Check this out: ```javascript // Basic statements that perform single actions @@ -193,9 +221,15 @@ document.body.style.backgroundColor = "lightblue"; - **Modify** the webpage's title that appears in the browser tab - **Change** the background color of the entire page body -### Variables: Storing Information +### Variables: Your Program's Memory System -**Variables** are like labeled containers that hold information your program needs to remember. Just as you might write a grocery list on paper and refer back to it, variables let programs store data and use it later. Variables have unique names and their contents can change as the program runs. +Okay, **variables** are honestly one of my absolute favorite concepts to teach because they're so much like things you already use every single day! + +Think about your phone's contact list for a second. You don't memorize everyone's phone number – instead, you save "Mom," "Best Friend," or "Pizza Place That Delivers Until 2 AM" and let your phone remember the actual numbers. Variables work exactly the same way! They're like labeled containers where your program can store information and retrieve it later using a name that actually makes sense. + +Here's what's really cool: variables can change as your program runs (hence the name "variable" – see what they did there?). Just like you might update that pizza place contact when you discover somewhere even better, variables can be updated as your program learns new information or as situations change! + +Let me show you how beautifully simple this can be: ```javascript // Step 1: Creating basic variables @@ -252,9 +286,15 @@ console.log(`${location} humidity: ${humidity}%`); - **Create** new variables automatically with the same names as object keys - **Simplify** code by avoiding repetitive dot notation -### Control Flow: Making Decisions +### Control Flow: Teaching Your Program to Think + +Okay, this is where programming gets absolutely mind-blowing! **Control flow** is basically teaching your program how to make smart decisions, exactly like you do every single day without even thinking about it. -Programs often need to make decisions based on different situations. **Control flow statements** (like `if...else`) allow programs to choose different paths, making them smart and responsive to changing conditions. +Picture this: this morning you probably went through something like "If it's raining, I'll grab an umbrella. If it's cold, I'll wear a jacket. If I'm running late, I'll skip breakfast and grab coffee on the way." Your brain naturally follows this if-then logic dozens of times every day! + +This is what makes programs feel intelligent and alive instead of just following some boring, predictable script. They can actually look at a situation, evaluate what's happening, and respond appropriately. It's like giving your program a brain that can adapt and make choices! + +Want to see how beautifully this works? Let me show you: ```javascript // Step 1: Basic conditional logic @@ -333,25 +373,31 @@ switch (dayOfWeek) { - **Include** a `default` case to handle unexpected values - **Use** `break` statements to prevent code from continuing to the next case -> 💡 **Real-world analogy**: Think of control flow like a GPS giving you directions. It might say "If there's traffic on Main Street, take the highway instead." Programs use the same type of conditional logic to respond to different situations. +> 💡 **Real-world analogy**: Think of control flow like having the world's most patient GPS giving you directions. It might say "If there's traffic on Main Street, take the highway instead. If construction is blocking the highway, try the scenic route." Programs use exactly the same type of conditional logic to respond intelligently to different situations and always give users the best possible experience. -✅ **Coming up**: You'll dive deeper into these concepts and learn how to use them effectively in the upcoming lessons. Don't worry about memorizing everything now – focus on understanding the big picture! +✅ **What's coming up next**: We're going to have an absolute blast diving deeper into these concepts as we continue this incredible journey together! Right now, just focus on feeling that excitement about all the amazing possibilities ahead of you. The specific skills and techniques will stick naturally as we practice together – I promise this is going to be so much more fun than you might expect! ## Tools of the Trade -Just as a carpenter needs quality tools to build beautiful furniture, web developers rely on specialized software and workflows to create amazing digital experiences. In this section, you'll discover the essential tools that professional developers use every day – and the best part is, many of these powerful tools are completely free! +Alright, this is honestly where I get so excited I can barely contain myself! 🚀 We're about to talk about the incredible tools that are going to make you feel like you just got handed the keys to a digital spaceship. + +You know how a chef has those perfectly balanced knives that feel like extensions of their hands? Or how a musician has that one guitar that seems to sing the moment they touch it? Well, developers have our own version of these magical tools, and here's what's going to absolutely blow your mind – most of them are completely free! + +I'm practically bouncing in my chair thinking about sharing these with you because they've completely revolutionized how we build software. We're talking about AI-powered coding assistants that can help write your code (I'm not even kidding!), cloud environments where you can build entire applications from literally anywhere with Wi-Fi, and debugging tools so sophisticated they're like having X-ray vision for your programs. + +And here's the part that still gives me chills: these aren't "beginner tools" that you'll outgrow. These are the exact same professional-grade tools that developers at Google, Netflix, and that indie app studio you love are using right this very moment. You're going to feel like such a pro using them! -The modern web development landscape has been transformed by innovative tools like AI-powered code assistants (such as GitHub Copilot), cloud-based development environments, and sophisticated debugging tools. These technologies have made it easier than ever to learn programming and build professional-quality applications. -As you progress in your web development journey, you'll discover that having the right tools can dramatically improve your productivity, help you catch errors before they become problems, and make coding more enjoyable and efficient. +### Code Editors and IDEs: Your New Digital Best Friends +Let's talk about code editors – these are seriously about to become your new favorite places to hang out! Think of them as your personal coding sanctuary where you'll spend most of your time crafting and perfecting your digital creations. -### Code Editors and IDEs: Your Digital Workshop +But here's what's absolutely magical about modern editors: they're not just fancy text editors. They're like having the most brilliant, supportive coding mentor sitting right next to you 24/7. They catch your typos before you even notice them, suggest improvements that make you look like a genius, help you understand what every piece of code does, and some of them can even predict what you're about to type and offer to finish your thoughts! -Think of a code editor as your digital workshop – it's where you'll spend most of your time crafting, testing, and perfecting your code. Modern editors and Integrated Development Environments (IDEs) are far more than simple text editors; they're intelligent assistants that help you write better code faster. +I remember when I first discovered auto-completion – I literally felt like I was living in the future. You start typing something, and your editor goes, "Hey, were you thinking of this function that does exactly what you need?" It's like having a mind reader as your coding buddy! -**What makes modern editors so powerful?** +**What makes these editors so incredible?** Modern code editors offer an impressive array of features designed to boost your productivity: @@ -390,11 +436,15 @@ Modern code editors offer an impressive array of features designed to boost your > 💡 **Getting Started Tip**: Start with Visual Studio Code – it's free, widely used in the industry, and has an enormous community creating helpful tutorials and extensions. -### Web Browsers: Your Testing Laboratory +### Web Browsers: Your Secret Development Laboratory -Web browsers are much more than tools for browsing the internet – they're sophisticated development environments that help you build, test, and optimize web applications. Every modern browser includes powerful developer tools (DevTools) that provide deep insights into how your code performs. +Okay, prepare to have your mind completely blown! You know how you've been using browsers to scroll through social media and watch videos? Well, it turns out they've been hiding this incredible secret developer laboratory this entire time, just waiting for you to discover it! -**Why browsers are essential for web development:** +Every single time you right-click on a webpage and select "Inspect Element," you're opening up a hidden world of developer tools that are honestly more powerful than some expensive software I used to pay hundreds of dollars for. It's like discovering that your regular old kitchen has been concealing a professional chef's laboratory behind a secret panel! + +The first time someone showed me browser DevTools, I spent like three hours just clicking around and going "WAIT, IT CAN DO THAT TOO?!" You can literally edit any website in real-time, see exactly how fast everything loads, test how your site looks on different devices, and even debug JavaScript like a total pro. It's absolutely mind-blowing! + +**Here's why browsers are your secret weapon:** When you create a website or web application, you need to see how it looks and behaves in the real world. Browsers not only display your work but also provide detailed feedback about performance, accessibility, and potential issues. @@ -419,11 +469,15 @@ Modern browsers include comprehensive development suites: > ⚠️ **Important Testing Tip**: Always test your websites in multiple browsers! What works perfectly in Chrome might look different in Safari or Firefox. Professional developers test across all major browsers to ensure consistent user experiences. -### Command Line Tools: The Power User's Gateway +### Command Line Tools: Your Gateway to Developer Superpowers + +Alright, let's have a completely honest moment here about the command line, because I want you to hear this from someone who truly gets it. When I first saw it – just this scary black screen with blinking text – I literally thought, "Nope, absolutely not! This looks like something from a 1980s hacker movie, and I am definitely not smart enough for this!" 😅 + +But here's what I wish someone had told me back then, and what I'm telling you right now: the command line isn't scary – it's actually like having a direct conversation with your computer. Think of it like the difference between ordering food through a fancy app with pictures and menus (which is nice and easy) versus walking into your favorite local restaurant where the chef knows exactly what you like and can whip up something perfect just by you saying "surprise me with something amazing." -The command line (also called terminal or shell) might look intimidating at first – it's just a black screen with text! But don't let its simple appearance fool you. The command line is one of the most powerful tools in a developer's toolkit, allowing you to perform complex tasks with simple text commands. +The command line is where developers go to feel like absolute wizards. You type a few seemingly magical words (okay, they're just commands, but they feel magical!), hit enter, and BOOM – you've created entire project structures, installed powerful tools from around the world, or deployed your app to the internet for millions of people to see. Once you get your first taste of that power, it's honestly pretty addictive! -**Why developers love the command line:** +**Why the command line will become your favorite tool:** While graphical interfaces are great for many tasks, the command line excels at automation, precision, and speed. Many development tools work primarily through command line interfaces, and learning to use them efficiently can dramatically improve your productivity. @@ -496,11 +550,15 @@ npx vite > 🎯 **Learning Path**: Start with basic commands like `cd` (change directory), `ls` or `dir` (list files), and `mkdir` (create folder). Practice with modern workflow commands like `npm install`, `git status`, and `code .` (opens current directory in VS Code). As you become more comfortable, you'll naturally pick up more advanced commands and automation techniques. -### Documentation: Your Learning Compass +### Documentation: Your Always-Available Learning Mentor -Documentation is like having a knowledgeable mentor available 24/7. When you encounter new concepts, need to understand how a tool works, or want to explore advanced features, high-quality documentation becomes your roadmap to success. +Okay, let me share a little secret that's going to make you feel so much better about being a beginner: even the most experienced developers spend a huge chunk of their time reading documentation. And that's not because they don't know what they're doing – it's actually a sign of wisdom! -**Why documentation matters:** +Think of documentation as having access to the world's most patient, knowledgeable teachers who are available 24/7. Stuck on a problem at 2 AM? Documentation is there with a warm virtual hug and exactly the answer you need. Want to learn about some cool new feature that everyone's talking about? Documentation has your back with step-by-step examples. Trying to understand why something works the way it does? You guessed it – documentation is ready to explain it in a way that finally makes it click! + +Here's something that completely changed my perspective: the web development world moves incredibly fast, and nobody (I mean absolutely nobody!) keeps everything memorized. I've watched senior developers with 15+ years of experience look up basic syntax, and you know what? That's not embarrassing – that's smart! It's not about having a perfect memory; it's about knowing where to find reliable answers quickly and understanding how to apply them. + +**Here's where the real magic happens:** Professional developers spend a significant portion of their time reading documentation – not because they don't know what they're doing, but because the web development landscape evolves so rapidly that staying current requires continuous learning. Great documentation helps you understand not just *how* to use something, but *why* and *when* to use it. @@ -530,7 +588,7 @@ Professional developers spend a significant portion of their time reading docume > 📚 **Study Strategy**: Don't try to memorize documentation – instead, learn how to navigate it efficiently. Bookmark frequently-used references and practice using the search functions to find specific information quickly. -✅ **Reflection Exercise**: Think about how web development tools might differ from web design tools. Consider how accessibility features, responsive design capabilities, and collaborative workflows might vary between the two roles. This comparison will help you understand the broader ecosystem of web creation! +✅ **Food for thought**: Here's something interesting to ponder – how do you think the tools for building websites (development) might be different from tools for designing how they look (design)? It's like the difference between being an architect who designs a beautiful house and the contractor who actually builds it. Both are crucial, but they need different toolboxes! This kind of thinking will really help you see the bigger picture of how websites come to life. ## GitHub Copilot Agent Challenge 🚀 @@ -545,45 +603,53 @@ Use the Agent mode to complete the following challenge: ## 🚀 Challenge -**Explore Programming Language Diversity** +**Alright, detective, ready for your first case?** + +Now that you've got this awesome foundation, I've got an adventure that's going to help you see just how incredibly diverse and fascinating the programming world really is. And listen – this isn't about writing code yet, so no pressure there! Think of yourself as a programming language detective on your very first exciting case! + +**Your mission, should you choose to accept it:** +1. **Become a language explorer**: Pick three programming languages from completely different universes – maybe one that builds websites, one that creates mobile apps, and one that crunches data for scientists. Find examples of the same simple task written in each language. I promise you're going to be absolutely amazed at how different they can look while doing the exact same thing! -Now that you understand the basics of programming languages, dive deeper into their unique characteristics and use cases. Choose three programming languages from different categories (e.g., web development, mobile development, data science, systems programming) and research their distinctive features. +2. **Uncover their origin stories**: What makes each language special? Here's a cool fact – every single programming language was created because someone thought, "You know what? There's got to be a better way to solve this specific problem." Can you figure out what those problems were? Some of these stories are genuinely fascinating! -**Your task:** -1. **Compare syntax styles**: Find the same simple task (like creating a variable or printing "Hello World") written in your chosen languages -2. **Identify unique strengths**: What makes each language special? What problems is it designed to solve? -3. **Explore communities**: Look at the size and activity of each language's developer community -4. **Consider learning paths**: Which language seems most approachable for a beginner, and why? +3. **Meet the communities**: Check out how welcoming and passionate each language's community is. Some have millions of developers sharing knowledge and helping each other, others are smaller but incredibly tight-knit and supportive. You're going to love seeing the different personalities these communities have! -**Bonus challenge**: Try to find examples of major websites, apps, or systems built with each language. You might be surprised by what powers your favorite digital experiences! +4. **Follow your gut feeling**: Which language feels most approachable to you right now? Don't stress about making the "perfect" choice – just listen to your instincts! There's honestly no wrong answer here, and you can always explore others later. -> 💡 **Learning tip**: Don't worry about understanding all the syntax details – focus on recognizing patterns and differences in how each language approaches problem-solving. +**Bonus detective work**: See if you can discover what major websites or apps are built with each language. I guarantee you'll be shocked to learn what powers Instagram, Netflix, or that mobile game you can't stop playing! -## Post-Lecture Quiz -[Post-lecture quiz](https://ff-quizzes.netlify.app/web/) +> 💡 **Remember**: You're not trying to become an expert in any of these languages today. You're just getting to know the neighborhood before you decide where you want to set up shop. Take your time, have fun with it, and let your curiosity guide you! + +## Let's Celebrate What You've Discovered! + +Holy moly, you've absorbed so much incredible information today! I'm genuinely excited to see how much of this amazing journey has stuck with you. And remember – this isn't a test where you need to get everything perfect. This is more like a celebration of all the cool stuff you've learned about this fascinating world you're about to dive into! + +[Take the post-lesson quiz](https://ff-quizzes.netlify.app/web/) ## Review & Self Study -**Deepen Your Understanding** +**Take your time to explore and have fun with it!** + +You've covered a lot of ground today, and that's something to be proud of! Now comes the fun part – exploring the topics that sparked your curiosity. Remember, this isn't homework – it's an adventure! -Take time to explore the concepts you've learned by diving deeper into the tools and languages that interest you most: +**Dive deeper into what excites you:** -**Programming Language Exploration:** -- Visit the official websites of 2-3 programming languages mentioned in this lesson -- Try online coding playgrounds like [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Replit](https://replit.com/) to experiment with simple code -- Read about the history and creators of your favorite programming language – understanding the "why" behind a language's design helps you use it more effectively +**Get hands-on with programming languages:** +- Visit the official websites of 2-3 languages that caught your attention. Each one has its own personality and story! +- Try some online coding playgrounds like [CodePen](https://codepen.io/), [JSFiddle](https://jsfiddle.net/), or [Replit](https://replit.com/). Don't be afraid to experiment – you can't break anything! +- Read about how your favorite language came to be. Seriously, some of these origin stories are fascinating and will help you understand why languages work the way they do. -**Tool Familiarization:** -- Download and install Visual Studio Code (if you haven't already) -- Explore the Extensions marketplace and install a few recommended extensions -- Open your browser's Developer Tools and spend a few minutes exploring the different tabs and features +**Get comfortable with your new tools:** +- Download Visual Studio Code if you haven't already – it's free and you're going to love it! +- Spend a few minutes browsing the Extensions marketplace. It's like an app store for your code editor! +- Open up your browser's Developer Tools and just click around. Don't worry about understanding everything – just get familiar with what's there. -**Community Connection:** -- Follow developer communities on platforms like [Dev.to](https://dev.to/), [Stack Overflow](https://stackoverflow.com/), or [GitHub](https://github.com/) -- Watch beginner-friendly programming videos on YouTube or coding tutorial platforms -- Consider joining local meetups or online communities focused on web development +**Join the community:** +- Follow some developer communities on [Dev.to](https://dev.to/), [Stack Overflow](https://stackoverflow.com/), or [GitHub](https://github.com/). The programming community is incredibly welcoming to newcomers! +- Watch some beginner-friendly coding videos on YouTube. There are so many great creators out there who remember what it's like to be starting out. +- Consider joining local meetups or online communities. Trust me, developers love helping newcomers! -> 🎯 **Remember**: The goal isn't to master everything immediately, but to build familiarity with the landscape of tools and concepts you'll encounter as you continue learning web development. +> 🎯 **Listen, here's what I want you to remember**: You're not expected to become a coding wizard overnight! Right now, you're just getting to know this amazing new world you're about to be part of. Take your time, enjoy the journey, and remember – every single developer you admire was once sitting exactly where you are right now, feeling excited and maybe a little overwhelmed. That's totally normal, and it means you're doing it right! @@ -591,4 +657,4 @@ Take time to explore the concepts you've learned by diving deeper into the tools [Reading the Docs](assignment.md) -> Note: When selecting tools for your assignment, do not choose editors, browsers, or command line tools already listed above. Focus on tools that are current, widely used, and have strong community or official support. +> 💡 **A little nudge for your assignment**: I'd absolutely love to see you explore some tools we haven't covered yet! Skip the editors, browsers, and command line tools we've already talked about – there's this whole incredible universe of amazing development tools out there just waiting to be discovered. Look for ones that are actively maintained and have vibrant, helpful communities (these tend to have the best tutorials and the most supportive people when you inevitably get stuck and need a friendly hand). diff --git a/1-getting-started-lessons/2-github-basics/README.md b/1-getting-started-lessons/2-github-basics/README.md index b6998394..903e3df4 100644 --- a/1-getting-started-lessons/2-github-basics/README.md +++ b/1-getting-started-lessons/2-github-basics/README.md @@ -1,10 +1,12 @@ # Introduction to GitHub -GitHub is one of the most essential platforms in modern web development, serving as the collaborative backbone for millions of developers worldwide. Think of it as a combination of cloud storage for your code and a social network for programmers – it's where developers share their work, collaborate on projects, and contribute to the open-source community that powers much of the internet you use every day. +Hey there, future developer! 👋 Ready to join millions of coders around the world? I'm genuinely excited to introduce you to GitHub – think of it as the social media platform for programmers, except instead of sharing photos of your lunch, we're sharing code and building incredible things together! -In this lesson, you'll discover how GitHub transforms the way developers work together. You'll learn to track changes in your code, collaborate with others seamlessly, and even contribute to projects used by millions of people. This isn't just about storing code online – it's about joining a global community of developers and learning the fundamental workflows that every professional developer uses. +Here's what absolutely blows my mind: every app on your phone, every website you visit, and most of the tools you'll learn to use were built by teams of developers collaborating on platforms just like GitHub. That music app you love? Someone like you contributed to it. That game you can't put down? Yep, probably built with GitHub collaboration. And now YOU'RE going to learn how to be part of that amazing community! -By the end of this lesson, you'll have your own GitHub repository, understand how to manage code changes with Git, and know how to contribute to open-source projects. These skills will serve as your foundation for collaborating with other developers throughout your web development journey. Let's dive in and unlock the power of collaborative coding! +I know this might feel like a lot at first – heck, I remember staring at my first GitHub page thinking "What on earth does any of this mean?" But here's the thing: every single developer started exactly where you are right now. By the end of this lesson, you'll have your very own GitHub repository (think of it as your personal project showcase in the cloud), and you'll know how to save your work, share it with others, and even contribute to projects that millions of people use. + +We're going to take this journey together, one step at a time. No rushing, no pressure – just you, me, and some really cool tools that are about to become your new best friends! ![Intro to GitHub](../../sketchnotes/webdev101-github.png) > Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac) @@ -14,9 +16,9 @@ By the end of this lesson, you'll have your own GitHub repository, understand ho ## Introduction -Before we dive into hands-on GitHub activities, let's establish the foundation you'll need for success. Understanding the key concepts and ensuring your development environment is properly configured will make your GitHub journey much smoother. +Before we dive into the really exciting stuff, let's get your computer ready for some GitHub magic! Think of this like organizing your art supplies before creating a masterpiece – having the right tools ready makes everything so much smoother and way more fun. -In this section, we'll cover the essential knowledge and tools that every developer needs when working with GitHub. Don't worry if some concepts seem unfamiliar at first – we'll guide you through each step and explain why these tools are so valuable for web developers. +I'm going to walk you through each setup step personally, and I promise it's not nearly as intimidating as it might look at first glance. If something doesn't click right away, that's completely normal! I remember setting up my first development environment and feeling like I was trying to read ancient hieroglyphics. Every single developer has been exactly where you are right now, wondering if they're doing it right. Spoiler alert: if you're here learning, you're already doing it right! 🌟 In this lesson, we'll cover: @@ -26,14 +28,14 @@ In this lesson, we'll cover: ### Prerequisites -Setting up your development environment properly is crucial for a smooth GitHub experience. Think of this as preparing your toolkit before starting a project – having the right tools configured correctly will save you time and frustration later. +Let's get your computer ready for some GitHub magic! Don't worry – this setup is something you only need to do once, and then you'll be all set for your entire coding journey. -Let's ensure you have everything you need to start collaborating with Git and GitHub effectively. +Alright, let's start with the foundation! First, we need to check if Git is already hanging out on your computer. Git is basically like having a super-smart assistant that remembers every single change you make to your code – way better than frantically hitting Ctrl+S every two seconds (we've all been there!). -Before you begin, you'll need to check if Git is installed. In the terminal type: +Let's see if Git is already installed by typing this magic command in your terminal: `git --version` -If Git is not installed, [download Git](https://git-scm.com/downloads). Then, setup your local Git profile in the terminal: +If Git isn't there yet, no worries! Just head over to [download Git](https://git-scm.com/downloads) and grab it. Once you've got it installed, we need to introduce Git to you properly: > 💡 **First Time Setup**: These commands tell Git who you are. This information will be attached to every commit you make, so choose a name and email you're comfortable sharing publicly. @@ -59,11 +61,11 @@ Navigate to [github.com](https://github.com/) and create an account if you haven You'll need both a folder with a code project on your local machine (laptop or PC), and a public repository on GitHub, which will serve as an example for how to contribute to the projects of others. -### Modern Security Practices +### Keeping Your Code Safe -Security in software development isn't just important – it's essential. As you begin your journey with GitHub, establishing secure practices from the start will protect your code, your collaborators, and the projects you contribute to. +Let's talk about security for a moment – but don't worry, we're not going to overwhelm you with scary stuff! Think of these security practices like locking your car or your house. They're simple habits that become second nature and keep your hard work protected. -Modern development workflows prioritize security at every step. Let's explore the key security practices that every developer should know when working with GitHub and Git. +We'll show you the modern, secure ways to work with GitHub right from the start. This way, you'll develop good habits that will serve you well throughout your coding career. When working with GitHub, it's important to follow security best practices: @@ -92,63 +94,70 @@ git remote set-url origin git@github.com:username/repository.git --- -## Code management +## Managing Your Code Like a Pro + +Okay, THIS is where things get really exciting! 🎉 We're about to learn how to track and manage your code like the pros do, and honestly, this is one of my favorite things to teach because it's such a game-changer. -Now that you understand the importance of GitHub and have your environment set up, let's dive into the practical skills you'll use every day as a developer. Code management with Git is like maintaining a detailed journal of your project's evolution – every change, every decision, and every milestone is carefully tracked and preserved. +Picture this: you're writing an amazing story, and you want to keep track of every draft, every brilliant edit, and every "wait, that's genius!" moment along the way. That's exactly what Git does for your code! It's like having the most incredible time-traveling notebook that remembers EVERYTHING – every keystroke, every change, every "oops, that broke everything" moment that you can instantly undo. -Think of Git as your coding time machine. You can see exactly what changed, when it changed, and why it changed. This becomes incredibly valuable when working on complex projects or collaborating with others. +I'll be honest – this might feel overwhelming at first. When I started, I thought "Why can't I just save my files like normal?" But trust me on this: once Git clicks for you (and it will!), you'll have one of those lightbulb moments where you think "How did I EVER code without this?" It's like discovering you can fly when you've been walking everywhere your whole life! Let's say you have a folder locally with some code project and you want to start tracking your progress using git - the version control system. Some people compare using git to writing a love letter to your future self. Reading your commit messages days or weeks or months later you'll be able to recall why you made a decision, or "rollback" a change - that is, when you write good "commit messages". -### Task: Make a repository and commit code +### Task: Create Your First Repository! + +> 🎯 **Your Mission (and I'm so excited for you!)**: We're going to create your very first GitHub repository together! By the time we're done here, you'll have your own little corner of the internet where your code lives, and you'll have made your first "commit" (that's developer speak for saving your work in a really smart way). +> +> This is honestly such a special moment – you're about to officially join the global community of developers! I still remember the thrill of creating my first repo and thinking "Wow, I'm really doing this!" -> 🎯 **Learning Goal**: By the end of this task, you'll have created your first GitHub repository and made your first commit. This is your entry point into the world of version control! +Let's walk through this adventure together, step by step. Take your time with each part – there's no prize for rushing, and I promise every single step will make sense. Remember, every coding superstar you admire was once sitting exactly where you are, about to create their first repository. How cool is that? > Check out video > > [![Git and GitHub basics video](https://img.youtube.com/vi/9R31OUPpxU4/0.jpg)](https://www.youtube.com/watch?v=9R31OUPpxU4) -**Step-by-Step Workflow:** +**Let's Do This Together:** +1. **Create your repository on GitHub**. Head over to GitHub.com and look for that bright green **New** button (or the **+** sign in the top right corner). Click it and select **New repository**. -1. **Create repository on GitHub**. On GitHub.com, in the repositories tab, or from the navigation bar top-right, find the **New** button (green button) or the **+** dropdown and select **New repository**. + Here's what to do: + 1. Give your repository a name – make it something meaningful to you! + 1. Add a description if you want (this helps others understand what your project is about) + 1. Decide if you want it public (everyone can see it) or private (just for you) + 1. I recommend checking the box to add a README file – it's like the front page of your project + 1. Click **Create repository** and celebrate – you just created your first repo! 🎉 - 1. Give your repository (folder) a name - 1. Add a description (optional but recommended) - 1. Choose to make it public or private - 1. Consider adding a README file, .gitignore, and license - 1. Select **Create repository**. - -1. **Navigate to your working folder**. In your terminal, switch to the folder (also known as the directory) you want to start tracking. Type: +2. **Navigate to your project folder**. Now let's open up your terminal (don't worry, it's not as scary as it looks!). We need to tell your computer where your project files are. Type this command: ```bash cd [name of your folder] ``` - **Here's what this command does:** - - **Navigate** to your project directory where your code files are located - - **Prepare** the environment for Git initialization and tracking + **What we're doing here:** + - We're basically saying "Hey computer, take me to my project folder" + - This is like opening a specific folder on your desktop, but we're doing it with text commands + - Replace `[name of your folder]` with the actual name of your project folder -1. **Initialize a git repository**. In your project type: +3. **Turn your folder into a Git repository**. This is where the magic happens! Type: ```bash git init ``` - **Step by step, here's what's happening:** - - **Create** a hidden `.git` folder that contains all version control information - - **Transform** your regular folder into a Git repository that can track changes - - **Set up** the foundation for version control in your project + **Here's what just happened (pretty cool stuff!):** + - Git just created a hidden `.git` folder in your project – you won't see it, but it's there! + - Your regular folder is now a "repository" that can track every change you make + - Think of it like giving your folder superpowers to remember everything -1. **Check status**. To check the status of your repository type: +4. **Check what's happening**. Let's see what Git thinks about your project right now: ```bash git status ``` - **Understanding the output:** + **Understanding what Git is telling you:** - The output might look something like this: + You might see something that looks like this: ```output Changes not staged for commit: @@ -159,119 +168,117 @@ Let's say you have a folder locally with some code project and you want to start modified: file2.txt ``` - **What you need to know about this output:** - - **Red text** typically indicates files that have changes but aren't ready for commit - - **Green text** shows files that are staged and ready to be committed - - **Helpful hints** are provided about what commands you can use next - - > 💡 **Understanding Git Status**: This command is your best friend! It tells you exactly what Git sees in your project and what actions you can take next. + **Don't panic! Here's what this means:** + - Files in **red** are files that have changes but aren't ready to be saved yet + - Files in **green** (when you see them) are ready to be saved + - Git is being helpful by telling you exactly what you can do next - The `git status` command tells you things like what files are ready to be _saved_ to the repo or have changes that you might want to persist. + > 💡 **Pro tip**: The `git status` command is your best friend! Use it anytime you're confused about what's going on. It's like asking Git "Hey, what's the situation right now?" -1. **Add all files for tracking** (also called staging files): +5. **Get your files ready to save** (this is called "staging"): ```bash git add . ``` - **Here's what this command does:** - - **Stage** all modified and new files in your project directory - - **Prepare** these files to be included in your next commit - - **Mark** files as ready for the permanent snapshot we'll create next - - The `git add` command with the `.` argument indicates that all your files & changes are ready for tracking. + **What we just did:** + - We told Git "Hey, I want to include ALL my files in the next save" + - The `.` is like saying "everything in this folder" + - Now your files are "staged" and ready for the next step -1. **Add selected files for tracking** (selective staging): + **Want to be more selective?** You can add just specific files: ```bash git add [file or folder name] ``` - **When to use selective staging:** - - **Organize** related changes into separate commits for cleaner history - - **Include** only the files that belong together logically - - **Create** more meaningful commit messages by grouping related work + **Why might you want to do this?** + - Sometimes you want to save related changes together + - It helps you organize your work into logical chunks + - Makes it easier to understand what changed and when - > 💡 **Pro Tip**: Use selective adding when you want to commit related changes together. This creates more meaningful commit history. - -1. **Unstage files** (if you change your mind): + **Changed your mind?** No worries! You can unstage files like this: ```bash - # Unstage all files + # Unstage everything git reset - # Unstage a particular file - git reset [file or folder name] + # Unstage just one file + git reset [file name] ``` - **Understanding unstaging:** - - **Remove** files from the staging area without losing your changes - - **Keep** your modifications but exclude them from the next commit - - **Reorganize** what you want to include in your commit + Don't worry – this doesn't delete your work, it just takes files out of the "ready to save" pile. -1. **Persisting your work** (making a commit). At this point you've added the files to a so called _staging area_. A place where Git is tracking your files. To make the change permanent you need to _commit_ the files. To do so you create a _commit_ with the `git commit` command. A _commit_ represents a saving point in the history of your repo. Type the following to create a _commit_: +6. **Save your work permanently** (making your first commit!): ```bash git commit -m "first commit" ``` - **What happens when you commit:** - - **Create** a permanent snapshot of all staged files at this point in time - - **Record** the commit message to explain what changes were made - - **Generate** a unique identifier (hash) for this specific set of changes - - **Add** this snapshot to your project's version history - - > 💡 **Commit Message Tips**: Your first commit message can be simple, but for future commits, be descriptive! Good examples: "Add user login functionality" or "Fix navigation menu bug". + **🎉 Congratulations! You just made your first commit!** + + **Here's what just happened:** + - Git took a "snapshot" of all your staged files at this exact moment + - Your commit message "first commit" explains what this save point is about + - Git gave this snapshot a unique ID so you can always find it later + - You've officially started tracking your project's history! - This commits all of your files, adding the message "first commit". For future commit messages you will want to be more descriptive to convey what type of change you've made. + > 💡 **Future commit messages**: For your next commits, be more descriptive! Instead of "updated stuff", try "Add contact form to homepage" or "Fix navigation menu bug". Your future self will thank you! -1. **Connect your local Git repo with GitHub**. A Git repo is good on your machine but at some point you want to have backup of your files somewhere and also invite other people to work with you on your repo. One such great place to do so is GitHub. Remember we've already created a repo on GitHub so the only thing we need to do is to connect our local Git repo with GitHub. The command `git remote add` will do just that. Type the following command: +7. **Connect your local project to GitHub**. Right now, your project exists only on your computer. Let's connect it to your GitHub repository so you can share it with the world! - > Note, before you type the command go to your GitHub repo page to find the repository URL. You will use it in the below command. Replace `https://github.com/username/repository_name.git` with your GitHub URL. + First, go to your GitHub repository page and copy the URL. Then come back here and type: ```bash git remote add origin https://github.com/username/repository_name.git ``` + + (Replace that URL with your actual repository URL!) - **Step by step, here's what's happening:** - - **Create** a connection named "origin" that points to your GitHub repository - - **Link** your local Git repository with the remote repository on GitHub - - **Enable** the ability to push your local commits to GitHub and pull changes from GitHub + **What we just did:** + - We created a connection between your local project and your GitHub repository + - "Origin" is just a nickname for your GitHub repository – it's like adding a contact to your phone + - Now your local Git knows where to send your code when you're ready to share it - 💡 **Modern alternative**: You can also use the GitHub CLI to create and connect your repository in one step: + 💡 **Easier way**: If you have GitHub CLI installed, you can do this in one command: ```bash gh repo create my-repo --public --push --source=. ``` - This creates a _remote_, or connection, named "origin" pointing at the GitHub repository you created earlier. - -1. **Send local files to GitHub**. So far you've created a _connection_ between the local repo and the GitHub repo. Let's send these files to GitHub with the following command `git push`, like so: +8. **Send your code to GitHub** (the big moment!): ```bash git push -u origin main ``` - **Breaking down this command:** - - **Upload** your commits from the "main" branch to GitHub - - **Set** the upstream branch using `-u` to establish a permanent link - - **Enable** simplified future pushes without specifying branch names + **🚀 This is it! You're uploading your code to GitHub!** + + **What's happening:** + - Your commits are traveling from your computer to GitHub + - The `-u` flag sets up a permanent connection so future pushes are easier + - "main" is the name of your primary branch (like the main folder) + - After this, you can just type `git push` for future uploads! - This sends your commits in your "main" branch to GitHub. Setting the `upstream` branch with `-u` in the command establishes a link between your local branch and the remote branch, so you can simply use `git push` or `git pull` without specifying the branch name in the future. + 💡 **Quick note**: If your branch is called something else (like "master"), use that name instead. You can check with `git branch --show-current`. - 💡 **Note**: If your default branch is named differently (like "master"), replace "main" with your actual branch name. You can check your current branch with `git branch --show-current`. +9. **Your new daily coding rhythm** (this is where it gets addictive!): -2. **To add more changes** (daily workflow). If you want to continue making changes and pushing them to GitHub you'll just need to use the following three commands: + From now on, whenever you make changes to your project, you've got this simple three-step dance: ```bash git add . - git commit -m "type your commit message here" + git commit -m "describe what you changed" git push ``` - **Step by step, here's your daily workflow:** - - **Stage** your modified files with `git add .` (or add specific files) - - **Commit** your changes with a descriptive message about what you've accomplished - - **Push** to GitHub to backup your work and share it with others + **This becomes your coding heartbeat:** + - Make some awesome changes to your code ✨ + - Stage them with `git add` ("Hey Git, pay attention to these changes!") + - Save them with `git commit` and a descriptive message (future you will thank you!) + - Share them with the world using `git push` 🚀 + - Rinse and repeat – seriously, this becomes as natural as breathing! + + I love this workflow because it's like having multiple save points in a video game. Made a change you love? Commit it! Want to try something risky? No problem – you can always go back to your last commit if things go sideways! > 💡 **Tip**: You might also want to adopt a `.gitignore` file to prevent files you don't want to track from showing up on GitHub - like that notes file you store in the same folder but has no place on a public repository. You can find templates for `.gitignore` files at [.gitignore templates](https://github.com/github/gitignore) or create one using [gitignore.io](https://www.toptal.com/developers/gitignore). @@ -293,11 +300,15 @@ As in the subject, in the body (optional) also use the imperative, present tense ✅ Take a few minutes to surf around GitHub. Can you find a really great commit message? Can you find a really minimal one? What information do you think is the most important and useful to convey in a commit message? -## Working on projects with others +## Working with Others (The Fun Part!) + +Hold onto your hat because THIS is where GitHub becomes absolutely magical! 🪄 You've mastered managing your own code, but now we're diving into my absolute favorite part – collaborating with amazing people from all over the world. -Collaboration is where GitHub truly shines. While managing your own code is valuable, the real magic happens when developers work together to build something amazing. GitHub transforms solo coding into a collaborative symphony where multiple developers can contribute simultaneously without stepping on each other's toes. +Picture this: you wake up tomorrow and see that someone in Tokyo improved your code while you were sleeping. Then someone in Berlin fixes a bug you've been stuck on. By afternoon, a developer in São Paulo has added a feature you never even thought of. That's not science fiction – that's just Tuesday in the GitHub universe! -In this section, you'll learn how to make your projects welcoming to other developers and how to contribute meaningfully to existing projects. These collaboration skills are what separate hobbyist coders from professional developers. +What gets me really excited is that the collaboration skills you're about to learn? These are the EXACT same workflows that teams at Google, Microsoft, and your favorite startups use every single day. You're not just learning a cool tool – you're learning the secret language that makes the entire software world work together. + +Seriously, once you experience the rush of having someone merge your first pull request, you'll understand why developers get so passionate about open source. It's like being part of the world's biggest, most creative team project! > Check out video > @@ -307,18 +318,20 @@ The main reason for putting things on GitHub was to make it possible to collabor In your repository, navigate to `Insights > Community` to see how your project compares to recommended community standards. -> 🎯 **Making Your Repository Professional**: A well-documented repository attracts more contributors and shows that you care about code quality. +Want to make your repository look professional and welcoming? Head over to your repository and click on `Insights > Community`. This cool feature shows you how your project compares to what the GitHub community considers "good repository practices." + +> 🎯 **Making Your Project Shine**: A well-organized repository with good documentation is like having a clean, welcoming storefront. It tells people you care about your work and makes others want to contribute! -**Essential Repository Elements:** +**Here's what makes a repository awesome:** -| Element | Purpose | Why It Matters | -|---------|---------|----------------| -| **Description** | Brief summary of your project | Helps people understand what your project does at a glance | -| **README** | Detailed project documentation | The first thing people read - make it count! | -| **Contributing Guidelines** | Instructions for contributors | Shows you welcome collaboration and sets clear expectations | -| **Code of Conduct** | Community behavior standards | Creates a welcoming environment for all contributors | -| **License** | Usage permissions | Defines how others can legally use your code | -| **Security Policy** | Vulnerability reporting process | Shows you take security seriously | +| What to Add | Why It's Important | What It Does for You | +|-------------|-------------------|---------------------| +| **Description** | First impression matters! | People know instantly what your project does | +| **README** | Your project's front page | Like a friendly tour guide for new visitors | +| **Contributing Guidelines** | Shows you welcome help | People know exactly how they can help you | +| **Code of Conduct** | Creates a friendly space | Everyone feels welcome to participate | +| **License** | Legal clarity | Others know how they can use your code | +| **Security Policy** | Shows you're responsible | Demonstrates professional practices | > 💡 **Pro Tip**: GitHub provides templates for all of these files. When creating a new repository, check the boxes to automatically generate these files. @@ -444,11 +457,17 @@ Update your current local working branch with all new commits from the correspon `git pull` -## How to contribute to open source +## Contributing to Open Source (Your Chance to Make an Impact!) + +Are you ready for something that's going to absolutely blow your mind? 🤯 Let's talk about contributing to open source projects – and I'm getting goosebumps just thinking about sharing this with you! + +This is your chance to become part of something truly extraordinary. Imagine improving the tools that millions of developers use every day, or fixing a bug in an app that your friends love. That's not just a dream – that's what open source contribution is all about! + +Here's what gives me chills every time I think about it: every single tool you've been learning with – your code editor, the frameworks we'll explore, even the browser you're reading this in – started with someone exactly like you making their very first contribution. That brilliant developer who built your favorite VS Code extension? They were once a beginner clicking "create pull request" with shaky hands, just like you're about to do. -Contributing to open source projects is one of the most rewarding experiences in web development. It's your opportunity to give back to the community, learn from experienced developers, and make a real impact on software used by thousands or even millions of people. +And here's the most beautiful part: the open source community is like the internet's biggest group hug. Most projects actively look for newcomers and have issues tagged "good first issue" specifically for people like you! Maintainers genuinely get excited when they see new contributors because they remember their own first steps. -The beauty of open source contribution is that everyone started as a beginner. The developers who created the tools you're learning with today were once exactly where you are now. By contributing to open source, you become part of this continuous cycle of learning and sharing that drives innovation in web development. +You're not just learning to code here – you're preparing to join a global family of builders who wake up every day thinking "How can we make the digital world a little bit better?" Welcome to the club! 🌟 First, let's find a repository (or **repo**) on GitHub of interest to you and to which you'd like to contribute a change. You will want to copy its contents to your machine. @@ -503,29 +522,40 @@ Projects might also have discussion in forums, mailing lists, or chat channels l ## 🚀 Challenge -Pair with a friend to work on each other's code. Create a project collaboratively, fork code, create branches, and merge changes. +Alright, it's time to put your shiny new GitHub superpowers to the test! 🚀 Here's a challenge that's going to make everything click in the most satisfying way: + +Grab a friend (or that family member who's always asking what you're up to with all this "computer stuff") and embark on a collaborative coding adventure together! This is where the real magic happens – create a project, let them fork it, make some branches, and merge changes like the pros you're becoming. + +I'm not gonna lie – you'll probably laugh at some point (especially when you both try to change the same line), maybe scratch your heads in confusion, but you'll definitely have those amazing "aha!" moments that make all the learning worth it. Plus, there's something special about sharing that first successful merge with someone else – it's like a tiny celebration of how far you've come! + +Don't have a coding buddy yet? No worries at all! The GitHub community is packed with incredibly welcoming people who remember what it was like to be new. Look for repositories with "good first issue" labels – they're basically saying "Hey beginners, come learn with us!" How awesome is that? ## Post-Lecture Quiz [Post-lecture quiz](https://ff-quizzes.netlify.app/web/en/) -## Review & Self Study +## Review & Keep Learning -Read more about [contributing to open source software](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution). +Whew! 🎉 Look at you – you've just conquered GitHub basics like an absolute champion! If your brain feels a little full right now, that's completely normal and honestly a good sign. You've just learned tools that took me weeks to feel comfortable with when I started. -[Git cheatsheet](https://training.github.com/downloads/github-git-cheat-sheet/). +Git and GitHub are incredibly powerful (like, seriously powerful), and every developer I know – including the ones who seem like wizards now – had to practice and stumble around a bit before it all clicked. The fact that you've made it through this lesson means you're already on your way to mastering some of the most important tools in a developer's toolkit. -Practice, practice, practice. GitHub has great learning paths available via [GitHub Skills](https://skills.github.com): +Here are some absolutely fantastic resources to help you practice and become even more awesome: + +- [Contributing to open source software guide](https://opensource.guide/how-to-contribute/#how-to-submit-a-contribution) – Your roadmap to making a difference +- [Git cheatsheet](https://training.github.com/downloads/github-git-cheat-sheet/) – Keep this handy for quick reference! + +And remember: practice makes progress, not perfection! The more you use Git and GitHub, the more natural it becomes. GitHub has created some amazing interactive courses that let you practice in a safe environment: - [Introduction to GitHub](https://github.com/skills/introduction-to-github) - [Communicate using Markdown](https://github.com/skills/communicate-using-markdown) - [GitHub Pages](https://github.com/skills/github-pages) - [Managing merge conflicts](https://github.com/skills/resolve-merge-conflicts) -**Additional modern resources**: -- [GitHub CLI documentation](https://cli.github.com/manual/) -- [GitHub Codespaces documentation](https://docs.github.com/en/codespaces) -- [GitHub Actions documentation](https://docs.github.com/en/actions) -- [Git best practices](https://www.atlassian.com/git/tutorials/comparing-workflows) +**Feeling adventurous? Check out these modern tools:** +- [GitHub CLI documentation](https://cli.github.com/manual/) – For when you want to feel like a command-line wizard +- [GitHub Codespaces documentation](https://docs.github.com/en/codespaces) – Code in the cloud! +- [GitHub Actions documentation](https://docs.github.com/en/actions) – Automate all the things +- [Git best practices](https://www.atlassian.com/git/tutorials/comparing-workflows) – Level up your workflow game ## GitHub Copilot Agent Challenge 🚀 @@ -537,10 +567,12 @@ Use the Agent mode to complete the following challenge: ## Assignment -Complete the [Introduction to GitHub](https://github.com/skills/introduction-to-github) course on GitHub Skills. +Your mission, should you choose to accept it: Complete the [Introduction to GitHub](https://github.com/skills/introduction-to-github) course on GitHub Skills. This interactive course will let you practice everything you've learned in a safe, guided environment. Plus, you'll get a cool badge when you finish! 🏅 + +**Feeling ready for more challenges?** +- Set up SSH authentication for your GitHub account (no more passwords!) +- Try using GitHub CLI for your daily Git operations +- Create a repository with a GitHub Actions workflow +- Explore GitHub Codespaces by opening this very repository in a cloud-based editor -**Optional advanced assignments**: -- Set up SSH authentication for your GitHub account -- Try using GitHub CLI for common operations -- Create a repository with GitHub Actions workflow -- Explore GitHub Codespaces by opening this repository in a codespace +Remember: every expert was once a beginner. You've got this! 💪 diff --git a/1-getting-started-lessons/3-accessibility/README.md b/1-getting-started-lessons/3-accessibility/README.md index 0c581168..ffc6f71c 100644 --- a/1-getting-started-lessons/3-accessibility/README.md +++ b/1-getting-started-lessons/3-accessibility/README.md @@ -10,25 +10,27 @@ > > \- Sir Timothy Berners-Lee, W3C Director and inventor of the World Wide Web -Web accessibility isn't just a nice-to-have feature—it's a fundamental principle that makes the internet truly universal. When you build accessible websites, you're not just helping people with disabilities; you're creating better experiences for everyone. Think about how curb cuts designed for wheelchairs also help people with strollers, luggage, or bicycles. Accessible web design works the same way. +Here's something that might surprise you: when you build accessible websites, you're not just helping people with disabilities—you're actually making the web better for everyone! -In this lesson, you'll discover how to create websites that work for everyone, regardless of their abilities or the technologies they use to browse the web. You'll learn practical techniques that are built into modern web standards, explore powerful accessibility testing tools, and understand how accessibility enhances usability for all users. +Ever notice those curb cuts at street corners? They were originally designed for wheelchairs, but now they help people with strollers, delivery workers with dollies, travelers with rolling luggage, and cyclists too. That's exactly how accessible web design works—solutions that help one group often end up benefiting everyone. Pretty cool, right? -By the end of this lesson, you'll have the knowledge and tools to make accessibility a natural part of your development process from day one. Let's explore how thoughtful design choices can open up the web to billions of users worldwide. +In this lesson, we're going to explore how to create websites that truly work for everyone, no matter how they browse the web. You'll discover practical techniques that are already built into web standards, get hands-on with testing tools, and see how accessibility makes your sites more usable for all users. + +By the end of this lesson, you'll have the confidence to make accessibility a natural part of your development workflow. Ready to explore how thoughtful design choices can open up the web to billions of users? Let's dive in! > You can take this lesson on [Microsoft Learn](https://docs.microsoft.com/learn/modules/web-development-101/accessibility/?WT.mc_id=academic-77807-sagibbon)! ## Understanding Assistive Technologies -Before we dive into building accessible websites, let's understand how people with different abilities navigate the web. This knowledge will help you make informed decisions about your design and development choices. +Before we jump into coding, let's take a moment to understand how people with different abilities actually experience the web. This isn't just theory—understanding these real-world navigation patterns will make you a much better developer! -Assistive technologies are specialized tools that help people with disabilities interact with digital content. Understanding how these tools work is essential for creating truly accessible web experiences. +Assistive technologies are pretty amazing tools that help people with disabilities interact with websites in ways that might surprise you. Once you get the hang of how these technologies work, creating accessible web experiences becomes way more intuitive. It's like learning to see your code through someone else's eyes. ### Screen readers -[Screen readers](https://en.wikipedia.org/wiki/Screen_reader) are remarkable assistive technologies that convert digital text into speech or braille output. They're primarily used by people with visual impairments, but they also help users with learning disabilities like dyslexia. +[Screen readers](https://en.wikipedia.org/wiki/Screen_reader) are pretty sophisticated pieces of technology that convert digital text into speech or braille output. While they're primarily used by people with visual impairments, they're also super helpful for users with learning disabilities like dyslexia. -Think of a screen reader as a voice narrator for the web. It reads content aloud in a logical order, announces interactive elements like buttons and links, and provides keyboard shortcuts for efficient navigation. However, screen readers can only work effectively if websites are built with proper structure and meaningful content. +I like to think of a screen reader as having a really smart narrator reading a book to you. It reads content aloud in a logical order, announces interactive elements like "button" or "link," and provides keyboard shortcuts for jumping around a page. But here's the thing—screen readers can only work their magic if we build websites with proper structure and meaningful content. That's where you come in as a developer! **Popular screen readers across platforms:** - **Windows**: [NVDA](https://www.nvaccess.org/about-nvda/) (free and most popular), [JAWS](https://webaim.org/articles/jaws/), [Narrator](https://support.microsoft.com/windows/complete-guide-to-narrator-e4397a0d-ef4f-b386-d8ae-c172f109bdb1/?WT.mc_id=academic-77807-sagibbon) (built-in) @@ -45,11 +47,11 @@ Screen readers provide multiple navigation methods that make browsing efficient - **Link lists**: Generate a list of all links for quick access - **Form controls**: Navigate directly between input fields and buttons -> 💡 **Developer Insight**: 68% of screen reader users navigate primarily by headings ([WebAIM Survey](https://webaim.org/projects/screenreadersurvey9/#finding)). This is why proper heading structure is crucial! +> 💡 **Here's something that blew my mind**: 68% of screen reader users navigate primarily by headings ([WebAIM Survey](https://webaim.org/projects/screenreadersurvey9/#finding)). This means your heading structure is like a roadmap for users—when you get it right, you're literally helping people find their way around your content faster! ### Building your testing workflow -Effective accessibility testing requires both automated tools and manual verification. Here's a systematic approach that catches the most issues: +Here's some good news—effective accessibility testing doesn't have to be overwhelming! You'll want to combine automated tools (they're fantastic at catching obvious issues) with some hands-on testing. Here's a systematic approach that I've found catches the most issues without eating up your entire day: **Essential manual testing workflow:** @@ -79,9 +81,9 @@ graph TD ### Zoom and magnification tools -Many users rely on magnification to make content readable. This includes people with low vision, older adults, and even users in bright sunlight or with temporary vision issues. Modern zoom technologies have evolved far beyond simple image scaling. +You know how you sometimes pinch to zoom on your phone when text is too small, or squint at your laptop screen in bright sunlight? Many users rely on magnification tools to make content readable every single day. This includes people with low vision, older adults, and anyone who's ever tried to read a website outdoors. -Understanding how zoom works helps you create responsive designs that remain functional and beautiful at any magnification level. +Modern zoom technologies have evolved beyond just making things bigger. Understanding how these tools work will help you create responsive designs that remain functional and attractive at any magnification level. **Modern browser zoom capabilities:** - **Page zoom**: Scales all content proportionally (text, images, layout) - this is the preferred method @@ -99,13 +101,13 @@ Understanding how zoom works helps you create responsive designs that remain fun ## Modern Accessibility Testing Tools -Now that you understand how assistive technologies work, let's explore the tools that help you build and test accessible websites. Combining automated testing with manual verification gives you confidence that your sites work for everyone. +Now that you understand how people navigate the web with assistive technologies, let's explore the tools that help you build and test accessible websites. -Modern accessibility testing follows a comprehensive approach: automated tools catch obvious issues, while manual testing ensures real-world usability. +Think of it like this: automated tools are great at catching obvious issues (like missing alt text), while hands-on testing helps you ensure your site feels good to use in the real world. Together, they give you confidence that your sites work for everyone. ### Color contrast testing -Color contrast is one of the most common accessibility issues, but it's also one of the easiest to fix. Good contrast benefits everyone—from users with visual impairments to people viewing screens in bright sunlight. +Here's some good news: color contrast is one of the most common accessibility issues, but it's also one of the easiest to fix. Good contrast benefits everyone—from users with visual impairments to people trying to read their phones at the beach. **WCAG contrast requirements:** @@ -146,15 +148,15 @@ The most effective accessibility testing combines multiple approaches. No single ## Building Accessibility from the Ground Up -The most effective approach to web accessibility is building it into your foundation from day one. Retrofitting accessibility later is not only more expensive and time-consuming—it often results in subpar user experiences. +The key to accessibility success is building it into your foundation from day one. I know it's tempting to think "I'll add accessibility later," but that's like trying to add a ramp to a house after it's already built. Possible? Yes. Easy? Not really. -Think of accessibility like building a house: it's much easier to include wheelchair accessibility in the initial architectural plans than to add ramps and wider doorways after construction is complete. +Think of accessibility like planning a house—it's much easier to include wheelchair accessibility in your initial architectural plans than to retrofit everything later. ### The POUR principles: Your accessibility foundation -The Web Content Accessibility Guidelines (WCAG) are built around four fundamental principles known as POUR. These principles provide a framework for making content accessible to users with diverse abilities and technologies. +The Web Content Accessibility Guidelines (WCAG) are built around four fundamental principles that spell out POUR. Don't worry—these aren't stuffy academic concepts! They're actually practical guidelines for making content that works for everyone. -Understanding POUR helps you make accessibility decisions that create inclusive experiences for everyone. +Once you get the hang of POUR, making accessibility decisions becomes way more intuitive. It's like having a mental checklist that guides your design choices. Let's break it down: **🔍 Perceivable**: Information must be presentable in ways users can perceive through their available senses @@ -285,9 +287,9 @@ button:focus:not(:focus-visible) { ### Semantic HTML: The foundation of accessibility -Semantic HTML is like providing a clear roadmap for assistive technologies. When you use the right HTML elements for their intended purpose, you're giving screen readers, keyboards, and other tools the information they need to help users navigate effectively. +Semantic HTML is like giving assistive technologies a GPS system for your website. When you use the right HTML elements for their intended purpose, you're basically providing screen readers, keyboards, and other tools with a detailed roadmap to help users navigate effectively. -Think of semantic HTML as the difference between a well-organized library with clear categories and signs versus a warehouse where books are randomly scattered. Both contain the same information, but only one is truly usable. +Here's an analogy that really clicked for me: semantic HTML is the difference between a well-organized library with clear categories and helpful signs versus a warehouse where books are scattered randomly. Both places have the same books, but which one would you rather try to find something in? Exactly! **Building blocks of accessible page structure:** @@ -368,10 +370,10 @@ Think of semantic HTML as the difference between a well-organized library with c ### Heading hierarchy: Creating a logical content outline -Headings are the backbone of accessible content structure. Screen reader users rely heavily on headings to understand and navigate your content—it's like providing a detailed table of contents for your page. +Headings are absolutely crucial for accessible content—they're like the spine that holds everything together. Screen reader users rely heavily on headings to understand and navigate your content. Think of it as providing a table of contents for your page. -**The heading hierarchy rule:** -Never skip heading levels. Always progress logically from `

` to `

` to `

`, and so on. Think of headings like an outline structure in a document. +**Here's the golden rule for headings:** +Never skip levels. Always progress logically from `

` to `

` to `

`, and so on. Remember making outlines in school? It's exactly the same principle—you wouldn't jump from "I. Main Point" straight to "C. Sub-sub-point" without a "A. Sub-point" in between, right? **Perfect heading structure example:** @@ -501,9 +503,9 @@ Beyond the basics of contrast and color, there are sophisticated techniques that ## Crafting Meaningful Link Text -Links are the highways of the web, but poorly written link text creates roadblocks for users with disabilities. Great link text makes your content scannable and navigable for everyone. +Links are basically the highways of the web, but poorly written link text is like having road signs that just say "Place" instead of "Downtown Chicago." Not very helpful, right? -Screen readers can extract all links from a page and present them as a list—imagine if your links appeared as a directory. Would each link make sense without surrounding context? +Here's something that blew my mind when I first learned it: screen readers can extract all the links from a page and show them as one big list. Imagine if someone handed you a directory of every link on your page. Would each one make sense on its own? That's the test your link text needs to pass! ### Understanding link navigation patterns @@ -680,11 +682,11 @@ Sometimes visual design constraints or technical requirements need special solut ## ARIA: Supercharging HTML Accessibility -[Accessible Rich Internet Applications (ARIA)](https://developer.mozilla.org/docs/Web/Accessibility/ARIA) is like a universal translator between your complex web applications and assistive technologies. When HTML alone can't express the full meaning of your interactive components, ARIA fills in the gaps. +[Accessible Rich Internet Applications (ARIA)](https://developer.mozilla.org/docs/Web/Accessibility/ARIA) is like having a universal translator between your complex web applications and assistive technologies. When HTML alone can't express everything your interactive components are doing, ARIA steps in to fill those gaps. -Think of ARIA as adding helpful annotations to your HTML—like stage directions in a play script that help actors understand their roles and relationships. +I like to think of ARIA as adding helpful annotations to your HTML—kind of like stage directions in a play script that help actors understand their roles and relationships. -**The fundamental rule of ARIA**: Use semantic HTML first, ARIA second. ARIA should enhance and clarify, never replace proper HTML structure. +**Here's the most important rule about ARIA**: Always use semantic HTML first, then add ARIA to enhance it. Think of ARIA as seasoning, not the main dish. It should clarify and enhance your HTML structure, never replace it. Get that foundation right first! ### Strategic ARIA implementation @@ -840,9 +842,9 @@ graph TD ## Making Images and Media Accessible -Visual and audio content are essential parts of modern web experiences, but they can create barriers if not implemented thoughtfully. The goal is to ensure that the information and emotional impact of your media reaches every user. +Visual and audio content are essential parts of modern web experiences, but they can create barriers if not implemented thoughtfully. The goal is ensuring that the information and emotional impact of your media reaches every user. Once you get the hang of it, it becomes second nature. -Different types of media content require different accessibility approaches—understanding these distinctions helps you choose the right solution for each situation. +Different types of media need different accessibility approaches. It's like cooking—you wouldn't treat a delicate fish the same way you'd treat a hearty steak. Understanding these distinctions helps you choose the right solution for each situation. ### Strategic image accessibility @@ -917,7 +919,7 @@ Every image on your website serves a purpose. Understanding that purpose helps y ## Keyboard navigation and focus management -Many users rely exclusively on keyboard navigation. Ensuring your site works perfectly with keyboard input is essential for accessibility. +Many users navigate the web entirely with their keyboards. This includes people with motor disabilities, power users who find keyboards faster than mice, and anyone whose mouse has stopped working. Making sure your site works well with keyboard input is essential and often makes your site more efficient for everyone. ### Essential keyboard navigation patterns @@ -1075,7 +1077,9 @@ Forms are critical for user interaction and require special attention to accessi ## Your Accessibility Journey: Key Takeaways -Congratulations! You've just gained the foundational knowledge to create truly inclusive web experiences. Web accessibility isn't just about compliance—it's about recognizing the diverse ways people interact with digital content and designing for that beautiful complexity. +Congratulations! You've just gained the foundational knowledge to create truly inclusive web experiences. This is pretty exciting stuff! Web accessibility isn't just about checking compliance boxes—it's about recognizing the diverse ways people interact with digital content and designing for that amazing complexity. + +You're now part of a growing community of developers who understand that great design works for everyone. Welcome to the club! **🎯 Your accessibility toolkit now includes:** @@ -1097,9 +1101,9 @@ Congratulations! You've just gained the foundational knowledge to create truly i > 💡 **Remember**: Accessibility constraints often lead to innovative, elegant solutions that benefit everyone. Curb cuts, captions, and voice controls all started as accessibility features and became mainstream improvements. -**The business case is clear**: Accessible websites reach more users, rank better in search engines, have lower maintenance costs, and avoid legal risks. But more importantly, accessible websites embody the best values of the web—openness, inclusivity, and equal access to information. +**The business case is crystal clear**: Accessible websites reach more users, rank better in search engines, have lower maintenance costs, and avoid legal risks. But honestly? The real reason to care about accessibility goes so much deeper. Accessible websites embody the best values of the web—openness, inclusivity, and the idea that everyone deserves equal access to information. -You're now equipped to build the inclusive web of the future. Every accessible site you create makes the internet a more welcoming place for everyone. +You're now equipped to build the inclusive web of the future. Every accessible site you create makes the internet a more welcoming place for everyone. That's pretty amazing when you think about it! ## Additional Resources diff --git a/10-ai-framework-project/README.md b/10-ai-framework-project/README.md index 3962b66d..446ef432 100644 --- a/10-ai-framework-project/README.md +++ b/10-ai-framework-project/README.md @@ -1,16 +1,50 @@ # AI Framework -There are many AI frameworks out there that when used can severely quicken up the time it takes to build a project. In this project we will focus on understanding what problems these frameworks address and build such a project ourselves. +Ever felt overwhelmed trying to build AI applications from scratch? You're not alone! AI frameworks are like having a Swiss Army knife for AI development - they're powerful tools that can save you time and headaches when building intelligent applications. Think of an AI framework as a well-organized library: it provides pre-built components, standardized APIs, and smart abstractions so you can focus on solving problems instead of wrestling with implementation details. -## Why a framework +In this lesson, we'll explore how frameworks like LangChain can turn what used to be complex AI integration tasks into clean, readable code. You'll discover how to tackle real-world challenges like keeping track of conversations, implementing tool calling, and juggling different AI models through one unified interface. -When it comes to using AI there are different approaches and different reasons for choosing these approaches, here are some: +By the time we're done, you'll know when to reach for frameworks instead of raw API calls, how to use their abstractions effectively, and how to build AI applications that are ready for real-world use. Let's explore what AI frameworks can do for your projects. -- **No SDK**, most AI models allows you to interact directly with the AI model via for example HTTP requests. That approach works and may sometimes be your only option if an SDK option is missing. -- **SDK**. Using an SDK is usually the recommended approach as it allows you to type less code to interact with your model. It usually is limited to a specific model and if using different models, you might need to write new code to support those additional models. -- **A framework**. A framework usually takes things to another level in the sense that if you need to use different models, there's one API for all of them, what differs is usually the initial set up. Additionally frameworks brings in useful abstractions like in the AI space, they can deal with tools, memory, workflows, agents and more while writing less code. Because frameworks are usually opinionated they can really be helpful if you buy into how they do things but may fall short if you try to do something bespoke that the framework isn't made for. Sometimes a framework can also simplify too much and you may therefore not learn an important topic that later may harm performance for example. +## Why choose a framework? -Generally, use the right tool for the job. +So you're ready to build an AI app - awesome! But here's the thing: you've got several different paths you can take, and each one has its own pros and cons. It's kind of like choosing between walking, biking, or driving to get somewhere - they'll all get you there, but the experience (and effort) will be totally different. + +Let's break down the three main ways you can integrate AI into your projects: + +| Approach | Advantages | Best For | Considerations | +|----------|------------|----------|--------------| +| **Direct HTTP Requests** | Full control, no dependencies | Simple queries, learning fundamentals | More verbose code, manual error handling | +| **SDK Integration** | Less boilerplate, model-specific optimization | Single-model applications | Limited to specific providers | +| **AI Frameworks** | Unified API, built-in abstractions | Multi-model apps, complex workflows | Learning curve, potential over-abstraction | + +### Framework Benefits in Practice + +```mermaid +graph TD + A[Your Application] --> B[AI Framework] + B --> C[OpenAI GPT] + B --> D[Anthropic Claude] + B --> E[GitHub Models] + B --> F[Local Models] + + B --> G[Built-in Tools] + G --> H[Memory Management] + G --> I[Conversation History] + G --> J[Function Calling] + G --> K[Error Handling] +``` + +**Why frameworks matter:** +- **Unifies** multiple AI providers under one interface +- **Handles** conversation memory automatically +- **Provides** ready-made tools for common tasks like embeddings and function calling +- **Manages** error handling and retry logic +- **Turns** complex workflows into readable method calls + +> 💡 **Pro Tip**: Use frameworks when switching between different AI models or building complex features like agents, memory, or tool calling. Stick with direct APIs when learning the basics or building simple, focused applications. + +**Bottom line**: Like choosing between a craftsman's specialized tools and a complete workshop, it's about matching the tool to the task. Frameworks excel for complex, feature-rich applications, while direct APIs work well for straightforward use cases. ## Introduction @@ -20,13 +54,13 @@ In this lesson, we'll learn to: - Address common problems like chat conversations, tool usage, memory and context. - Leverage this to build AI apps. -## First prompt +## Your first AI prompt -In our first app example, we'll learn how to connect to an AI model and query it using a prompt. +Let's start with the fundamentals by creating your first AI application that sends a question and gets an answer back. Like Archimedes discovering the principle of displacement in his bath, sometimes the simplest observations lead to the most powerful insights - and frameworks make these insights accessible. -### Using Python +### Setting up LangChain with GitHub Models -For this example, we'll use Langchain to connect to GitHub Models. We can use a class called `ChatOpenAI` and give it the fields `api_key`, `base_url` and `model`. The token is something that automatically is populated within GitHub Codespaces and if you're running the app locally, you need to set up a personal access token for this to work. +We're going to use LangChain to connect to GitHub Models, which is pretty sweet because it gives you free access to various AI models. The best part? You only need a few simple configuration parameters to get started: ```python from langchain_openai import ChatOpenAI @@ -38,32 +72,59 @@ llm = ChatOpenAI( model="openai/gpt-4o-mini", ) -# works -response = llm.invoke("What's the capital of France?") +# Send a simple prompt +response = llm.invoke("What's the capital of France?") print(response.content) ``` -In this code, we: +**Let's break down what's happening here:** +- **Creates** a LangChain client using the `ChatOpenAI` class - this is your gateway to AI! +- **Configures** the connection to GitHub Models with your authentication token +- **Specifies** which AI model to use (`gpt-4o-mini`) - think of this as choosing your AI assistant +- **Sends** your question using the `invoke()` method - this is where the magic happens +- **Extracts** and displays the response - and voilà, you're chatting with AI! -- Call `ChatOpenAI` to create a client. -- Use `llm.invoke` with a prompt to create a response -- Print the response with `print(response.content)`. - -You should see a response similar to: +> 🔧 **Setup Note**: If you're using GitHub Codespaces, you're in luck - the `GITHUB_TOKEN` is already set up for you! Working locally? No worries, you'll just need to create a personal access token with the right permissions. +**Expected output:** ```text The capital of France is Paris. ``` -## Chat conversation +```mermaid +sequenceDiagram + participant App as Your Python App + participant LC as LangChain + participant GM as GitHub Models + participant AI as GPT-4o-mini + + App->>LC: llm.invoke("What's the capital of France?") + LC->>GM: HTTP request with prompt + GM->>AI: Process prompt + AI->>GM: Generated response + GM->>LC: Return response + LC->>App: response.content +``` -In the preceding section, you saw how we used what's normally known as zero shot prompting, a single prompt followed by a response. +## Building conversational AI -However, often you find yourself in a situation where you need to maintain a conversation of several messages being exchanged between yourself and the AI assistant. +That first example demonstrates the basics, but it's just a single exchange - you ask a question, get an answer, and that's it. In real applications, you want your AI to remember what you've been discussing, like how Watson and Holmes built their investigative conversations over time. -### Using Python +This is where LangChain becomes particularly useful. It provides different message types that help structure conversations and let you give your AI a personality. You'll be building chat experiences that maintain context and character. -In langchain, we can store the conversation in a list. The `HumanMessage` represents a message from a user, and `SystemMessage` is a message meant to set the "personality" of the AI. In below example you see how we instruct the AI to assume the personality of Captain Picard and for the human/user to ask "Tell me about you" as the prompt. +### Understanding message types + +Think of these message types as different "hats" that participants wear in a conversation. LangChain uses different message classes to keep track of who's saying what: + +| Message Type | Purpose | Example Use Case | +|--------------|---------|------------------| +| `SystemMessage` | Defines AI personality and behavior | "You are a helpful coding assistant" | +| `HumanMessage` | Represents user input | "Explain how functions work" | +| `AIMessage` | Stores AI responses | Previous AI responses in conversation | + +### Creating your first conversation + +Let's create a conversation where our AI assumes a specific role. We'll have it embody Captain Picard - a character known for his diplomatic wisdom and leadership: ```python messages = [ @@ -72,6 +133,11 @@ messages = [ ] ``` +**Breaking down this conversation setup:** +- **Establishes** the AI's role and personality through `SystemMessage` +- **Provides** the initial user query via `HumanMessage` +- **Creates** a foundation for multi-turn conversation + The full code for this example looks like so: ```python @@ -106,7 +172,7 @@ I believe in the importance of diplomacy, reason, and the pursuit of knowledge. I hold the ideals of the Federation close to my heart, believing in the importance of cooperation, understanding, and respect for all sentient beings. My experiences have shaped my leadership style, and I strive to be a thoughtful and just captain. How may I assist you further? ``` -To keep the state of the conversation, you can add the response from a chat, so conversation is remembered, here's how to do that: +To maintain conversation continuity (instead of resetting context each time), you need to keep adding responses to your message list. Like the oral traditions that preserved stories across generations, this approach builds lasting memory: ```python from langchain_core.messages import HumanMessage, SystemMessage @@ -141,9 +207,9 @@ print(response.content) ``` -What we can see from the above conversation is how we invoke the LLM two times, first with the conversation consisting of just two messages but then a second time with more messages added to the conversation. +Pretty neat, right? What's happening here is that we're calling the LLM twice - first with just our initial two messages, but then again with the full conversation history. It's like the AI is actually following along with our chat! -In fact, if you run this, you will see the second response being something like: +When you run this code, you'll get a second response that sounds something like: ```text Welcome aboard, Chris! It's always a pleasure to meet those who share a passion for exploration and discovery. While I cannot formally offer you a position on the Enterprise right now, I encourage you to pursue your aspirations. We are always in need of talented individuals with diverse skills and backgrounds. @@ -155,19 +221,121 @@ I'll take that as a maybe ;) ## Streaming responses -TODO +Ever notice how ChatGPT seems to "type" its responses in real-time? That's streaming in action. Like watching a skilled calligrapher work - seeing the characters appear stroke by stroke rather than materializing instantly - streaming makes the interaction feel more natural and provides immediate feedback. + +### Implementing streaming with LangChain + +```python +from langchain_openai import ChatOpenAI +import os + +llm = ChatOpenAI( + api_key=os.environ["GITHUB_TOKEN"], + base_url="https://models.github.ai/inference", + model="openai/gpt-4o-mini", + streaming=True +) + +# Stream the response +for chunk in llm.stream("Write a short story about a robot learning to code"): + print(chunk.content, end="", flush=True) +``` + +**Why streaming is awesome:** +- **Shows** content as it's being created - no more awkward waiting! +- **Makes** users feel like something's actually happening +- **Feels** faster, even when it technically isn't +- **Lets** users start reading while the AI is still "thinking" + +> 💡 **User Experience Tip**: Streaming really shines when you're dealing with longer responses like code explanations, creative writing, or detailed tutorials. Your users will love seeing progress instead of staring at a blank screen! ## Prompt templates -TODO +Prompt templates work like the rhetorical structures used in classical oratory - think of how Cicero would adapt his speech patterns for different audiences while maintaining the same persuasive framework. They let you create reusable prompts where you can swap out different pieces of information without rewriting everything from scratch. Once you set up the template, you just fill in the variables with whatever values you need. + +### Creating reusable prompts + +```python +from langchain_core.prompts import ChatPromptTemplate + +# Define a template for code explanations +template = ChatPromptTemplate.from_messages([ + ("system", "You are an expert programming instructor. Explain concepts clearly with examples."), + ("human", "Explain {concept} in {language} with a practical example for {skill_level} developers") +]) + +# Use the template with different values +questions = [ + {"concept": "functions", "language": "JavaScript", "skill_level": "beginner"}, + {"concept": "classes", "language": "Python", "skill_level": "intermediate"}, + {"concept": "async/await", "language": "JavaScript", "skill_level": "advanced"} +] + +for question in questions: + prompt = template.format_messages(**question) + response = llm.invoke(prompt) + print(f"Topic: {question['concept']}\n{response.content}\n---\n") +``` + +**Why you'll love using templates:** +- **Keeps** your prompts consistent across your entire app +- **No more** messy string concatenation - just clean, simple variables +- **Your AI** behaves predictably because the structure stays the same +- **Updates** are a breeze - change the template once, and it's fixed everywhere ## Structured output -TODO +Ever get frustrated trying to parse AI responses that come back as unstructured text? Structured output is like teaching your AI to follow the systematic approach that Linnaeus used for biological classification - organized, predictable, and easy to work with. You can request JSON, specific data structures, or any format you need. + +### Defining output schemas + +```python +from langchain_core.prompts import ChatPromptTemplate +from langchain_core.output_parsers import JsonOutputParser +from pydantic import BaseModel, Field + +class CodeReview(BaseModel): + score: int = Field(description="Code quality score from 1-10") + strengths: list[str] = Field(description="List of code strengths") + improvements: list[str] = Field(description="List of suggested improvements") + overall_feedback: str = Field(description="Summary feedback") + +# Set up the parser +parser = JsonOutputParser(pydantic_object=CodeReview) + +# Create prompt with format instructions +prompt = ChatPromptTemplate.from_messages([ + ("system", "You are a code reviewer. {format_instructions}"), + ("human", "Review this code: {code}") +]) + +# Format the prompt with instructions +chain = prompt | llm | parser + +# Get structured response +code_sample = """ +def calculate_average(numbers): + return sum(numbers) / len(numbers) +""" + +result = chain.invoke({ + "code": code_sample, + "format_instructions": parser.get_format_instructions() +}) + +print(f"Score: {result['score']}") +print(f"Strengths: {', '.join(result['strengths'])}") +``` + +**Why structured output is a game-changer:** +- **No more** guessing what format you'll get back - it's consistent every time +- **Plugs** directly into your databases and APIs without extra work +- **Catches** weird AI responses before they break your app +- **Makes** your code cleaner because you know exactly what you're working with ## Tool calling -Tools are how we give the LLM extra skills. The idea is to tell the LLM about functions it has and if a prompt is made that matches the description of one of these tools then we call them. +Now we reach one of the most powerful features: tools. This is how you give your AI practical capabilities beyond conversation. Like how medieval guilds developed specialized tools for specific crafts, you can equip your AI with focused instruments. You describe what tools are available, and when someone requests something that matches, your AI can take action. ### Using Python @@ -190,7 +358,7 @@ functions = { } ``` -What we're doing here is to create a description of a tool called `add`. By inheriting from `TypedDict` and adding members like `a` and `b` of type `Annotated` this can be converted to a schema that the LLM can understand. The creation of functions is a dictionary that ensures that we know what to do if a specific tool is identified. +So what's happening here? We're creating a blueprint for a tool called `add`. By inheriting from `TypedDict` and using those fancy `Annotated` types for `a` and `b`, we're giving the LLM a clear picture of what this tool does and what it needs. The `functions` dictionary is like our toolbox - it tells our code exactly what to do when the AI decides to use a specific tool. Let's see how we call the LLM with this tool next: @@ -263,15 +431,15 @@ TOOL CALL: 15 CONTENT: ``` -What this output mean is that the LLM analyzed the prompt "What is 3 + 12" as meaning that the `add` tool should be called and it knew that thanks to its name, description and member field descriptions. That the answer is 15 is because of our code using the dictionary `functions` to invoke it: +The AI examined "What is 3 + 12" and recognized this as a task for the `add` tool. Like how a skilled librarian knows which reference to consult based on the type of question asked, it made this determination from the tool's name, description, and field specifications. The result of 15 comes from our `functions` dictionary executing the tool: ```python print("TOOL CALL: ", functions[tool["name"]](**tool["args"])) ``` -### A more interesting tool that calls a web api +### A more interesting tool that calls a web API -Tools that adds two numbers is interesting as it illustrates how tool calling works but usually tools tend to do something more interesting like for example calling a Web API, let's do just that with this code: +Adding numbers demonstrates the concept, but real tools typically perform more complex operations, like calling web APIs. Let's expand our example to have the AI fetch content from the internet - similar to how telegraph operators once connected distant locations: ```python class joke(TypedDict): @@ -355,20 +523,342 @@ if(res.tool_calls): print("CONTENT: ",res.content) ``` -## Embedding +## Embeddings and document processing + +Embeddings represent one of the most elegant solutions in modern AI. Imagine if you could take any piece of text and convert it into numerical coordinates that capture its meaning. That's exactly what embeddings do - they transform text into points in multi-dimensional space where similar concepts cluster together. It's like having a coordinate system for ideas, reminiscent of how Mendeleev organized the periodic table by atomic properties. + +### Creating and using embeddings + +```python +from langchain_openai import OpenAIEmbeddings +from langchain_community.vectorstores import FAISS +from langchain_community.document_loaders import TextLoader +from langchain.text_splitter import CharacterTextSplitter + +# Initialize embeddings +embeddings = OpenAIEmbeddings( + api_key=os.environ["GITHUB_TOKEN"], + base_url="https://models.github.ai/inference", + model="text-embedding-3-small" +) + +# Load and split documents +loader = TextLoader("documentation.txt") +documents = loader.load() + +text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) +texts = text_splitter.split_documents(documents) + +# Create vector store +vectorstore = FAISS.from_documents(texts, embeddings) + +# Perform similarity search +query = "How do I handle user authentication?" +similar_docs = vectorstore.similarity_search(query, k=3) + +for doc in similar_docs: + print(f"Relevant content: {doc.page_content[:200]}...") +``` + +### Document loaders for various formats + +```python +from langchain_community.document_loaders import ( + PyPDFLoader, + CSVLoader, + JSONLoader, + WebBaseLoader +) + +# Load different document types +pdf_loader = PyPDFLoader("manual.pdf") +csv_loader = CSVLoader("data.csv") +json_loader = JSONLoader("config.json") +web_loader = WebBaseLoader("https://example.com/docs") + +# Process all documents +all_documents = [] +for loader in [pdf_loader, csv_loader, json_loader, web_loader]: + docs = loader.load() + all_documents.extend(docs) +``` + +**What you can do with embeddings:** +- **Build** search that actually understands what you mean, not just keyword matching +- **Create** AI that can answer questions about your documents +- **Make** recommendation systems that suggest truly relevant content +- **Automatically** organize and categorize your content + +## Building a complete AI application + +Now we'll integrate everything you've learned into a comprehensive application - a coding assistant that can answer questions, use tools, and maintain conversation memory. Like how the printing press combined existing technologies (movable type, ink, paper, and pressure) into something transformative, we'll combine our AI components into something practical and useful. -vectorize content, compare via cosine similarity +### Complete application example + +```python +from langchain_openai import ChatOpenAI, OpenAIEmbeddings +from langchain_core.prompts import ChatPromptTemplate +from langchain_core.messages import HumanMessage, SystemMessage, AIMessage +from langchain_community.vectorstores import FAISS +from typing_extensions import Annotated, TypedDict +import os +import requests + +class CodingAssistant: + def __init__(self): + self.llm = ChatOpenAI( + api_key=os.environ["GITHUB_TOKEN"], + base_url="https://models.github.ai/inference", + model="openai/gpt-4o-mini" + ) + + self.conversation_history = [ + SystemMessage(content="""You are an expert coding assistant. + Help users learn programming concepts, debug code, and write better software. + Use tools when needed and maintain a helpful, encouraging tone.""") + ] + + # Define tools + self.setup_tools() + + def setup_tools(self): + class web_search(TypedDict): + """Search for programming documentation or examples.""" + query: Annotated[str, "Search query for programming help"] + + class code_formatter(TypedDict): + """Format and validate code snippets.""" + code: Annotated[str, "Code to format"] + language: Annotated[str, "Programming language"] + + self.tools = [web_search, code_formatter] + self.llm_with_tools = self.llm.bind_tools(self.tools) + + def chat(self, user_input: str): + # Add user message to conversation + self.conversation_history.append(HumanMessage(content=user_input)) + + # Get AI response + response = self.llm_with_tools.invoke(self.conversation_history) + + # Handle tool calls if any + if response.tool_calls: + for tool_call in response.tool_calls: + tool_result = self.execute_tool(tool_call) + print(f"🔧 Tool used: {tool_call['name']}") + print(f"📊 Result: {tool_result}") + + # Add AI response to conversation + self.conversation_history.append(response) + + return response.content + + def execute_tool(self, tool_call): + tool_name = tool_call['name'] + args = tool_call['args'] + + if tool_name == 'web_search': + return f"Found documentation for: {args['query']}" + elif tool_name == 'code_formatter': + return f"Formatted {args['language']} code: {args['code'][:50]}..." + + return "Tool execution completed" + +# Usage example +assistant = CodingAssistant() + +print("🤖 Coding Assistant Ready! Type 'quit' to exit.\n") + +while True: + user_input = input("You: ") + if user_input.lower() == 'quit': + break + + response = assistant.chat(user_input) + print(f"🤖 Assistant: {response}\n") +``` + +**Application architecture:** + +```mermaid +graph TD + A[User Input] --> B[Coding Assistant] + B --> C[Conversation Memory] + B --> D[Tool Detection] + B --> E[LLM Processing] + + D --> F[Web Search Tool] + D --> G[Code Formatter Tool] + + E --> H[Response Generation] + F --> H + G --> H + + H --> I[User Interface] + H --> C +``` -https://python.langchain.com/docs/how_to/embed_text/ +**Key features we've implemented:** +- **Remembers** your entire conversation for context continuity +- **Performs actions** through tool calling, not just conversation +- **Follows** predictable interaction patterns +- **Manages** error handling and complex workflows automatically -### document loaders +## Assignment: Build your own AI-powered study assistant -pdf and csv +**Objective**: Create an AI application that helps students learn programming concepts by providing explanations, code examples, and interactive quizzes. -## Building an app +### Requirements -TODO +**Core Features (Required):** +1. **Conversational Interface**: Implement a chat system that maintains context across multiple questions +2. **Educational Tools**: Create at least two tools that help with learning: + - Code explanation tool + - Concept quiz generator +3. **Personalized Learning**: Use system messages to adapt responses to different skill levels +4. **Response Formatting**: Implement structured output for quiz questions -## Assignment +### Implementation Steps + +**Step 1: Setup your environment** +```bash +pip install langchain langchain-openai +``` + +**Step 2: Basic chat functionality** +- Create a `StudyAssistant` class +- Implement conversation memory +- Add personality configuration for educational support + +**Step 3: Add educational tools** +- **Code Explainer**: Breaks down code into understandable parts +- **Quiz Generator**: Creates questions about programming concepts +- **Progress Tracker**: Keeps track of topics covered + +**Step 4: Enhanced features (Optional)** +- Implement streaming responses for better user experience +- Add document loading to incorporate course materials +- Create embeddings for similarity-based content retrieval + +### Evaluation Criteria + +| Feature | Excellent (4) | Good (3) | Satisfactory (2) | Needs Work (1) | +|---------|---------------|----------|------------------|----------------| +| **Conversation Flow** | Natural, context-aware responses | Good context retention | Basic conversation | No memory between exchanges | +| **Tool Integration** | Multiple useful tools working seamlessly | 2+ tools implemented correctly | 1-2 basic tools | Tools not functional | +| **Code Quality** | Clean, well-documented, error handling | Good structure, some documentation | Basic functionality works | Poor structure, no error handling | +| **Educational Value** | Truly helpful for learning, adaptive | Good learning support | Basic explanations | Limited educational benefit | + +### Sample code structure + +```python +class StudyAssistant: + def __init__(self, skill_level="beginner"): + # Initialize LLM, tools, and conversation memory + pass + + def explain_code(self, code, language): + # Tool: Explain how code works + pass + + def generate_quiz(self, topic, difficulty): + # Tool: Create practice questions + pass + + def chat(self, user_input): + # Main conversation interface + pass + +# Example usage +assistant = StudyAssistant(skill_level="intermediate") +response = assistant.chat("Explain how Python functions work") +``` + +**Bonus Challenges:** +- Add voice input/output capabilities +- Implement a web interface using Streamlit or Flask +- Create a knowledge base from course materials using embeddings +- Add progress tracking and personalized learning paths ## Summary + +🎉 You've now mastered the fundamentals of AI framework development and learned how to build sophisticated AI applications using LangChain. Like completing a comprehensive apprenticeship, you've acquired a substantial toolkit of skills. Let's review what you've accomplished. + +### What you've learned + +**Core Framework Concepts:** +- **Framework Benefits**: Understanding when to choose frameworks over direct API calls +- **LangChain Basics**: Setting up and configuring AI model connections +- **Message Types**: Using `SystemMessage`, `HumanMessage`, and `AIMessage` for structured conversations + +**Advanced Features:** +- **Tool Calling**: Creating and integrating custom tools for enhanced AI capabilities +- **Conversation Memory**: Maintaining context across multiple conversation turns +- **Streaming Responses**: Implementing real-time response delivery +- **Prompt Templates**: Building reusable, dynamic prompts +- **Structured Output**: Ensuring consistent, parseable AI responses +- **Embeddings**: Creating semantic search and document processing capabilities + +**Practical Applications:** +- **Building Complete Apps**: Combining multiple features into production-ready applications +- **Error Handling**: Implementing robust error management and validation +- **Tool Integration**: Creating custom tools that extend AI capabilities + +### Key takeaways + +> 🎯 **Remember**: AI frameworks like LangChain are basically your complexity-hiding, feature-packed best friends. They're perfect when you need conversation memory, tool calling, or want to work with multiple AI models without losing your sanity. + +**Decision framework for AI integration:** + +```mermaid +flowchart TD + A[AI Integration Need] --> B{Simple single query?} + B -->|Yes| C[Direct API calls] + B -->|No| D{Need conversation memory?} + D -->|No| E[SDK Integration] + D -->|Yes| F{Need tools or complex features?} + F -->|No| G[Framework with basic setup] + F -->|Yes| H[Full framework implementation] + + C --> I[HTTP requests, minimal dependencies] + E --> J[Provider SDK, model-specific] + G --> K[LangChain basic chat] + H --> L[LangChain with tools, memory, agents] +``` + +### Where do you go from here? + +**Start building right now:** +- Take these concepts and build something that excites YOU! +- Play around with different AI models through LangChain - it's like having a playground of AI models +- Create tools that solve actual problems you face in your work or projects + +**Ready for the next level?** +- **AI Agents**: Build AI systems that can actually plan and execute complex tasks on their own +- **RAG (Retrieval-Augmented Generation)**: Combine AI with your own knowledge bases for super-powered applications +- **Multi-Modal AI**: Work with text, images, and audio all together - the possibilities are endless! +- **Production Deployment**: Learn how to scale your AI apps and monitor them in the real world + +**Join the community:** +- The LangChain community is fantastic for staying up-to-date and learning best practices +- GitHub Models gives you access to cutting-edge AI capabilities - perfect for experimenting +- Keep practicing with different use cases - each project will teach you something new + +You now have the knowledge to build intelligent, conversational applications that can help people solve real problems. Like the Renaissance craftsmen who combined artistic vision with technical skill, you can now merge AI capabilities with practical application. The question is: what will you create? 🚀 + +## GitHub Copilot Agent Challenge 🚀 + +Use the Agent mode to complete the following challenge: + +**Description:** Build an advanced AI-powered code review assistant that combines multiple LangChain features including tool calling, structured output, and conversation memory to provide comprehensive feedback on code submissions. + +**Prompt:** Create a CodeReviewAssistant class that implements: +1. A tool for analyzing code complexity and suggesting improvements +2. A tool for checking code against best practices +3. Structured output using Pydantic models for consistent review format +4. Conversation memory to track review sessions +5. A main chat interface that can handle code submissions and provide detailed, actionable feedback + +The assistant should be able to review code in multiple programming languages, maintain context across multiple code submissions in a session, and provide both summary scores and detailed improvement suggestions. + +Learn more about [agent mode](https://code.visualstudio.com/blogs/2025/02/24/introducing-copilot-agent-mode) here. diff --git a/2-js-basics/1-data-types/README.md b/2-js-basics/1-data-types/README.md index e7ada0bf..d1c9bef4 100644 --- a/2-js-basics/1-data-types/README.md +++ b/2-js-basics/1-data-types/README.md @@ -3,6 +3,12 @@ ![JavaScript Basics - Data types](../../sketchnotes/webdev101-js-datatypes.png) > Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac) +Data types are one of the fundamental concepts in JavaScript that you'll encounter in every program you write. Think of data types like the filing system used by ancient librarians in Alexandria – they had specific places for scrolls containing poetry, mathematics, and historical records. JavaScript organizes information in a similar way with different categories for different kinds of data. + +In this lesson, we'll explore the core data types that make JavaScript work. You'll learn how to handle numbers, text, true/false values, and understand why choosing the correct type is essential for your programs. These concepts might seem abstract at first, but with practice, they'll become second nature. + +Understanding data types will make everything else in JavaScript much clearer. Just as architects need to understand different building materials before constructing a cathedral, these fundamentals will support everything you build going forward. + ## Pre-Lecture Quiz [Pre-lecture quiz](https://ff-quizzes.netlify.app/web/) @@ -17,108 +23,163 @@ This lesson covers the basics of JavaScript, the language that provides interact > 🎥 Click the images above for videos about variables and data types Let's start with variables and the data types that populate them! + ## Variables -Variables store values that can be used and changed throughout your code. +Variables are fundamental building blocks in programming. Like the labeled jars that medieval alchemists used to store different substances, variables let you store information and give it a descriptive name so you can reference it later. Need to remember someone's age? Store it in a variable called `age`. Want to track a user's name? Keep it in a variable called `userName`. + +We'll focus on the modern approach to creating variables in JavaScript. The techniques you'll learn here represent years of language evolution and best practices developed by the programming community. Creating and **declaring** a variable has the following syntax **[keyword] [name]**. It's made up of the two parts: -- **Keyword**. Keywords can be `let` or `var`. +- **Keyword**. Use `let` for variables that can change, or `const` for values that stay the same. +- **The variable name**, this is a descriptive name you choose yourself. -✅ The keyword `let` was introduced in ES6 and gives your variable a so called _block scope_. It's recommended that you use `let` over `var`. We will cover block scopes more in depth in future parts. -- **The variable name**, this is a name you choose yourself. +✅ The keyword `let` was introduced in ES6 and gives your variable a so called _block scope_. It's recommended that you use `let` or `const` instead of the older `var` keyword. We will cover block scopes more in depth in future parts. ### Task - working with variables -1. **Declare a variable**. Let's declare a variable using the `let` keyword: +1. **Declare a variable**. Let's start by creating our first variable: ```javascript let myVariable; ``` - `myVariable` has now been declared using the `let` keyword. It currently doesn't have a value. + **What this accomplishes:** + - This tells JavaScript to create a storage location called `myVariable` + - JavaScript allocates space in memory for this variable + - The variable currently has no value (undefined) -1. **Assign a value**. Store a value in a variable with the `=` operator, followed by the expected value. +2. **Give it a value**. Now let's put something in our variable: ```javascript myVariable = 123; ``` - > Note: the use of `=` in this lesson means we make use of an "assignment operator", used to set a value to a variable. It doesn't denote equality. + **How assignment works:** + - The `=` operator assigns the value 123 to our variable + - The variable now contains this value instead of being undefined + - You can reference this value throughout your code using `myVariable` - `myVariable` has now been *initialized* with the value 123. + > Note: the use of `=` in this lesson means we make use of an "assignment operator", used to set a value to a variable. It doesn't denote equality. -1. **Refactor**. Replace your code with the following statement. +3. **Do it the smart way**. Actually, let's combine those two steps: ```javascript let myVariable = 123; ``` - The above is called an _explicit initialization_ when a variable is declared and is assigned a value at the same time. + **This approach is more efficient:** + - You're declaring the variable and assigning a value in one statement + - This is the standard practice among developers + - It reduces code length while maintaining clarity -1. **Change the variable value**. Change the variable value in the following way: +4. **Change your mind**. What if we want to store a different number? ```javascript myVariable = 321; ``` - Once a variable is declared, you can change its value at any point in your code with the `=` operator and the new value. + **Understanding reassignment:** + - The variable now contains 321 instead of 123 + - The previous value is replaced – variables store only one value at a time + - This mutability is the key characteristic of variables declared with `let` ✅ Try it! You can write JavaScript right in your browser. Open a browser window and navigate to Developer Tools. In the console, you will find a prompt; type `let myVariable = 123`, press return, then type `myVariable`. What happens? Note, you'll learn more about these concepts in subsequent lessons. ## Constants +Sometimes you need to store information that should never change during program execution. Think of constants like the mathematical principles that Euclid established in ancient Greece – once proven and documented, they remained fixed for all future reference. + +Constants work similarly to variables, but with an important restriction: once you assign their value, it cannot be changed. This immutability helps prevent accidental modifications to critical values in your program. + Declaration and initialization of a constant follows the same concepts as a variable, with the exception of the `const` keyword. Constants are typically declared with all uppercase letters. ```javascript const MY_VARIABLE = 123; ``` -Constants are similar to variables, with two exceptions: +**Here's what this code does:** +- **Creates** a constant named `MY_VARIABLE` with the value 123 +- **Uses** uppercase naming convention for constants +- **Prevents** any future changes to this value + +Constants have two main rules: + +- **You must give them a value right away** – no empty constants allowed! +- **You can never change that value** – JavaScript will throw an error if you try. Let's see what I mean: -- **Must have a value**. Constants must be initialized, or an error will occur when running code. -- **Reference cannot be changed**. The reference of a constant cannot be changed once initialized, or an error will occur when running code. Let's look at two examples: - - **Simple value**. The following is NOT allowed: + **Simple value** - The following is NOT allowed: ```javascript const PI = 3; PI = 4; // not allowed ``` + + **What you need to remember:** + - **Attempts** to reassign a constant will cause an error + - **Protects** important values from accidental changes + - **Ensures** the value remains consistent throughout your program - - **Object reference is protected**. The following is NOT allowed. + **Object reference is protected** - The following is NOT allowed: ```javascript const obj = { a: 3 }; obj = { b: 5 } // not allowed ``` - - **Object value is not protected**. The following IS allowed: + **Understanding these concepts:** + - **Prevents** replacing the entire object with a new one + - **Protects** the reference to the original object + - **Maintains** the object's identity in memory + + **Object value is not protected** - The following IS allowed: ```javascript const obj = { a: 3 }; obj.a = 5; // allowed ``` - Above you are changing the value of the object but not the reference itself, which makes it allowed. + **Breaking down what happens here:** + - **Modifies** the property value inside the object + - **Keeps** the same object reference + - **Demonstrates** that object contents can change while the reference stays constant > Note, a `const` means the reference is protected from reassignment. The value is not _immutable_ though and can change, especially if it's a complex construct like an object. ## Data Types +JavaScript organizes information into different categories called data types. This concept mirrors how ancient scholars categorized knowledge – Aristotle distinguished between different types of reasoning, knowing that logical principles couldn't be applied uniformly to poetry, mathematics, and natural philosophy. + +Data types matter because different operations work with different kinds of information. Just as you can't perform arithmetic on a person's name or alphabetize a mathematical equation, JavaScript requires the appropriate data type for each operation. Understanding this prevents errors and makes your code more reliable. + Variables can store many different types of values, like numbers and text. These various types of values are known as the **data type**. Data types are an important part of software development because it helps developers make decisions on how the code should be written and how the software should run. Furthermore, some data types have unique features that help transform or extract additional information in a value. ✅ Data Types are also referred to as JavaScript data primitives, as they are the lowest-level data types that are provided by the language. There are 7 primitive data types: string, number, bigint, boolean, undefined, null and symbol. Take a minute to visualize what each of these primitives might represent. What is a `zebra`? How about `0`? `true`? ### Numbers -In the previous section, the value of `myVariable` was a number data type. +Numbers are the most straightforward data type in JavaScript. Whether you're working with whole numbers like 42, decimals like 3.14, or negative numbers like -5, JavaScript handles them uniformly. + +Remember our variable from earlier? That 123 we stored was actually a number data type: -`let myVariable = 123;` +```javascript +let myVariable = 123; +``` + +**Key characteristics:** +- JavaScript automatically recognizes numeric values +- You can perform mathematical operations with these variables +- No explicit type declaration is required Variables can store all types of numbers, including decimals or negative numbers. Numbers also can be used with arithmetic operators, covered in the [next section](#arithmetic-operators). ### Arithmetic Operators +Arithmetic operators allow you to perform mathematical calculations in JavaScript. These operators follow the same principles mathematicians have used for centuries – the same symbols that appeared in the works of scholars like Al-Khwarizmi, who developed algebraic notation. + +The operators work as you would expect from traditional mathematics: plus for addition, minus for subtraction, and so forth. + There are several types of operators to use when performing arithmetic functions, and some are listed here: | Symbol | Description | Example | @@ -133,17 +194,31 @@ There are several types of operators to use when performing arithmetic functions ### Strings +In JavaScript, textual data is represented as strings. The term "string" comes from the concept of characters strung together in sequence, much like the way scribes in medieval monasteries would connect letters to form words and sentences in their manuscripts. + +Strings are fundamental to web development. Every piece of text displayed on a website – usernames, button labels, error messages, content – is handled as string data. Understanding strings is essential for creating functional user interfaces. + Strings are sets of characters that reside between single or double quotes. -- `'This is a string'` -- `"This is also a string"` -- `let myString = 'This is a string value stored in a variable';` +```javascript +'This is a string' +"This is also a string" +let myString = 'This is a string value stored in a variable'; +``` + +**Understanding these concepts:** +- **Uses** either single quotes `'` or double quotes `"` to define strings +- **Stores** text data that can include letters, numbers, and symbols +- **Assigns** string values to variables for later use +- **Requires** quotes to distinguish text from variable names Remember to use quotes when writing a string, or else JavaScript will assume it's a variable name. ### Formatting Strings -Strings are textual, and will require formatting from time to time. +String manipulation allows you to combine text elements, incorporate variables, and create dynamic content that responds to program state. This technique enables you to construct text programmatically. + +Often you need to join multiple strings together – this process is called concatenation. To **concatenate** two or more strings, or join them together, use the `+` operator. @@ -154,9 +229,14 @@ let myString2 = "World"; myString1 + myString2 + "!"; //HelloWorld! myString1 + " " + myString2 + "!"; //Hello World! myString1 + ", " + myString2 + "!"; //Hello, World! - ``` +**Step by step, here's what's happening:** +- **Combines** multiple strings using the `+` operator +- **Joins** strings directly together without spaces in the first example +- **Adds** space characters `" "` between strings for readability +- **Inserts** punctuation like commas to create proper formatting + ✅ Why does `1 + 1 = 2` in JavaScript, but `'1' + '1' = 11?` Think about it. What about `'1' + 1`? **Template literals** are another way to format strings, except instead of quotes, the backtick is used. Anything that is not plain text must be placed inside placeholders `${ }`. This includes any variables that may be strings. @@ -169,24 +249,54 @@ let myString2 = "World"; `${myString1}, ${myString2}!` //Hello, World! ``` +**Let's understand each part:** +- **Uses** backticks `` ` `` instead of regular quotes to create template literals +- **Embeds** variables directly using `${}` placeholder syntax +- **Preserves** spaces and formatting exactly as written +- **Provides** a cleaner way to create complex strings with variables + You can achieve your formatting goals with either method, but template literals will respect any spaces and line breaks. ✅ When would you use a template literal vs. a plain string? ### Booleans +Booleans represent the simplest form of data: they can only hold one of two values – `true` or `false`. This binary logic system traces back to the work of George Boole, a 19th-century mathematician who developed Boolean algebra. + +Despite their simplicity, booleans are essential for program logic. They enable your code to make decisions based on conditions – whether a user is logged in, if a button was clicked, or if certain criteria are met. + Booleans can be only two values: `true` or `false`. Booleans can help make decisions on which lines of code should run when certain conditions are met. In many cases, [operators](#arithmetic-operators) assist with setting the value of a Boolean and you will often notice and write variables being initialized or their values being updated with an operator. -- `let myTrueBool = true` -- `let myFalseBool = false` +```javascript +let myTrueBool = true; +let myFalseBool = false; +``` + +**In the above, we've:** +- **Created** a variable that stores the Boolean value `true` +- **Demonstrated** how to store the Boolean value `false` +- **Used** the exact keywords `true` and `false` (no quotes needed) +- **Prepared** these variables for use in conditional statements ✅ A variable can be considered 'truthy' if it evaluates to a boolean `true`. Interestingly, in JavaScript, [all values are truthy unless defined as falsy](https://developer.mozilla.org/docs/Glossary/Truthy). --- +## GitHub Copilot Agent Challenge 🚀 + +Use the Agent mode to complete the following challenge: + +**Description:** Create a personal information manager that demonstrates all the JavaScript data types you've learned in this lesson while handling real-world data scenarios. + +**Prompt:** Build a JavaScript program that creates a user profile object containing: a person's name (string), age (number), is a student status (boolean), favorite colors as an array, and an address object with street, city, and zip code properties. Include functions to display the profile information and update individual fields. Make sure to demonstrate string concatenation, template literals, arithmetic operations with the age, and boolean logic for the student status. + +Learn more about [agent mode](https://code.visualstudio.com/blogs/2025/02/24/introducing-copilot-agent-mode) here. + ## 🚀 Challenge -JavaScript is notorious for its surprising ways of handling datatypes on occasion. Do a bit of research on these 'gotchas'. For example: case sensitivity can bite! Try this in your console: `let age = 1; let Age = 2; age == Age` (resolves `false` -- why?). What other gotchas can you find? +JavaScript has some behaviors that can catch developers off guard. Here's a classic example to explore: try typing this in your browser console: `let age = 1; let Age = 2; age == Age` and observe the result. It returns `false` – can you determine why? + +This represents one of many JavaScript behaviors worth understanding. Familiarity with these quirks will help you write more reliable code and debug issues more effectively. ## Post-Lecture Quiz [Post-lecture quiz](https://ff-quizzes.netlify.app) diff --git a/2-js-basics/1-data-types/assignment.md b/2-js-basics/1-data-types/assignment.md index 30c25550..f5f00cc9 100644 --- a/2-js-basics/1-data-types/assignment.md +++ b/2-js-basics/1-data-types/assignment.md @@ -1,11 +1,87 @@ -# Data Types Practice +# Data Types Practice: E-commerce Shopping Cart ## Instructions -Imagine you are building a shopping cart. Write documentation on the data types you would need to complete your shopping experience. For each data type, explain how and why you would use it, and provide an example. The six JavaScript data types are: String, Number, Boolean, Null, Undefined, and Object. +Imagine you are building a modern e-commerce shopping cart system. This assignment will help you understand how different JavaScript data types work together to create real-world applications. + +### Your Task + +Create a comprehensive analysis of how you would use JavaScript data types in a shopping cart application. For each of the seven primitive data types and objects, you need to: + +1. **Identify** the data type and its purpose +2. **Explain** why this data type is the best choice for specific shopping cart features +3. **Provide** realistic code examples showing the data type in action +4. **Describe** how this data type interacts with other parts of the shopping cart + +### Required Data Types to Cover + +**Primitive Data Types:** +- **String**: Product names, descriptions, user information +- **Number**: Prices, quantities, tax calculations +- **Boolean**: Item availability, user preferences, cart status +- **Null**: Intentionally empty values (like missing discount codes) +- **Undefined**: Uninitialized values or missing data +- **Symbol**: Unique identifiers (advanced use) +- **BigInt**: Large financial calculations (advanced use) + +**Reference Types:** +- **Object**: Product details, user profiles, cart contents +- **Array**: List of products, order history, categories + +### Example Format for Each Data Type + +For each data type, structure your response like this: + +```markdown +## [Data Type Name] + +**Purpose in Shopping Cart:** [Explain what this data type does] + +**Why This Type:** [Explain why this is the best choice] + +**Code Example:** +```javascript +// Your realistic code example here +``` + +**Real-world Usage:** [Describe how this would work in practice] + +**Interactions:** [Explain how this data type works with others] +``` + +### Bonus Challenges + +1. **Type Coercion**: Show an example where JavaScript automatically converts between data types in your shopping cart (e.g., string "5" + number 10) + +2. **Data Validation**: Demonstrate how you would check if user input is the correct data type before processing + +3. **Performance Considerations**: Explain when you might choose one data type over another for performance reasons + +### Submission Guidelines + +- Create a markdown document with clear headings for each data type +- Include working JavaScript code examples +- Use realistic e-commerce scenarios in your examples +- Explain your reasoning clearly for beginners to understand +- Test your code examples to ensure they work correctly ## Rubric -Criteria | Exemplary | Adequate | Needs Improvement ---- | --- | --- | -- | -Data Types | All six data types are listed, explored in detail, and documented with examples | Four data types are explored with some explanation | Two data types are explored with minimal explanation | \ No newline at end of file +| Criteria | Exemplary (90-100%) | Proficient (80-89%) | Developing (70-79%) | Needs Improvement (Below 70%) | +|----------|---------------------|---------------------|---------------------|------------------------------| +| **Data Type Coverage** | All 7 primitive types and objects/arrays covered with detailed explanations | 6-7 data types covered with good explanations | 4-5 data types covered with basic explanations | Fewer than 4 data types or minimal explanations | +| **Code Examples** | All examples are realistic, working, and well-commented | Most examples work and are relevant to e-commerce | Some examples work but may be generic | Code examples are incomplete or non-functional | +| **Real-world Application** | Clearly connects each data type to practical shopping cart features | Good connection to e-commerce scenarios | Some connection to shopping cart context | Limited real-world application demonstrated | +| **Technical Accuracy** | All technical information is correct and demonstrates deep understanding | Most technical information is accurate | Generally accurate with minor errors | Contains significant technical errors | +| **Communication** | Explanations are clear, beginner-friendly, and well-organized | Good explanations that are mostly clear | Explanations are understandable but may lack clarity | Explanations are unclear or poorly organized | +| **Bonus Elements** | Includes multiple bonus challenges with excellent execution | Includes one or more bonus challenges well done | Attempts bonus challenges with mixed success | No bonus challenges attempted | + +### Learning Objectives + +By completing this assignment, you will: +- ✅ **Understand** the seven JavaScript primitive data types and their uses +- ✅ **Apply** data types to real-world programming scenarios +- ✅ **Analyze** when to choose specific data types for different purposes +- ✅ **Create** working code examples that demonstrate data type usage +- ✅ **Explain** technical concepts in beginner-friendly language +- ✅ **Connect** fundamental programming concepts to practical applications \ No newline at end of file diff --git a/2-js-basics/2-functions-methods/README.md b/2-js-basics/2-functions-methods/README.md index 7707796f..d273ae73 100644 --- a/2-js-basics/2-functions-methods/README.md +++ b/2-js-basics/2-functions-methods/README.md @@ -6,7 +6,11 @@ ## Pre-Lecture Quiz [Pre-lecture quiz](https://ff-quizzes.netlify.app) -When we think about writing code, we always want to ensure our code is readable. While this sounds counterintuitive, code is read many more times than it's written. One core tool in a developer's toolbox to ensure maintainable code is the **function**. +Writing the same code repeatedly is one of programming's most common frustrations. Functions solve this problem by letting you package code into reusable blocks. Think of functions like the standardized parts that made Henry Ford's assembly line revolutionary – once you create a reliable component, you can use it wherever needed without rebuilding from scratch. + +Functions allow you to bundle pieces of code so you can reuse them throughout your program. Instead of copying and pasting the same logic everywhere, you can create a function once and call it whenever needed. This approach keeps your code organized and makes updates much easier. + +In this lesson, you'll learn how to create your own functions, pass information to them, and get useful results back. You'll discover the difference between functions and methods, learn modern syntax approaches, and see how functions can work with other functions. We'll build these concepts step by step. [![Methods and Functions](https://img.youtube.com/vi/XgKsD6Zwvlc/0.jpg)](https://youtube.com/watch?v=XgKsD6Zwvlc "Methods and Functions") @@ -16,13 +20,15 @@ When we think about writing code, we always want to ensure our code is readable. ## Functions -At its core, a function is a block of code we can execute on demand. This is perfect for scenarios where we need to perform the same task multiple times; rather than duplicating the logic in multiple locations (which would make it hard to update when the time comes), we can centralize it in one location, and call it whenever we need the operation performed - you can even call functions from other functions!. +A function is a self-contained block of code that performs a specific task. It encapsulates logic that you can execute whenever needed. + +Instead of writing the same code multiple times throughout your program, you can package it in a function and call that function whenever you need it. This approach keeps your code clean and makes updates much easier. Consider the maintenance challenge if you needed to change logic that was scattered across 20 different locations in your codebase. -Just as important is the ability to name a function. While this might seem trivial, the name provides a quick way of documenting a section of code. You could think of this as a label on a button. If I click on a button which reads "Cancel timer", I know it's going to stop running the clock. +Naming your functions descriptively is essential. A well-named function communicates its purpose clearly – when you see `cancelTimer()`, you immediately understand what it does, just as a clearly labeled button tells you exactly what will happen when you click it. ## Creating and calling a function -The syntax for a function looks like the following: +Let's examine how to create a function. The syntax follows a consistent pattern: ```javascript function nameOfFunction() { // function definition @@ -30,7 +36,13 @@ function nameOfFunction() { // function definition } ``` -If I wanted to create a function to display a greeting, it might look like this: +Let's break this down: +- The `function` keyword tells JavaScript "Hey, I'm creating a function!" +- `nameOfFunction` is where you give your function a descriptive name +- The parentheses `()` are where you can add parameters (we'll get to that soon) +- The curly braces `{}` contain the actual code that runs when you call the function + +Let's create a simple greeting function to see this in action: ```javascript function displayGreeting() { @@ -38,28 +50,34 @@ function displayGreeting() { } ``` -Whenever we want to call (or invoke) our function, we use the name of the function followed by `()`. It's worth noting the fact our function can be defined before or after we decide to call it; the JavaScript compiler will find it for you. +This function prints "Hello, world!" to the console. Once you've defined it, you can use it as many times as needed. + +To execute (or "call") your function, write its name followed by parentheses. JavaScript allows you to define your function before or after you call it – the JavaScript engine will handle the execution order. ```javascript // calling our function displayGreeting(); ``` -> **NOTE:** There is a special type of function known as a **method**, which you've already been using! In fact, we saw this in our demo above when we used `console.log`. What makes a method different from a function is a method is attached to an object (`console` in our example), while a function is free floating. You will hear many developers use these terms interchangeably. +When you run this line, it executes all the code inside your `displayGreeting` function, displaying "Hello, world!" in your browser's console. You can call this function repeatedly. + +> **Note:** You've been using **methods** throughout these lessons. `console.log()` is a method – essentially a function that belongs to the `console` object. The key difference is that methods are attached to objects, while functions stand independently. Many developers use these terms interchangeably in casual conversation. ### Function best practices -There are a handful of best practices to keep in mind when creating functions +Here are a few tips to help you write great functions: -- As always, use descriptive names so you know what the function will do -- Use **camelCasing** to combine words -- Keep your functions focused on a specific task +- Give your functions clear, descriptive names – your future self will thank you! +- Use **camelCasing** for multi-word names (like `calculateTotal` instead of `calculate_total`) +- Keep each function focused on doing one thing well ## Passing information to a function -To make a function more reusable you'll often want to pass information into it. If we consider our `displayGreeting` example above, it will only display **Hello, world!**. Not the most useful function one could create. If we want to make it a little more flexible, like allowing someone to specify the name of the person to greet, we can add a **parameter**. A parameter (also sometimes called an **argument**), is additional information sent to a function. +Our `displayGreeting` function is limited – it can only display "Hello, world!" for everyone. Parameters allow us to make functions more flexible and useful. -Parameters are listed in the definition part within parenthesis and are comma separated like so: +**Parameters** act like placeholders where you can insert different values each time you use the function. This way, the same function can work with different information on each call. + +You list parameters inside the parentheses when you define your function, separating multiple parameters with commas: ```javascript function name(param, param2, param3) { @@ -67,7 +85,9 @@ function name(param, param2, param3) { } ``` -We can update our `displayGreeting` to accept a name and have that displayed. +Each parameter acts like a placeholder – when someone calls your function, they'll provide actual values that get plugged into these spots. + +Let's update our greeting function to accept someone's name: ```javascript function displayGreeting(name) { @@ -76,16 +96,22 @@ function displayGreeting(name) { } ``` -When we want to call our function and pass in the parameter, we specify it in the parenthesis. +Notice how we're using backticks (`` ` ``) and `${}` to insert the name directly into our message – this is called a template literal, and it's a really handy way to build strings with variables mixed in. + +Now when we call our function, we can pass in any name: ```javascript displayGreeting('Christopher'); // displays "Hello, Christopher!" when run ``` +JavaScript takes the string `'Christopher'`, assigns it to the `name` parameter, and creates the personalized message "Hello, Christopher!" + ## Default values -We can make our function even more flexible by adding more parameters. But what if we don't want to require every value be specified? Keeping with our greeting example, we could leave name as required (we need to know who we're greeting), but we want to allow the greeting itself to be customized as desired. If someone doesn't want to customize it, we provide a default value instead. To provide a default value to a parameter, we set it much in the same way we set a value for a variable - `parameterName = 'defaultValue'`. To see a full example: +What if we want to make some parameters optional? That's where default values come in handy! + +Let's say we want people to be able to customize the greeting word, but if they don't specify one, we'll just use "Hello" as a fallback. You can set up default values by using the equals sign, just like setting a variable: ```javascript function displayGreeting(name, salutation='Hello') { @@ -93,7 +119,9 @@ function displayGreeting(name, salutation='Hello') { } ``` -When we call the function, we can then decide if we want to set a value for `salutation`. +Here, `name` is still required, but `salutation` has a backup value of `'Hello'` if no one provides a different greeting. + +Now we can call this function in two different ways: ```javascript displayGreeting('Christopher'); @@ -103,19 +131,23 @@ displayGreeting('Christopher', 'Hi'); // displays "Hi, Christopher" ``` +In the first call, JavaScript uses the default "Hello" since we didn't specify a salutation. In the second call, it uses our custom "Hi" instead. This flexibility makes functions adaptable to different scenarios. + ## Return values -Up until now the function we built will always output to the [console](https://developer.mozilla.org/docs/Web/API/console). Sometimes this can be exactly what we're looking for, especially when we create functions which will be calling other services. But what if I want to create a helper function to perform a calculation and provide the value back so I can use it elsewhere? +Our functions so far have just been printing messages to the console, but what if you want a function to calculate something and give you back the result? -We can do this by using a **return value**. A return value is returned by the function, and can be stored in a variable just the same as we could store a literal value such as a string or number. +That's where **return values** come in. Instead of just displaying something, a function can hand you back a value that you can store in a variable or use in other parts of your code. -If a function does return something then the keyword `return` is used. The `return` keyword expects a value or reference of what's being returned like so: +To send a value back, you use the `return` keyword followed by whatever you want to return: ```javascript return myVariable; -``` +``` -We could create a function to create a greeting message and return the value back to the caller +Here's something important: when a function hits a `return` statement, it immediately stops running and sends that value back to whoever called it. + +Let's modify our greeting function to return the message instead of printing it: ```javascript function createGreetingMessage(name) { @@ -124,19 +156,25 @@ function createGreetingMessage(name) { } ``` -When calling this function we'll store the value in a variable. This is much the same way we'd set a variable to a static value (like `const name = 'Christopher'`). +Now instead of printing the greeting, this function creates the message and hands it back to us. + +To use the returned value, we can store it in a variable just like any other value: ```javascript const greetingMessage = createGreetingMessage('Christopher'); ``` +Now `greetingMessage` contains "Hello, Christopher" and we can use it anywhere in our code – to display it on a webpage, include it in an email, or pass it to another function. + ## Functions as parameters for functions -As you progress in your programming career, you will come across functions which accept functions as parameters. This neat trick is commonly used when we don't know when something is going to occur or complete, but we know we need to perform an operation in response. +Functions can be passed as parameters to other functions. While this concept may seem complex initially, it's a powerful feature that enables flexible programming patterns. -As an example, consider [setTimeout](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout), which begins a timer and will execute code when it completes. We need to tell it what code we want to execute. Sounds like a perfect job for a function! +This pattern is super common when you want to say "when something happens, do this other thing." For example, "when the timer finishes, run this code" or "when the user clicks the button, call this function." -If you run the code below, after 3 seconds you'll see the message **3 seconds has elapsed**. +Let's look at `setTimeout`, which is a built-in function that waits a certain amount of time and then runs some code. We need to tell it what code to run – perfect use case for passing a function! + +Try this code – after 3 seconds, you'll see a message: ```javascript function displayDone() { @@ -146,13 +184,15 @@ function displayDone() { setTimeout(displayDone, 3000); ``` +Notice how we pass `displayDone` (without parentheses) to `setTimeout`. We're not calling the function ourselves – we're handing it over to `setTimeout` and saying "call this in 3 seconds." + ### Anonymous functions -Let's take another look at what we've built. We're creating a function with a name which will be used one time. As our application gets more complex, we can see ourselves creating a lot of functions which will only be called once. This isn't ideal. As it turns out, we don't always need to provide a name! +Sometimes you need a function for just one thing and don't want to give it a name. Think about it – if you're only using a function once, why clutter up your code with an extra name? -When we are passing a function as a parameter we can bypass creating one in advance and instead build one as part of the parameter. We use the same `function` keyword, but instead we build it as a parameter. +JavaScript lets you create **anonymous functions** – functions without names that you can define right where you need them. -Let's rewrite the code above to use an anonymous function: +Here's how we can rewrite our timer example using an anonymous function: ```javascript setTimeout(function() { @@ -160,13 +200,15 @@ setTimeout(function() { }, 3000); ``` -If you run our new code you'll notice we get the same results. We've created a function, but didn't have to give it a name! +This achieves the same result, but the function is defined directly within the `setTimeout` call, eliminating the need for a separate function declaration. ### Fat arrow functions -One shortcut common in a lot of programming languages (including JavaScript) is the ability to use what's called an **arrow** or **fat arrow** function. It uses a special indicator of `=>`, which looks like an arrow - thus the name! By using `=>`, we are able to skip the `function` keyword. +Modern JavaScript has an even shorter way to write functions called **arrow functions**. They use `=>` (which looks like an arrow – get it?) and are super popular with developers. + +Arrow functions let you skip the `function` keyword and write more concise code. -Let's rewrite our code one more time to use a fat arrow function: +Here's our timer example using an arrow function: ```javascript setTimeout(() => { @@ -174,9 +216,11 @@ setTimeout(() => { }, 3000); ``` +The `()` is where parameters would go (empty in this case), then comes the arrow `=>`, and finally the function body in curly braces. This provides the same functionality with more concise syntax. + ### When to use each strategy -You've now seen we have three ways to pass a function as a parameter and might be wondering when to use each. If you know you'll be using the function more than once, create it as normal. If you'll be using it for just the one location, it's generally best to use an anonymous function. Whether or not you use a fat arrow function or the more traditional `function` syntax is up to you, but you will notice most modern developers prefer `=>`. +When should you use each approach? A practical guideline: if you'll use the function multiple times, give it a name and define it separately. If it's for one specific use, consider an anonymous function. Both arrow functions and traditional syntax are valid choices, though arrow functions are prevalent in modern JavaScript codebases. --- @@ -199,6 +243,8 @@ Use the Agent mode to complete the following challenge: 4. A function `calculate` that accepts another function as a parameter and two numbers, then applies the function to those numbers 5. Demonstrate calling each function with appropriate test cases +Learn more about [agent mode](https://code.visualstudio.com/blogs/2025/02/24/introducing-copilot-agent-mode) here. + ## Post-Lecture Quiz [Post-lecture quiz](https://ff-quizzes.netlify.app) diff --git a/2-js-basics/2-functions-methods/assignment.md b/2-js-basics/2-functions-methods/assignment.md index 4fbe387d..a1a88073 100644 --- a/2-js-basics/2-functions-methods/assignment.md +++ b/2-js-basics/2-functions-methods/assignment.md @@ -2,12 +2,65 @@ ## Instructions -Create different functions, both functions that return something and functions that don't return anything. +In this assignment, you'll practice creating different types of functions to reinforce the concepts you've learned about JavaScript functions, parameters, default values, and return statements. -See if you can create a function that has a mix of parameters and parameters with default values. +Create a JavaScript file called `functions-practice.js` and implement the following functions: + +### Part 1: Basic Functions +1. **Create a function called `sayHello`** that doesn't take any parameters and simply logs "Hello!" to the console. + +2. **Create a function called `introduceYourself`** that takes a `name` parameter and logs a message like "Hi, my name is [name]" to the console. + +### Part 2: Functions with Default Parameters +3. **Create a function called `greetPerson`** that takes two parameters: `name` (required) and `greeting` (optional, defaults to "Hello"). The function should log a message like "[greeting], [name]!" to the console. + +### Part 3: Functions that Return Values +4. **Create a function called `addNumbers`** that takes two parameters (`num1` and `num2`) and returns their sum. + +5. **Create a function called `createFullName`** that takes `firstName` and `lastName` parameters and returns the full name as a single string. + +### Part 4: Mix It All Together +6. **Create a function called `calculateTip`** that takes two parameters: `billAmount` (required) and `tipPercentage` (optional, defaults to 15). The function should calculate and return the tip amount. + +### Part 5: Test Your Functions +Add function calls to test each of your functions and display the results using `console.log()`. + +**Example test calls:** +```javascript +// Test your functions here +sayHello(); +introduceYourself("Sarah"); +greetPerson("Alex"); +greetPerson("Maria", "Hi"); + +const sum = addNumbers(5, 3); +console.log(`The sum is: ${sum}`); + +const fullName = createFullName("John", "Doe"); +console.log(`Full name: ${fullName}`); + +const tip = calculateTip(50); +console.log(`Tip for $50 bill: $${tip}`); +``` ## Rubric -| Criteria | Exemplary | Adequate | Needs Improvement | -| -------- | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ----------------- | -| | Solution is offered with two or more well-performing functions with diverse parameters | Working solution is offered with one function and few parameters | Solution has bugs | \ No newline at end of file +| Criteria | Exemplary | Adequate | Needs Improvement | +| -------- | --------- | -------- | ----------------- | +| **Function Creation** | All 6 functions are correctly implemented with proper syntax and naming conventions | 4-5 functions are correctly implemented with minor syntax issues | 3 or fewer functions implemented or major syntax errors | +| **Parameters & Default Values** | Correctly uses required parameters, optional parameters, and default values as specified | Uses parameters correctly but may have issues with default values | Incorrect or missing parameter implementation | +| **Return Values** | Functions that should return values do so correctly, and functions that shouldn't return values only perform actions | Most return values are correct with minor issues | Significant problems with return statements | +| **Code Quality** | Clean, well-organized code with meaningful variable names and proper indentation | Code works but could be cleaner or better organized | Code is difficult to read or poorly structured | +| **Testing** | All functions are tested with appropriate function calls and results are displayed clearly | Most functions are tested adequately | Limited or incorrect testing of functions | + +## Bonus Challenges (Optional) + +If you want to challenge yourself further: + +1. **Create an arrow function version** of one of your functions +2. **Create a function that accepts another function as a parameter** (like the `setTimeout` examples from the lesson) +3. **Add input validation** to ensure your functions handle invalid inputs gracefully + +--- + +> 💡 **Tip**: Remember to open your browser's developer console (F12) to see the output of your `console.log()` statements! \ No newline at end of file diff --git a/2-js-basics/3-making-decisions/README.md b/2-js-basics/3-making-decisions/README.md index e1a4c02e..c7f447a4 100644 --- a/2-js-basics/3-making-decisions/README.md +++ b/2-js-basics/3-making-decisions/README.md @@ -4,11 +4,17 @@ > Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac) +Have you ever wondered how applications make smart decisions? Like how a navigation system chooses the fastest route, or how a thermostat decides when to turn on the heat? This is the fundamental concept of decision-making in programming. + +Just as Charles Babbage's Analytical Engine was designed to follow different sequences of operations based on conditions, modern JavaScript programs need to make choices based on varying circumstances. This ability to branch and make decisions is what transforms static code into responsive, intelligent applications. + +In this lesson, you'll learn how to implement conditional logic in your programs. We'll explore conditional statements, comparison operators, and logical expressions that allow your code to evaluate situations and respond appropriately. + ## Pre-Lecture Quiz [Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/11) -Making decisions and controlling the order in which your code runs makes your code reusable and robust. This section covers the syntax for controlling data flow in JavaScript and its significance when used with Boolean data types +The ability to make decisions and control program flow is a fundamental aspect of programming. This section covers how to control the execution path of your JavaScript programs using Boolean values and conditional logic. [![Making Decisions](https://img.youtube.com/vi/SxTp8j-fMMY/0.jpg)](https://youtube.com/watch?v=SxTp8j-fMMY "Making Decisions") @@ -18,18 +24,26 @@ Making decisions and controlling the order in which your code runs makes your co ## A Brief Recap on Booleans -Booleans can have only two values: `true` or `false`. Booleans help make decisions on which lines of code should run when certain conditions are met. +Before exploring decision-making, let's revisit Boolean values from our previous lesson. Named after mathematician George Boole, these values represent binary states – either `true` or `false`. There's no ambiguity, no middle ground. + +These binary values form the foundation of all computational logic. Every decision your program makes ultimately reduces to a Boolean evaluation. -Set your boolean to be true or false like this: +Creating Boolean variables is straightforward: + +```javascript +let myTrueBool = true; +let myFalseBool = false; +``` -`let myTrueBool = true` -`let myFalseBool = false` +This creates two variables with explicit Boolean values. ✅ Booleans are named after the English mathematician, philosopher and logician George Boole (1815–1864). ## Comparison Operators and Booleans -Operators are used to evaluate conditions by making comparisons that will create a Boolean value. The following is a list of operators that are frequently used. +In practice, you'll rarely set Boolean values manually. Instead, you'll generate them by evaluating conditions: "Is this number greater than that one?" or "Are these values equal?" + +Comparison operators enable these evaluations. They compare values and return Boolean results based on the relationship between the operands. | Symbol | Description | Example | | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | @@ -44,48 +58,60 @@ Operators are used to evaluate conditions by making comparisons that will create ## If Statement -The if statement will run code in between its blocks if the condition is true. +The `if` statement is like asking a question in your code. "If this condition is true, then do this thing." It's probably the most important tool you'll use for making decisions in JavaScript. + +Here's how it works: ```javascript if (condition) { - //Condition is true. Code in this block will run. + // Condition is true. Code in this block will run. } ``` -Logical operators are often used to form the condition. +The condition goes inside the parentheses, and if it's `true`, JavaScript runs the code inside the curly braces. If it's `false`, JavaScript just skips that whole block. + +You'll often use comparison operators to create these conditions. Let's see a practical example: ```javascript -let currentMoney; -let laptopPrice; +let currentMoney = 1000; +let laptopPrice = 800; if (currentMoney >= laptopPrice) { - //Condition is true. Code in this block will run. + // Condition is true. Code in this block will run. console.log("Getting a new laptop!"); } ``` +Since `1000 >= 800` evaluates to `true`, the code inside the block executes, displaying "Getting a new laptop!" in the console. + ## If..Else Statement -The `else` statement will run the code in between its blocks when the condition is false. It's optional with an `if` statement. +But what if you want your program to do something different when the condition is false? That's where `else` comes in – it's like having a backup plan. + +The `else` statement gives you a way to say "if this condition isn't true, do this other thing instead." ```javascript -let currentMoney; -let laptopPrice; +let currentMoney = 500; +let laptopPrice = 800; if (currentMoney >= laptopPrice) { - //Condition is true. Code in this block will run. + // Condition is true. Code in this block will run. console.log("Getting a new laptop!"); } else { - //Condition is false. Code in this block will run. + // Condition is false. Code in this block will run. console.log("Can't afford a new laptop, yet!"); } ``` +Now since `500 >= 800` is `false`, JavaScript skips the first block and runs the `else` block instead. You'll see "Can't afford a new laptop, yet!" in the console. + ✅ Test your understanding of this code and the following code by running it in a browser console. Change the values of the currentMoney and laptopPrice variables to change the returned `console.log()`. ## Switch Statement -The `switch` statement is used to perform different actions based on different conditions. Use the `switch` statement to select one of many code blocks to be executed. +Sometimes you need to compare one value against multiple options. While you could chain several `if..else` statements, this approach becomes unwieldy. The `switch` statement provides a cleaner structure for handling multiple discrete values. + +The concept resembles the mechanical switching systems used in early telephone exchanges – one input value determines which specific path the execution follows. ```javascript switch (expression) { @@ -96,61 +122,83 @@ switch (expression) { // code block break; default: - // code block + // code block } ``` +Here's how it's structured: +- JavaScript evaluates the expression once +- It looks through each `case` to find a match +- When it finds a match, it runs that code block +- The `break` tells JavaScript to stop and exit the switch +- If no cases match, it runs the `default` block (if you have one) + ```javascript -// program using switch statement -let a = 2; +// Program using switch statement for day of week +let dayNumber = 2; +let dayName; -switch (a) { +switch (dayNumber) { case 1: - a = "one"; + dayName = "Monday"; break; case 2: - a = "two"; + dayName = "Tuesday"; + break; + case 3: + dayName = "Wednesday"; break; default: - a = "not found"; + dayName = "Unknown day"; break; } -console.log(`The value is ${a}`); +console.log(`Today is ${dayName}`); ``` +In this example, JavaScript sees that `dayNumber` is `2`, finds the matching `case 2`, sets `dayName` to "Tuesday", and then breaks out of the switch. The result? "Today is Tuesday" gets logged to the console. + ✅ Test your understanding of this code and the following code by running it in a browser console. Change the values of the variable a to change the returned `console.log()`. ## Logical Operators and Booleans -Decisions might require more than one comparison, and can be strung together with logical operators to produce a Boolean value. +Complex decisions often require evaluating multiple conditions simultaneously. Just as Boolean algebra allows mathematicians to combine logical expressions, programming provides logical operators to connect multiple Boolean conditions. + +These operators enable sophisticated conditional logic by combining simple true/false evaluations. | Symbol | Description | Example | | ------ | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | -| `&&` | **Logical AND**: Compares two Boolean expressions. Returns true **only** if both sides are true | `(5 > 6) && (5 < 6 ) //One side is false, other is true. Returns false` | -| `\|\|` | **Logical OR**: Compares two Boolean expressions. Returns true if at least one side is true | `(5 > 6) \|\| (5 < 6) //One side is false, other is true. Returns true` | -| `!` | **Logical NOT**: Returns the opposite value of a Boolean expression | `!(5 > 6) // 5 is not greater than 6, but "!" will return true` | +| `&&` | **Logical AND**: Compares two Boolean expressions. Returns true **only** if both sides are true | `(5 > 3) && (5 < 10) // Both sides are true. Returns true` | +| `\|\|` | **Logical OR**: Compares two Boolean expressions. Returns true if at least one side is true | `(5 > 10) \|\| (5 < 10) // One side is false, other is true. Returns true` | +| `!` | **Logical NOT**: Returns the opposite value of a Boolean expression | `!(5 > 10) // 5 is not greater than 10, so "!" makes it true` | + +These operators let you combine conditions in useful ways: +- AND (`&&`) means both conditions must be true +- OR (`||`) means at least one condition must be true +- NOT (`!`) flips true to false (and vice versa) ## Conditions and Decisions with Logical Operators -Logical operators can be used to form conditions in if..else statements. +Let's see these logical operators in action with a more realistic example: ```javascript -let currentMoney; -let laptopPrice; -let laptopDiscountPrice = laptopPrice - laptopPrice * 0.2; //Laptop price at 20 percent off +let currentMoney = 600; +let laptopPrice = 800; +let laptopDiscountPrice = laptopPrice - (laptopPrice * 0.2); // Laptop price at 20 percent off if (currentMoney >= laptopPrice || currentMoney >= laptopDiscountPrice) { - //Condition is true. Code in this block will run. + // Condition is true. Code in this block will run. console.log("Getting a new laptop!"); } else { - //Condition is true. Code in this block will run. + // Condition is false. Code in this block will run. console.log("Can't afford a new laptop, yet!"); } ``` -### Negation operator +In this example: we calculate a 20% discount price (640), then evaluate whether our available funds cover either the full price OR the discounted price. Since 600 meets the discounted price threshold of 640, the condition evaluates to true. -You've seen so far how you can use an `if...else` statement to create conditional logic. Anything that goes into an `if` needs to evaluate to true/false. By using the `!` operator you can _negate_ the expression. It would look like so: +### Negation Operator + +Sometimes it's easier to think about when something is NOT true. Like instead of asking "Is the user logged in?", you might want to ask "Is the user NOT logged in?" The exclamation mark (`!`) operator flips the logic for you. ```javascript if (!condition) { @@ -160,14 +208,18 @@ if (!condition) { } ``` -### Ternary expressions +The `!` operator is like saying "the opposite of..." – if something is `true`, `!` makes it `false`, and vice versa. + +### Ternary Expressions -`if...else` isn't the only way to express decision logic. You can also use something called a ternary operator. The syntax for it looks like this: +For simple conditional assignments, JavaScript provides the **ternary operator**. This concise syntax allows you to write a conditional expression in a single line, useful when you need to assign one of two values based on a condition. ```javascript -let variable = condition ? : +let variable = condition ? returnThisIfTrue : returnThisIfFalse; ``` +It reads like a question: "Is this condition true? If yes, use this value. If no, use that value." + Below is a more tangible example: ```javascript @@ -178,13 +230,9 @@ let biggestNumber = firstNumber > secondNumber ? firstNumber : secondNumber; ✅ Take a minute to read this code a few times. Do you understand how these operators are working? -The above states that +Here's what this line is saying: "Is `firstNumber` greater than `secondNumber`? If yes, put `firstNumber` in `biggestNumber`. If no, put `secondNumber` in `biggestNumber`." -- if `firstNumber` is larger than `secondNumber` -- then assign `firstNumber` to `biggestNumber` -- else assign `secondNumber`. - -The ternary expression is just a compact way of writing the code below: +The ternary operator is just a shorter way to write this traditional `if..else` statement: ```javascript let biggestNumber; @@ -195,6 +243,8 @@ if (firstNumber > secondNumber) { } ``` +Both approaches produce identical results. The ternary operator offers conciseness, while the traditional if-else structure may be more readable for complex conditions. + --- @@ -227,6 +277,8 @@ Requirements: Test your program with various scores including edge cases like 59, 60, 89, 90, and invalid inputs. +Learn more about [agent mode](https://code.visualstudio.com/blogs/2025/02/24/introducing-copilot-agent-mode) here. + ## Post-Lecture Quiz diff --git a/2-js-basics/3-making-decisions/assignment.md b/2-js-basics/3-making-decisions/assignment.md index 54c15533..7eea2b22 100644 --- a/2-js-basics/3-making-decisions/assignment.md +++ b/2-js-basics/3-making-decisions/assignment.md @@ -1,40 +1,104 @@ -# Operators +# Making Decisions: Student Grade Processor -## Instructions +## Learning Objectives -Play around with operators. Here's a suggestion for a program you can implement: +In this assignment, you'll practice the decision-making concepts from this lesson by building a program that processes student grades from different grading systems. You'll use `if...else` statements, comparison operators, and logical operators to determine which students pass their courses. -You have a set of students from two different grading systems. +## The Challenge -### First grading system +You work for a school that recently merged with another institution. Now you need to process student grades from two completely different grading systems and determine which students are passing. This is a perfect opportunity to practice conditional logic! -One grading system is defined as grades being from 1-5 where 3 and above means you pass the course. +### Understanding the Grading Systems -### Second grading system +#### First Grading System (Numeric) +- Grades are given as numbers from 1-5 +- **Passing grade**: 3 and above (3, 4, or 5) +- **Failing grade**: Below 3 (1 or 2) -The other grade system has the following grades `A, A-, B, B-, C, C-` where `A` is the top grade and `C` is the lowest passing grade. +#### Second Grading System (Letter Grades) +- Grades use letters: `A`, `A-`, `B`, `B-`, `C`, `C-` +- **Passing grades**: `A`, `A-`, `B`, `B-`, `C`, `C-` (all listed grades are passing) +- **Note**: This system doesn't include failing grades like `D` or `F` -### The task +### Your Task -Given the following array `allStudents` representing all students and their grades, construct a new array `studentsWhoPass` containing all students who pass. - -> TIP, use a for-loop and if...else and comparison operators: +Given the following array `allStudents` representing all students and their grades, construct a new array `studentsWhoPass` containing all students who pass according to their respective grading systems. ```javascript let allStudents = [ - 'A', - 'B-', - 1, - 4, - 5, - 2 -] + 'A', // Letter grade - passing + 'B-', // Letter grade - passing + 1, // Numeric grade - failing + 4, // Numeric grade - passing + 5, // Numeric grade - passing + 2 // Numeric grade - failing +]; let studentsWhoPass = []; ``` +### Step-by-Step Approach + +1. **Set up a loop** to go through each grade in the `allStudents` array +2. **Check the grade type** (is it a number or a string?) +3. **Apply the appropriate grading system rules**: + - For numbers: check if grade >= 3 + - For strings: check if it's one of the valid passing letter grades +4. **Add passing grades** to the `studentsWhoPass` array + +### Helpful Code Techniques + +Use these JavaScript concepts from the lesson: + +- **typeof operator**: `typeof grade === 'number'` to check if it's a numeric grade +- **Comparison operators**: `>=` to compare numeric grades +- **Logical operators**: `||` to check multiple letter grade conditions +- **if...else statements**: to handle different grading systems +- **Array methods**: `.push()` to add passing grades to your new array + +### Expected Output + +When you run your program, `studentsWhoPass` should contain: `['A', 'B-', 4, 5]` + +**Why these grades pass:** +- `'A'` and `'B-'` are valid letter grades (all letter grades in this system are passing) +- `4` and `5` are numeric grades >= 3 +- `1` and `2` fail because they're numeric grades < 3 + +## Testing Your Solution + +Test your code with different scenarios: + +```javascript +// Test with different grade combinations +let testGrades1 = ['A-', 3, 'C', 1, 'B']; +let testGrades2 = [5, 'A', 2, 'C-', 4]; + +// Your solution should work with any combination of valid grades +``` + +## Bonus Challenges + +Once you complete the basic assignment, try these extensions: + +1. **Add validation**: Check for invalid grades (like negative numbers or invalid letters) +2. **Count statistics**: Calculate how many students pass vs. fail +3. **Grade conversion**: Convert all grades to a single numeric system (A=5, B=4, C=3, etc.) + ## Rubric -| Criteria | Exemplary | Adequate | Needs Improvement | -| -------- | ------------------------------ | ----------------------------- | ------------------------------- | -| | Complete solution is presented | Partial solution is presented | Solution with bugs is presented | +| Criteria | Exemplary (4) | Proficient (3) | Developing (2) | Beginning (1) | +|----------|---------------|----------------|----------------|---------------| +| **Functionality** | Program correctly identifies all passing grades from both systems | Program works with minor issues or edge cases | Program partially works but has logical errors | Program has significant errors or doesn't run | +| **Code Structure** | Clean, well-organized code with proper if...else logic | Good structure with appropriate conditional statements | Acceptable structure with some organizational issues | Poor structure, difficult to follow logic | +| **Use of Concepts** | Effectively uses comparison operators, logical operators, and conditional statements | Good use of lesson concepts with minor gaps | Some use of lesson concepts but missing key elements | Limited use of lesson concepts | +| **Problem Solving** | Shows clear understanding of the problem and elegant solution approach | Good problem-solving approach with solid logic | Adequate problem-solving with some confusion | Unclear approach, doesn't demonstrate understanding | + +## Submission Guidelines + +1. **Test your code** thoroughly with the provided examples +2. **Add comments** explaining your logic, especially for the conditional statements +3. **Verify output** matches expected results: `['A', 'B-', 4, 5]` +4. **Consider edge cases** like empty arrays or unexpected data types + +> 💡 **Pro Tip**: Start simple! Get the basic functionality working first, then add more sophisticated features. Remember, the goal is to practice decision-making logic with the tools you learned in this lesson. diff --git a/2-js-basics/4-arrays-loops/README.md b/2-js-basics/4-arrays-loops/README.md index 778e3c03..9330e048 100644 --- a/2-js-basics/4-arrays-loops/README.md +++ b/2-js-basics/4-arrays-loops/README.md @@ -6,7 +6,11 @@ ## Pre-Lecture Quiz [Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/13) -This lesson covers the basics of JavaScript, the language that provides interactivity on the web. In this lesson, you'll learn about arrays and loops, which are used to manipulate data. +Ever wondered how websites keep track of shopping cart items or display your friend list? That's where arrays and loops come in. Arrays are like digital containers that hold multiple pieces of information, while loops let you work with all that data efficiently without repetitive code. + +Together, these two concepts form the foundation for handling information in your programs. You'll learn to move from manually writing out every single step to creating smart, efficient code that can process hundreds or even thousands of items quickly. + +By the end of this lesson, you'll understand how to accomplish complex data tasks with just a few lines of code. Let's explore these essential programming concepts. [![Arrays](https://img.youtube.com/vi/1U4qTyq02Xw/0.jpg)](https://youtube.com/watch?v=1U4qTyq02Xw "Arrays") @@ -18,102 +22,325 @@ This lesson covers the basics of JavaScript, the language that provides interact ## Arrays -Working with data is a common task for any language, and it's a much easier task when data is organized in a structural format, such as arrays. With arrays, data is stored in a structure similar to a list. One major benefit of arrays is that you can store different types of data in one array. +Think of arrays as a digital filing cabinet - instead of storing one document per drawer, you can organize multiple related items in a single, structured container. In programming terms, arrays let you store multiple pieces of information in one organized package. + +Whether you're building a photo gallery, managing a to-do list, or keeping track of high scores in a game, arrays provide the foundation for data organization. Let's see how they work. ✅ Arrays are all around us! Can you think of a real-life example of an array, such as a solar panel array? -The syntax for an array is a pair of square brackets. +### Creating Arrays + +Creating an array is super simple - just use square brackets! ```javascript -let myArray = []; +// Empty array - like an empty shopping cart waiting for items +const myArray = []; ``` -This is an empty array, but arrays can be declared already populated with data. Multiple values in an array are separated by a comma. +**What's happening here?** +You've just created an empty container using those square brackets `[]`. Think of it like an empty library shelf - it's ready to hold whatever books you want to organize there. + +You can also fill your array with initial values right from the start: ```javascript -let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"]; +// Your ice cream shop's flavor menu +const iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"]; + +// A user's profile info (mixing different types of data) +const userData = ["John", 25, true, "developer"]; + +// Test scores for your favorite class +const scores = [95, 87, 92, 78, 85]; ``` -The array values are assigned a unique value called the **index**, a whole number that is assigned based on its distance from the beginning of the array. In the example above, the string value "Chocolate" has an index of 0, and the index of "Rocky Road" is 4. Use the index with square brackets to retrieve, change, or insert array values. +**Cool things to notice:** +- You can store text, numbers, or even true/false values in the same array +- Just separate each item with a comma - easy! +- Arrays are perfect for keeping related information together + +### Array Indexing + +Here's something that might seem unusual at first: arrays number their items starting from 0, not 1. This zero-based indexing has its roots in how computer memory works - it's been a programming convention since the early days of computing languages like C. Each spot in the array gets its own address number called an **index**. + +| Index | Value | Description | +|-------|-------|-------------| +| 0 | "Chocolate" | First element | +| 1 | "Strawberry" | Second element | +| 2 | "Vanilla" | Third element | +| 3 | "Pistachio" | Fourth element | +| 4 | "Rocky Road" | Fifth element | ✅ Does it surprise you that arrays start at the zero index? In some programming languages, indexes start at 1. There's an interesting history around this, which you can [read on Wikipedia](https://en.wikipedia.org/wiki/Zero-based_numbering). +**Accessing Array Elements:** + ```javascript -let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"]; -iceCreamFlavors[2]; //"Vanilla" +const iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"]; + +// Access individual elements using bracket notation +console.log(iceCreamFlavors[0]); // "Chocolate" - first element +console.log(iceCreamFlavors[2]); // "Vanilla" - third element +console.log(iceCreamFlavors[4]); // "Rocky Road" - last element ``` -You can leverage the index to change a value, like this: +**Breaking down what happens here:** +- **Uses** square bracket notation with the index number to access elements +- **Returns** the value stored at that specific position in the array +- **Starts** counting from 0, making the first element index 0 + +**Modifying Array Elements:** ```javascript -iceCreamFlavors[4] = "Butter Pecan"; //Changed "Rocky Road" to "Butter Pecan" +// Change an existing value +iceCreamFlavors[4] = "Butter Pecan"; +console.log(iceCreamFlavors[4]); // "Butter Pecan" + +// Add a new element at the end +iceCreamFlavors[5] = "Cookie Dough"; +console.log(iceCreamFlavors[5]); // "Cookie Dough" ``` -And you can insert a new value at a given index like this: +**In the above, we've:** +- **Modified** the element at index 4 from "Rocky Road" to "Butter Pecan" +- **Added** a new element "Cookie Dough" at index 5 +- **Expanded** the array length automatically when adding beyond current bounds + +### Array Length and Common Methods + +Arrays come with built-in properties and methods that make working with data much easier. + +**Finding Array Length:** ```javascript -iceCreamFlavors[5] = "Cookie Dough"; //Added "Cookie Dough" +const iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"]; +console.log(iceCreamFlavors.length); // 5 + +// Length updates automatically as array changes +iceCreamFlavors.push("Mint Chip"); +console.log(iceCreamFlavors.length); // 6 ``` -✅ A more common way to push values to an array is by using array operators such as array.push() +**Key points to remember:** +- **Returns** the total number of elements in the array +- **Updates** automatically when elements are added or removed +- **Provides** a dynamic count useful for loops and validation -To find out how many items are in an array, use the `length` property. +**Essential Array Methods:** ```javascript -let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"]; -iceCreamFlavors.length; //5 +const fruits = ["apple", "banana", "orange"]; + +// Add elements +fruits.push("grape"); // Adds to end: ["apple", "banana", "orange", "grape"] +fruits.unshift("strawberry"); // Adds to beginning: ["strawberry", "apple", "banana", "orange", "grape"] + +// Remove elements +const lastFruit = fruits.pop(); // Removes and returns "grape" +const firstFruit = fruits.shift(); // Removes and returns "strawberry" + +// Find elements +const index = fruits.indexOf("banana"); // Returns 1 (position of "banana") +const hasApple = fruits.includes("apple"); // Returns true ``` +**Understanding these methods:** +- **Adds** elements with `push()` (end) and `unshift()` (beginning) +- **Removes** elements with `pop()` (end) and `shift()` (beginning) +- **Locates** elements with `indexOf()` and checks existence with `includes()` +- **Returns** useful values like removed elements or position indexes + ✅ Try it yourself! Use your browser's console to create and manipulate an array of your own creation. ## Loops -Loops allow us to perform repetitive or **iterative** tasks, and can save a lot of time and code. Each iteration can vary in their variables, values, and conditions. There are different types of loops in JavaScript, and they all have small differences, but essentially do the same thing: loop over data. +Think of the famous punishment from Charles Dickens' novels where students had to write lines repeatedly on a slate. Imagine if you could simply instruct someone to "write this sentence 100 times" and have it done automatically. That's exactly what loops do for your code. + +Loops are like having a tireless assistant who can repeat tasks without error. Whether you need to check every item in a shopping cart or display all the photos in an album, loops handle the repetition efficiently. + +JavaScript provides several types of loops to choose from. Let's examine each one and understand when to use them. ### For Loop -The `for` loop requires 3 parts to iterate: -- `counter` A variable that is typically initialized with a number that counts the number of iterations -- `condition` Expression that uses comparison operators to cause the loop to stop when `false` -- `iteration-expression` Runs at the end of each iteration, typically used to change the counter value - +The `for` loop is like setting a timer - you know exactly how many times you want something to happen. It's super organized and predictable, which makes it perfect when you're working with arrays or need to count things. + +**For Loop Structure:** + +| Component | Purpose | Example | +|-----------|---------|----------| +| **Initialization** | Sets starting point | `let i = 0` | +| **Condition** | When to continue | `i < 10` | +| **Increment** | How to update | `i++` | + ```javascript -// Counting up to 10 +// Counting from 0 to 9 for (let i = 0; i < 10; i++) { - console.log(i); + console.log(`Count: ${i}`); +} + +// More practical example: processing scores +const testScores = [85, 92, 78, 96, 88]; +for (let i = 0; i < testScores.length; i++) { + console.log(`Student ${i + 1}: ${testScores[i]}%`); } ``` +**Step by step, here's what's happening:** +- **Initializes** the counter variable `i` to 0 at the start +- **Checks** the condition `i < 10` before each iteration +- **Executes** the code block when the condition is true +- **Increments** `i` by 1 after each iteration with `i++` +- **Stops** when the condition becomes false (when `i` reaches 10) + ✅ Run this code in a browser console. What happens when you make small changes to the counter, condition, or iteration expression? Can you make it run backwards, creating a countdown? -### While loop +### While Loop + +The `while` loop is like saying "keep doing this until..." - you might not know exactly how many times it'll run, but you know when to stop. It's perfect for things like asking a user for input until they give you what you need, or searching through data until you find what you're looking for. -Unlike the syntax of the `for` loop, `while` loops only require a condition that will stop the loop when the condition becomes `false`. Conditions in loops usually rely on other values like counters, and must be managed during the loop. Starting values for counters must be created outside the loop, and any expressions to meet a condition, including changing the counter must be maintained inside the loop. +**While Loop Characteristics:** +- **Continues** executing as long as the condition is true +- **Requires** manual management of any counter variables +- **Checks** the condition before each iteration +- **Risks** infinite loops if the condition never becomes false ```javascript -//Counting up to 10 +// Basic counting example let i = 0; while (i < 10) { - console.log(i); - i++; + console.log(`While count: ${i}`); + i++; // Don't forget to increment! +} + +// More practical example: processing user input +let userInput = ""; +let attempts = 0; +const maxAttempts = 3; + +while (userInput !== "quit" && attempts < maxAttempts) { + userInput = prompt(`Enter 'quit' to exit (attempt ${attempts + 1}):`); + attempts++; +} + +if (attempts >= maxAttempts) { + console.log("Maximum attempts reached!"); +} +``` + +**Understanding these examples:** +- **Manages** the counter variable `i` manually inside the loop body +- **Increments** the counter to prevent infinite loops +- **Demonstrates** practical use case with user input and attempt limiting +- **Includes** safety mechanisms to prevent endless execution + +### Modern Loop Alternatives + +JavaScript offers modern loop syntax that can make your code more readable and less error-prone. + +**For...of Loop (ES6+):** + +```javascript +const colors = ["red", "green", "blue", "yellow"]; + +// Modern approach - cleaner and safer +for (const color of colors) { + console.log(`Color: ${color}`); +} + +// Compare with traditional for loop +for (let i = 0; i < colors.length; i++) { + console.log(`Color: ${colors[i]}`); } ``` +**Key advantages of for...of:** +- **Eliminates** index management and potential off-by-one errors +- **Provides** direct access to array elements +- **Improves** code readability and reduces syntax complexity + +**forEach Method:** + +```javascript +const prices = [9.99, 15.50, 22.75, 8.25]; + +// Using forEach for functional programming style +prices.forEach((price, index) => { + console.log(`Item ${index + 1}: $${price.toFixed(2)}`); +}); + +// forEach with arrow functions for simple operations +prices.forEach(price => console.log(`Price: $${price}`)); +``` + +**What you need to know about forEach:** +- **Executes** a function for each array element +- **Provides** both element value and index as parameters +- **Cannot** be stopped early (unlike traditional loops) +- **Returns** undefined (doesn't create a new array) + ✅ Why would you choose a for loop vs. a while loop? 17K viewers had the same question on StackOverflow, and some of the opinions [might be interesting to you](https://stackoverflow.com/questions/39969145/while-loops-vs-for-loops-in-javascript). ## Loops and Arrays -Arrays are often used with loops because most conditions require the length of the array to stop the loop, and the index can also be the counter value. +Combining arrays with loops creates powerful data processing capabilities. This pairing is fundamental to many programming tasks, from displaying lists to calculating statistics. + +**Traditional Array Processing:** ```javascript -let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"]; +const iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Rocky Road"]; +// Classic for loop approach for (let i = 0; i < iceCreamFlavors.length; i++) { - console.log(iceCreamFlavors[i]); -} //Ends when all flavors are printed + console.log(`Flavor ${i + 1}: ${iceCreamFlavors[i]}`); +} + +// Modern for...of approach +for (const flavor of iceCreamFlavors) { + console.log(`Available flavor: ${flavor}`); +} +``` + +**Let's understand each approach:** +- **Uses** array length property to determine loop boundary +- **Accesses** elements by index in traditional for loops +- **Provides** direct element access in for...of loops +- **Processes** each array element exactly once + +**Practical Data Processing Example:** + +```javascript +const studentGrades = [85, 92, 78, 96, 88, 73, 89]; +let total = 0; +let highestGrade = studentGrades[0]; +let lowestGrade = studentGrades[0]; + +// Process all grades with a single loop +for (let i = 0; i < studentGrades.length; i++) { + const grade = studentGrades[i]; + total += grade; + + if (grade > highestGrade) { + highestGrade = grade; + } + + if (grade < lowestGrade) { + lowestGrade = grade; + } +} + +const average = total / studentGrades.length; +console.log(`Average: ${average.toFixed(1)}`); +console.log(`Highest: ${highestGrade}`); +console.log(`Lowest: ${lowestGrade}`); ``` -✅ Experiment with looping over an array of your own making in your browser's console. +**Here's how this code works:** +- **Initializes** tracking variables for sum and extremes +- **Processes** each grade with a single efficient loop +- **Accumulates** the total for average calculation +- **Tracks** highest and lowest values during iteration +- **Calculates** final statistics after loop completion + +✅ Experiment with looping over an array of your own making in your browser's console. --- @@ -121,13 +348,17 @@ for (let i = 0; i < iceCreamFlavors.length; i++) { Use the Agent mode to complete the following challenge: -**Description:** Build a data processing function that combines arrays and loops to analyze a dataset. +**Description:** Build a comprehensive data processing function that combines arrays and loops to analyze a dataset and generate meaningful insights. -**Prompt:** Create a function called `analyzeGrades` that takes an array of student grade objects (each containing name and score properties) and returns statistics including the highest score, lowest score, average score, and count of students who passed (score >= 70). Use loops to process the data. +**Prompt:** Create a function called `analyzeGrades` that takes an array of student grade objects (each containing name and score properties) and returns an object with statistics including the highest score, lowest score, average score, count of students who passed (score >= 70), and an array of student names who scored above average. Use at least two different loop types in your solution. + +Learn more about [agent mode](https://code.visualstudio.com/blogs/2025/02/24/introducing-copilot-agent-mode) here. ## 🚀 Challenge -There are other ways of looping over arrays other than for and while loops. There are [forEach](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach), [for-of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), and [map](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map). Rewrite your array loop using one of these techniques. +JavaScript offers several modern array methods that can replace traditional loops for specific tasks. Explore [forEach](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach), [for-of](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of), [map](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map), [filter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), and [reduce](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce). + +**Your challenge:** Refactor the student grades example using at least three different array methods. Notice how much cleaner and more readable the code becomes with modern JavaScript syntax. ## Post-Lecture Quiz [Post-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/14) diff --git a/2-js-basics/4-arrays-loops/assignment.md b/2-js-basics/4-arrays-loops/assignment.md index 0b9bd6dc..be4fc402 100644 --- a/2-js-basics/4-arrays-loops/assignment.md +++ b/2-js-basics/4-arrays-loops/assignment.md @@ -1,13 +1,108 @@ -# Loop an Array +# Arrays and Loops Assignment ## Instructions +Complete the following exercises to practice working with arrays and loops. Each exercise builds on concepts from the lesson and encourages you to apply different loop types and array methods. + +### Exercise 1: Number Pattern Generator Create a program that lists every 3rd number between 1-20 and prints it to the console. -> TIP: use a for-loop and modify the iteration-expression +**Requirements:** +- Use a `for` loop with a custom increment +- Display numbers in a user-friendly format +- Add descriptive comments explaining your logic + +**Expected Output:** +``` +3, 6, 9, 12, 15, 18 +``` + +> **Tip:** Modify the iteration-expression in your for loop to skip numbers. + +### Exercise 2: Array Analysis +Create an array of at least 8 different numbers and write functions to analyze the data. + +**Requirements:** +- Create an array called `numbers` with at least 8 values +- Write a function `findMaximum()` that returns the highest number +- Write a function `findMinimum()` that returns the lowest number +- Write a function `calculateSum()` that returns the total of all numbers +- Test each function and display the results + +**Bonus Challenge:** Create a function that finds the second highest number in the array. + +### Exercise 3: String Array Processing +Create an array of your favorite movies/books/songs and practice different loop types. + +**Requirements:** +- Create an array with at least 5 string values +- Use a traditional `for` loop to display items with numbers (1. Item Name) +- Use a `for...of` loop to display items in uppercase +- Use `forEach()` method to count and display the total characters + +**Example Output:** +``` +Traditional for loop: +1. The Matrix +2. Inception +3. Interstellar + +For...of loop (uppercase): +THE MATRIX +INCEPTION +INTERSTELLAR + +Character count: +Total characters across all titles: 42 +``` + +### Exercise 4: Data Filtering (Advanced) +Create a program that processes an array of objects representing students. + +**Requirements:** +- Create an array of at least 5 student objects with properties: `name`, `age`, `grade` +- Use loops to find students who are 18 or older +- Calculate the average grade of all students +- Create a new array containing only students with grades above 85 + +**Example Structure:** +```javascript +const students = [ + { name: "Alice", age: 17, grade: 92 }, + { name: "Bob", age: 18, grade: 84 }, + // Add more students... +]; +``` + +## Testing Your Code + +Test your programs by: +1. Running each exercise in your browser's console +2. Verifying outputs match expected results +3. Testing with different data sets +4. Checking that your code handles edge cases (empty arrays, single elements) + +## Submission Guidelines + +Include the following in your submission: +- Well-commented JavaScript code for each exercise +- Screenshots or text output showing your programs running +- Brief explanation of which loop type you chose for each task and why ## Rubric -| Criteria | Exemplary | Adequate | Needs Improvement | -| -------- | --------------------------------------- | ------------------------ | ------------------------------ | -| | Program runs correctly and is commented | Program is not commented | Program is incomplete or buggy | \ No newline at end of file +| Criteria | Exemplary (3 points) | Adequate (2 points) | Needs Improvement (1 point) | +| -------- | -------------------- | ------------------- | --------------------------- | +| **Functionality** | All exercises completed correctly with bonus challenges | All required exercises work correctly | Some exercises incomplete or contain errors | +| **Code Quality** | Clean, well-organized code with descriptive variable names | Code works but could be cleaner | Code is messy or hard to understand | +| **Comments** | Comprehensive comments explaining logic and decisions | Basic comments present | Minimal or no comments | +| **Loop Usage** | Demonstrates understanding of different loop types appropriately | Uses loops correctly but limited variety | Incorrect or inefficient loop usage | +| **Testing** | Evidence of thorough testing with multiple scenarios | Basic testing demonstrated | Little evidence of testing | + +## Reflection Questions + +After completing the exercises, consider: +1. Which type of loop felt most natural to use and why? +2. What challenges did you encounter when working with arrays? +3. How could these skills apply to real-world web development projects? +4. What would you do differently if you had to optimize your code for performance? \ No newline at end of file diff --git a/3-terrarium/1-intro-to-html/README.md b/3-terrarium/1-intro-to-html/README.md index f5900ce8..f032795c 100644 --- a/3-terrarium/1-intro-to-html/README.md +++ b/3-terrarium/1-intro-to-html/README.md @@ -3,74 +3,87 @@ ![Introduction to HTML](../../sketchnotes/webdev101-html.png) > Sketchnote by [Tomomi Imura](https://twitter.com/girlie_mac) -## Pre-Lecture Quiz - -[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/15) +HTML, or HyperText Markup Language, is the foundation of every website you've ever visited. Think of HTML as the skeleton that gives structure to web pages – it defines where content goes, how it's organized, and what each piece represents. While CSS will later "dress up" your HTML with colors and layouts, and JavaScript will bring it to life with interactivity, HTML provides the essential structure that makes everything else possible. +In this lesson, you'll create the HTML structure for a virtual terrarium interface. This hands-on project will teach you fundamental HTML concepts while building something visually engaging. You'll learn how to organize content using semantic elements, work with images, and create the foundation for an interactive web application. -> Check out video +By the end of this lesson, you'll have a working HTML page displaying plant images in organized columns, ready for styling in the next lesson. Don't worry if it looks basic at first – that's exactly what HTML should do before CSS adds the visual polish. -> -> [![Git and GitHub basics video](https://img.youtube.com/vi/1TvxJKBzhyQ/0.jpg)](https://www.youtube.com/watch?v=1TvxJKBzhyQ) +## Pre-Lecture Quiz -### Introduction +[Pre-lecture quiz](https://ff-quizzes.netlify.app/web/quiz/15) -HTML, or HyperText Markup Language, is the 'skeleton' of the web. If CSS 'dresses up' your HTML and JavaScript brings it to life, HTML is the body of your web application. HTML's syntax even reflects that idea, as it includes "head", "body", and "footer" tags. +> 📺 **Watch and Learn**: Check out this helpful video overview +> +> [![HTML Fundamentals Video](https://img.youtube.com/vi/1TvxJKBzhyQ/0.jpg)](https://www.youtube.com/watch?v=1TvxJKBzhyQ) -In this lesson, we're going to use HTML to layout the 'skeleton' of our virtual terrarium's interface. It will have a title and three columns: a right and a left column where the draggable plants live, and a center area that will be the actual glass-looking terrarium. By the end of this lesson, you will be able to see the plants in the columns, but the interface will look a little strange; don't worry, in the next section you will add CSS styles to the interface to make it look better. +## Setting Up Your Project -### Task +Before we dive into HTML code, let's set up a proper workspace for your terrarium project. Creating an organized file structure from the beginning is a crucial habit that will serve you well throughout your web development journey. -On your computer, create a folder called 'terrarium' and inside it, a file called 'index.html'. You can do this in Visual Studio Code after you create your terrarium folder by opening a new VS Code window, clicking 'open folder', and navigating to your new folder. Click the small 'file' button in the Explorer pane and create the new file: +### Task: Create Your Project Structure -![explorer in VS Code](images/vs-code-index.png) +You'll create a dedicated folder for your terrarium project and add your first HTML file. Here are two approaches you can use: -Or +**Option 1: Using Visual Studio Code** +1. Open Visual Studio Code +2. Click "File" → "Open Folder" or use `Ctrl+K, Ctrl+O` (Windows/Linux) or `Cmd+K, Cmd+O` (Mac) +3. Create a new folder called `terrarium` and select it +4. In the Explorer pane, click the "New File" icon +5. Name your file `index.html` -Use these commands on your git bash: -* `mkdir terrarium` -* `cd terrarium` -* `touch index.html` -* `code index.html` or `nano index.html` +![VS Code Explorer showing new file creation](images/vs-code-index.png) -> index.html files indicate to a browser that it is the default file in a folder; URLs such as `https://anysite.com/test` might be built using a folder structure including a folder called `test` with `index.html` inside it; `index.html` doesn't have to show in a URL. +**Option 2: Using Terminal Commands** +```bash +mkdir terrarium +cd terrarium +touch index.html +code index.html +``` ---- +**Here's what these commands accomplish:** +- **Creates** a new directory called `terrarium` for your project +- **Navigates** into the terrarium directory +- **Creates** an empty `index.html` file +- **Opens** the file in Visual Studio Code for editing -## The DocType and html tags +> 💡 **Pro Tip**: The filename `index.html` is special in web development. When someone visits a website, browsers automatically look for `index.html` as the default page to display. This means a URL like `https://mysite.com/projects/` will automatically serve the `index.html` file from the `projects` folder without needing to specify the filename in the URL. -The first line of an HTML file is its doctype. It's a little surprising that you need to have this line at the very top of the file, but it tells older browsers that the browser needs to render the page in a standard mode, following the current html specification. +## Understanding HTML Document Structure -> Tip: in VS Code, you can hover over a tag and get information about its use from the MDN Reference guides. +Every HTML document follows a specific structure that browsers need to understand and display correctly. Think of this structure like a formal letter – it has required elements in a particular order that help the recipient (in this case, the browser) process the content properly. -The second line should be the `` tag's opening tag, followed right now by its closing tag ``. These tags are the root elements of your interface. +Let's start by adding the essential foundation that every HTML document needs. -### Task +### The DOCTYPE Declaration and Root Element -Add these lines at the top of your `index.html` file: +The first two lines of any HTML file serve as the document's "introduction" to the browser: -```HTML +```html ``` -✅ There are a few different modes that can be determined by setting the DocType with a query string: [Quirks Mode and Standards Mode](https://developer.mozilla.org/docs/Web/HTML/Quirks_Mode_and_Standards_Mode). These modes used to support really old browsers that aren't normally used nowadays (Netscape Navigator 4 and Internet Explorer 5). You can stick to the standard doctype declaration. +**Understanding what this code does:** +- **Declares** the document type as HTML5 using `` +- **Creates** the root `` element that will contain all page content +- **Establishes** modern web standards for proper browser rendering +- **Ensures** consistent display across different browsers and devices ---- +> 💡 **VS Code Tip**: Hover over any HTML tag in VS Code to see helpful information from MDN Web Docs, including usage examples and browser compatibility details. -## The document's 'head' +> 📚 **Learn More**: The DOCTYPE declaration prevents browsers from entering "quirks mode," which was used to support very old websites. Modern web development uses the simple `` declaration to ensure [standards-compliant rendering](https://developer.mozilla.org/docs/Web/HTML/Quirks_Mode_and_Standards_Mode). -The 'head' area of the HTML document includes crucial information about your web page, also known as [metadata](https://developer.mozilla.org/docs/Web/HTML/Element/meta). In our case, we tell the web server to which this page will be sent to be rendered, these four things: +## Adding Essential Document Metadata -- the page's title -- page metadata including: - - the 'character set', telling about what character encoding is used in the page - - browser information, including `x-ua-compatible` which indicates that the IE=edge browser is supported - - information about how the viewport should behave when it is loaded. Setting the viewport to have an initial scale of 1 controls the zoom level when the page is first loaded. +The `` section of an HTML document contains crucial information that browsers and search engines need, but that visitors don't see directly on the page. Think of it as the "behind-the-scenes" information that helps your webpage work properly and appear correctly across different devices and platforms. -### Task +This metadata tells browsers how to display your page, what character encoding to use, and how to handle different screen sizes – all essential for creating professional, accessible web pages. -Add a 'head' block to your document in between the opening and closing `` tags. +### Task: Add the Document Head + +Insert this `` section between your opening and closing `` tags: ```html @@ -81,17 +94,28 @@ Add a 'head' block to your document in between the opening and closing `` ``` -✅ What would happen if you set a viewport meta tag like this: ``? Read more about the [viewport](https://developer.mozilla.org/docs/Web/HTML/Viewport_meta_tag). +**Breaking down what each element accomplishes:** +- **Sets** the page title that appears in browser tabs and search results +- **Specifies** UTF-8 character encoding for proper text display worldwide +- **Ensures** compatibility with modern versions of Internet Explorer +- **Configures** responsive design by setting the viewport to match device width +- **Controls** initial zoom level to display content at natural size ---- +> 🤔 **Think About This**: What would happen if you set a viewport meta tag like this: ``? This would force the page to always be 600 pixels wide, breaking responsive design! Learn more about [proper viewport configuration](https://developer.mozilla.org/docs/Web/HTML/Viewport_meta_tag). -## The document's `body` +## Building the Document Body -### HTML Tags +The `` element contains all the visible content of your webpage – everything users will see and interact with. While the `` section provided instructions to the browser, the `` section contains the actual content: text, images, buttons, and other elements that create your user interface. -In HTML, you add tags to your .html file to create elements of a web page. Each tag usually has an opening and closing tag, like this: `

hello

` to indicate a paragraph. Create your interface's body by adding a set of `` tags inside the `` tag pair; your markup now looks like this: +Let's add the body structure and understand how HTML tags work together to create meaningful content. -### Task +### Understanding HTML Tag Structure + +HTML uses paired tags to define elements. Most tags have an opening tag like `

` and a closing tag like `

`, with content in between: `

Hello, world!

`. This creates a paragraph element containing the text "Hello, world!". + +### Task: Add the Body Element + +Update your HTML file to include the `` element: ```html @@ -106,17 +130,28 @@ In HTML, you add tags to your .html file to create elements of a web page. Each ``` -Now, you can start building out your page. Normally, you use `
` tags to create the separate elements in a page. We'll create a series of `
` elements which will contain images. +**Here's what this complete structure provides:** +- **Establishes** the basic HTML5 document framework +- **Includes** essential metadata for proper browser rendering +- **Creates** an empty body ready for your visible content +- **Follows** modern web development best practices + +Now you're ready to add the visible elements of your terrarium. We'll use `
` elements as containers to organize different sections of content, and `` elements to display the plant images. -### Images +### Working with Images and Layout Containers -One html tag that doesn't need a closing tag is the `` tag, because it has a `src` element that contains all the information the page needs to render the item. +Images are special in HTML because they use "self-closing" tags. Unlike elements like `

` that wrap around content, the `` tag contains all the information it needs within the tag itself using attributes like `src` for the image file path and `alt` for accessibility. -Create a folder in your app called `images` and in that, add all the images in the [source code folder](../solution/images); (there are 14 images of plants). +Before adding images to your HTML, you'll need to organize your project files properly by creating an images folder and adding the plant graphics. -### Task +**First, set up your images:** +1. Create a folder called `images` inside your terrarium project folder +2. Download the plant images from the [solution folder](../solution/images) (14 plant images total) +3. Copy all plant images into your new `images` folder -Add those plant images into two columns between the `` tags: +### Task: Create the Plant Display Layout + +Now add the plant images organized in two columns between your `` tags: ```html
@@ -169,37 +204,62 @@ Add those plant images into two columns between the `` tags:
``` -> Note: Spans vs. Divs. Divs are considered 'block' elements, and Spans are 'inline'. What would happen if you transformed these divs to spans? +**Step by step, here's what's happening in this code:** +- **Creates** a main page container with `id="page"` to hold all content +- **Establishes** two column containers: `left-container` and `right-container` +- **Organizes** 7 plants in the left column and 7 plants in the right column +- **Wraps** each plant image in a `plant-holder` div for individual positioning +- **Applies** consistent class names for CSS styling in the next lesson +- **Assigns** unique IDs to each plant image for JavaScript interaction later +- **Includes** proper file paths pointing to the images folder -With this markup, the plants now show up on the screen. It looks pretty bad, because they aren't yet styled using CSS, and we'll do that in the next lesson. +> 🤔 **Consider This**: Notice that all images currently have the same alt text "plant". This isn't ideal for accessibility. Screen reader users would hear "plant" repeated 14 times without knowing which specific plant each image shows. Can you think of better, more descriptive alt text for each image? -Each image has alt text that will appear even if you can't see or render an image. This is an important attribute to include for accessibility. Learn more about accessibility in future lessons; for now, remember that the alt attribute provides alternative information for an image if a user for some reason cannot view it (because of slow connection, an error in the src attribute, or if the user uses a screen reader). +> 📝 **HTML Element Types**: `
` elements are "block-level" and take up full width, while `` elements are "inline" and only take up necessary width. What do you think would happen if you changed all these `
` tags to `` tags? -✅ Did you notice that each image has the same alt tag? Is this good practice? Why or why not? Can you improve this code? +With this markup added, the plants will appear on screen, though they won't look polished yet – that's what CSS is for in the next lesson! For now, you have a solid HTML foundation that properly organizes your content and follows accessibility best practices. ---- +## Using Semantic HTML for Accessibility + +Semantic HTML means choosing HTML elements based on their meaning and purpose, not just their appearance. When you use semantic markup, you're communicating the structure and meaning of your content to browsers, search engines, and assistive technologies like screen readers. -## Semantic markup +This approach makes your websites more accessible to users with disabilities and helps search engines better understand your content. It's a fundamental principle of modern web development that creates better experiences for everyone. -In general, it's preferable to use meaningful 'semantics' when writing HTML. What does that mean? It means that you use HTML tags to represent the type of data or interaction they were designed for. For example, the main title text on a page should use an `

` tag. +### Adding a Semantic Page Title -Add the following line right below your opening `` tag: +Let's add a proper heading to your terrarium page. Insert this line right after your opening `` tag: ```html

My Terrarium

``` -Using semantic markup such as having headers be `

` and unordered lists be rendered as `
    ` helps screen readers navigate through a page. In general, buttons should be written as `` | `Click me` | +| Article content | `

    ` | `
    ` | -✅ Take a look at a screen reader and [how it interacts with a web page](https://www.youtube.com/watch?v=OUDV1gqs9GA). Can you see why having non semantic markup might frustrate the user? +> 🎥 **See It in Action**: Watch [how screen readers interact with web pages](https://www.youtube.com/watch?v=OUDV1gqs9GA) to understand why semantic markup is crucial for accessibility. Notice how proper HTML structure helps users navigate efficiently. -## The terrarium +## Creating the Terrarium Container -The last part of this interface involves creating markup that will be styled to create a terrarium. +Now let's add the HTML structure for the terrarium itself – the glass container where plants will eventually be placed. This section demonstrates an important concept: HTML provides structure, but without CSS styling, these elements won't be visible yet. -### Task: +The terrarium markup uses descriptive class names that will make CSS styling intuitive and maintainable in the next lesson. -Add this markup above the last `

` tag: +### Task: Add the Terrarium Structure + +Insert this markup above the last `
` tag (before the closing tag of the page container): ```html
@@ -213,11 +273,18 @@ Add this markup above the last `
` tag:
``` -✅ Even though you added this markup to the screen, you see absolutely nothing render. Why? +**Understanding this terrarium structure:** +- **Creates** a main terrarium container with a unique ID for styling +- **Defines** separate elements for each visual component (top, walls, dirt, bottom) +- **Includes** nested elements for glass reflection effects (glossy elements) +- **Uses** descriptive class names that clearly indicate each element's purpose +- **Prepares** the structure for CSS styling that will create the glass terrarium appearance + +> 🤔 **Notice Something?**: Even though you added this markup, you don't see anything new on the page! This perfectly illustrates how HTML provides structure while CSS provides appearance. These `
` elements exist but have no visual styling yet – that's coming in the next lesson! --- -## GitHub Copilot Agent Challenge 🚀 +## GitHub Copilot Agent Challenge Use the Agent mode to complete the following challenge: @@ -225,9 +292,26 @@ Use the Agent mode to complete the following challenge: **Prompt:** Create a semantic HTML section that includes a main heading "Plant Care Guide", three subsections with headings "Watering", "Light Requirements", and "Soil Care", each containing a paragraph of plant care information. Use proper semantic HTML tags like `
`, `

`, `

`, and `

` to structure the content appropriately. -## 🚀Challenge +Learn more about [agent mode](https://code.visualstudio.com/blogs/2025/02/24/introducing-copilot-agent-mode) here. + +## Explore HTML History Challenge + +**Learning About Web Evolution** -There are some wild 'older' tags in HTML that are still fun to play with, though you shouldn't use deprecated tags such as [these tags](https://developer.mozilla.org/docs/Web/HTML/Element#Obsolete_and_deprecated_elements) in your markup. Still, can you use the old `` tag to make the h1 title scroll horizontally? (if you do, don't forget to remove it afterwards) +HTML has evolved significantly since Tim Berners-Lee created the first web browser at CERN in 1990. Some older tags like `` are now deprecated because they don't work well with modern accessibility standards and responsive design principles. + +**Try This Experiment:** +1. Temporarily wrap your `

` title in a `` tag: `

My Terrarium

` +2. Open your page in a browser and observe the scrolling effect +3. Consider why this tag was deprecated (hint: think about user experience and accessibility) +4. Remove the `` tag and return to semantic markup + +**Reflection Questions:** +- How might a scrolling title affect users with visual impairments or motion sensitivity? +- What modern CSS techniques could achieve similar visual effects more accessibly? +- Why is it important to use current web standards instead of deprecated elements? + +Explore more about [obsolete and deprecated HTML elements](https://developer.mozilla.org/docs/Web/HTML/Element#Obsolete_and_deprecated_elements) to understand how web standards evolve to improve user experience. ## Post-Lecture Quiz @@ -236,9 +320,31 @@ There are some wild 'older' tags in HTML that are still fun to play with, though ## Review & Self Study -HTML is the 'tried and true' building block system that has helped build the web into what it is today. Learn a little about its history by studying some old and new tags. Can you figure out why some tags were deprecated and some added? What tags might be introduced in the future? +**Deepen Your HTML Knowledge** + +HTML has been the foundation of the web for over 30 years, evolving from a simple document markup language to a sophisticated platform for building interactive applications. Understanding this evolution helps you appreciate modern web standards and make better development decisions. + +**Recommended Learning Paths:** + +1. **HTML History and Evolution** + - Research the timeline from HTML 1.0 to HTML5 + - Explore why certain tags were deprecated (accessibility, mobile-friendliness, maintainability) + - Investigate emerging HTML features and proposals + +2. **Semantic HTML Deep Dive** + - Study the complete list of [HTML5 semantic elements](https://developer.mozilla.org/docs/Web/HTML/Element) + - Practice identifying when to use `
`, `
`, `