# Welcome

When you sign up for HackYourFuture (HYF) Denmark, you have the opportunity to join our 8 month program. It is split into two parts: a foundation course and a specialism course. In Foundation, you get a chance to practice the fundamentals of web development before you get the chance to specialise down a specific path to suit your skills and interests in the world of tech.

This repository contains all of our courses, modules, guides and other learning resources that we use throughout our learning program.

## What does the program look like?

We provide an environment for self-directed learning of the fundamentals of web development. We are not a school, we are a learning community, supported by a network of skilled mentors from the tech industry. HackYourFuture requires 30 hours of independent study per week, of which 4 hours are on-site sessions on Sundays. You are responsible for your own learning, delivering your assignments on time and showing up to the sessions well prepared. Together, we will discover state-of-the-art tools and frameworks, industry best-practices, and experience working collaboratively in a modern development team.

![Program Overview](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-694a9db715d765b54bc0478f0da2cb4acf681b2e%2Fprogram-overview.png?alt=media)

### Key Themes

1. **Web Design** - Build beautiful, well formatted web pages that work responsively across all devices using HTML and CSS.
2. **Web App Development** - Build fabulous functionality across the frontend and backend using the most popular web development programming language, JavaScript.
3. **Databases** - Design databases and query data using SQL across various technologies such as SQLite, MySQL and PostgreSQL.
4. **Team Collaboration** - Collaborate on projects using Git in a modern team environment based on Agile principles and Scrum practices.
5. **Generative AI** - Level up your learning with AI, practice effective prompting techniques and build AI-powered projects.
6. **Career Training** - Develop your personal brand to showcase on GitHub, LinkedIn and your CV, along with industry specific interview training.

## Getting started

You'll find lots of content in this repo, but as a starting point head to the [Courses](/course-content/courses) page to take a look through the modules we teach.

If you are, or interested in, volunteering, check out our [Mentor Guide](https://mentor.hackyourfuture.dk/) for further guidance on becoming a successful mentor in our learning community.

## Further info and questions

Feel free to check out our website [hackyourfuture.dk](https://hackyourfuture.dk) for further information about what we do and how we can help you. If you have any questions, you can find our contact details on there, too.

## Contributing

We are open source! Every volunteer is welcome to contribute with new ideas and fixes. If you're interested in becoming a contributor, please visit [Contributing](https://github.com/HackYourFuture-CPH/program/tree/main/contributing/README.md).

*The HackYourFuture Program is subject to CC BY NC SA copyright. This means you can freely use our materials, but just make sure to give us credit for it and don't use it commercially, as it is the intellectual property of our volunteers.*

[![Creative Commons License](https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png)](https://creativecommons.org/licenses/by-nc-sa/4.0/)

*This work is licensed under a* [*Creative Commons Attribution 4.0 International License*](http://creativecommons.org/licenses/by-nc-sa/4.0/)*.*


# Courses Overview

Our program is split into multiple phases from the pre-course, foundation and later the specialism courses which offer multiple paths to progress through.

It's important to note that this documentation lists all of the courses that we have developed. We do not always run every course for every team listed below. To see which courses are active and open for applications, see our website for up to date information [hackyourfuture.dk](https://hackyourfuture.dk).

## [Pre-Course](/course-content/pre-course)

## [Foundation](/course-content/foundation)

## [Frontend](/course-content/frontend)

## [Backend](/course-content/backend)

## [Cloud & AI](https://github.com/HackYourFuture-CPH/program/tree/main/courses/cloud\&ai/README.md)


# Pre-Course

The Pre-Course is a collection of tasks that you should complete before joining HackYourFuture.

## Modules

### [Pre-Assigmment](/course-content/pre-course/pre-assignment)

### [Self Study](/course-content/pre-course/self-study)


# Pre-Assignment

Here you can find a short list of resources to try out and get a small head-start for the test assignment.

## HTML and CSS Intro

If you don't know where to start, you can try some of these free online tutorials:

* [freeCodeCamp](https://www.freecodecamp.org/)
* [SCRIMBA](https://scrimba.com/g/ghtml)
* [sololearn](https://sololearn.com/) (mobile-friendly)

These are just suggestions - there are lots of other free online courses available online and it all depends on your personal preference.

## JavaScript Intro

A big part of our 7 month program is based on the programming language JavaScript. Try to have a first look at what JavaScript is with some of these free online tutorials:

* [freeCodeCamp](https://www.freecodecamp.org/)
* [FrontendMasters](https://frontendmasters.com/courses/web-development-v2/)
* [codecademy](https://www.codecademy.com/learn/introduction-to-javascript)

You can find lots more resources to learn from in the [FrontendMasters "Learn JavaScript" list](https://frontendmasters.com/books/front-end-handbook/2018/learning/javascript.html).

## Frontend Developer Handbook

If you prefer theory and reading up before taking a plunge into the coding world - then we recommend having a look at the below handbook. Reading this text will explain you a lot about what it means to be a web-developer. We really recommend it.

* [Front End Developer Handbook](https://frontendmasters.com/books/front-end-handbook/2019/) (yes, the 2019 version is still relevant and no newer versions exist).

## Frontend Developer Roadmap

If you're curious about what technologies are relevant in the field of Frontend Development - take a look at [this roadmap](https://roadmap.sh/frontend). It's totally fine if you don't recognize over 90% of the words - but return to this map as you keep learning and slowly you might be able to see your own path.

Don't worry if everything doesn't immediately make sense, that's what we can help with later. But do make sure that you understand the difference between HTML, CSS and JavaScript and what they are used for: [HTML, CSS, JavaScript Explained](https://youtu.be/gT0Lh1eYk78).


# Self Study

This module lists the steps you have to complete **BEFORE** the Foundation course starts.

You are going to be fully self-learning `HTML` and `CSS`, so it is very important and **mandatory** that you complete the steps before the first Sunday session at HackYourFuture.

You will also get a little introduction to `JavaScript`, so that you can be more comfortable jumping into it when the course starts.

## HTML and CSS

### freeCodeCamp certifications

The `freeCodeCamp` courses are a good way to learn. Their certifications are widely recognized, therefore we use this platform to give you a good start with learning `Web Development` and having a way to showcase your learning.

### What you have completed already

There are 5 parts in the [Responsive Web Design certification](https://www.freecodecamp.org/learn/2022/responsive-web-design/). Each part contains a few sections and a certification project at the end. You have already finished at least 2 sections from the first part during the application process:

* [Learn HTML by Building a Cat Photo App](https://www.freecodecamp.org/learn/2022/responsive-web-design/#learn-html-by-building-a-cat-photo-app)
* [Learn Basic CSS by Building a Cafe Menu](https://www.freecodecamp.org/learn/2022/responsive-web-design/#learn-basic-css-by-building-a-cafe-menu)

### What you have to do before the first Sunday session

You should finish the first part and the certification project that goes with it:

* [Learn CSS Colors by Building a Set of Colored Markers](https://www.freecodecamp.org/learn/2022/responsive-web-design/#learn-css-colors-by-building-a-set-of-colored-markers)
* [Learn HTML Forms by Building a Registration Form](https://www.freecodecamp.org/learn/2022/responsive-web-design/#learn-html-forms-by-building-a-registration-form)
* [Certification Project - Survey Form](https://www.freecodecamp.org/learn/2022/responsive-web-design/build-a-survey-form-project/build-a-survey-form)

This will familiarize you with `CSS` colors and building `Forms` with `HTML` and `CSS`, which are both essential parts of basic Web Development knowledge.

You should also complete 2 more sections from the second part:

* [Learn the CSS Box Model by Building a Rothko Painting](https://www.freecodecamp.org/learn/2022/responsive-web-design/#learn-the-css-box-model-by-building-a-rothko-painting)
* [Learn CSS Flexbox by Building a Photo Gallery](https://www.freecodecamp.org/learn/2022/responsive-web-design/#learn-css-flexbox-by-building-a-photo-gallery)

Learning the CSS Box Model and Flexbox will give you a very good foundational knowledge to deal with any styling or layout challenge.

## JavaScript

Complete these steps in the freeCodeCamp [JavaScript Algorithms and Data Structures certification](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/):

* [Comment Your JavaScript Code](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/comment-your-javascript-code)
* [Declare JavaScript Variables](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/declare-javascript-variables)
* [Storing Values with the Assignment Operator](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator)
* [Assigning the Value of One Variable to Another](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/assigning-the-value-of-one-variable-to-another)
* [Initializing Variables with the Assignment Operator](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/initializing-variables-with-the-assignment-operator)
* [Declare String Variables](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/declare-string-variables)
* [Understanding Uninitialized Variables](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables)
* [Understanding Case Sensitivity in Variables](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/understanding-case-sensitivity-in-variables)
* [Explore Differences Between the var and let Keywords](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/explore-differences-between-the-var-and-let-keywords)
* [Declare a Read-Only Variable with the const Keyword](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/declare-a-read-only-variable-with-the-const-keyword)
* [Add Two Numbers with JavaScript](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/add-two-numbers-with-javascript)
* [Subtract One Number from Another with JavaScript](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/divide-one-number-by-another-with-javascript)
* [Multiply Two Numbers with JavaScript](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/multiply-two-numbers-with-javascript)
* [Divide One Number by Another with JavaScript](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/divide-one-number-by-another-with-javascript)
* [Increment a Number with JavaScript](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/increment-a-number-with-javascript)
* [Decrement a Number with JavaScript](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/decrement-a-number-with-javascript)
* [Create Decimal Numbers with JavaScript](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/create-decimal-numbers-with-javascript)
* [Multiply Two Decimals with JavaScript](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/multiply-two-decimals-with-javascript)
* [Divide One Decimal by Another with JavaScript](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/divide-one-decimal-by-another-with-javascript)
* [Finding a Remainder in JavaScript](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/finding-a-remainder-in-javascript)
* [Compound Assignment With Augmented Addition](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-addition)
* [Compound Assignment With Augmented Subtraction](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-subtraction)
* [Compound Assignment With Augmented Multiplication](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-multiplication)
* [Compound Assignment With Augmented Division](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-division)

If you like the `freeCodeCamp` format, you should definitely continue beyond what we ask of you and attain the various relevant certifications - especially by completing the **Responsive Web Design** and **Javascript Algorithms and Data Structures** certifications!

## Submitting your preparation

Before the first Sunday session, you must have completed all the steps listed above. Then you need to make your `freeCodeCamp` profile public - [Video on How to make your freeCodeCamp profile public](https://www.loom.com/share/019547eab49e4e198fd2d24f6cb27d3c) - and post a link to your profile in your team Slack channel. If you do not do this before the first Sunday session, you will not be able to continue with the course.

## FAQ

* If you have completed all these parts already, just continue further with the certifications. You are here to learn after all and you are entering a journey of self-learning!
* If you have not completed the steps listed above from the `Responsive Web Design` certification and the `JavaScript Algorithms and Data Structures` certification by the time of the first Sunday session, you will not be able to continue with the course.
* Stuck or need help? Please use your team Slack channel to ask for help from your fellow trainees. Asking for help, explaining the problems you have, and sharing your own knowledge with your fellow trainees are all very important skills to succeed in HackYourFuture, so start practising now!


# Foundation

Here you'll learn the fundamentals for how the web works, the basics of programming, and how to start shaping your CV as you develop your tech skills.

## Modules

| Name                                                                              | Weeks |
| --------------------------------------------------------------------------------- | ----- |
| [HTML & CSS](/course-content/foundation/html-and-css)                             | 1     |
| [Git](/course-content/foundation/git)                                             | 1     |
| [Intro to Using AI](/course-content/foundation/intro-to-using-ai)                 | 1     |
| [Intro to JavaScript](/course-content/foundation/intro-to-javascript)             | 4     |
| [Intro to Web Architecture](/course-content/foundation/intro-to-web-architecture) | 1     |
| [Databases](/course-content/foundation/databases)                                 | 1     |
| [Intro to Backend](/course-content/foundation/intro-to-backend)                   | 1     |
| [Intro to Frontend](/course-content/foundation/intro-to-frontend)                 | 1     |
| [Career Training](/course-content/foundation/career-training)                     | 2     |
| [Intro to Agile](/course-content/foundation/intro-to-agile)                       | 1     |
| [Final project](/course-content/foundation/final-project)                         | 3     |

Total: 17 weeks

## Learning Goals Overview

### [HTML & CSS](/course-content/foundation/html-and-css)

* [ ] Setup VSCode
* [ ] Round-up the [Pre-Course](/course-content/pre-course) materials on HTML and CSS
* [ ] Spend a lot of time with hands-on coding practice
* [ ] Learn to work efficiently with your team members
* [ ] Briefly introduce Figma

### [Git](/course-content/foundation/git)

* [ ] Understand what version control is
* [ ] Understand what Git is used for
* [ ] Know the difference between Git and GitHub
* [ ] Successfully install and configure Git
* [ ] Practice command line basics
* [ ] Know how to create a repo, branches, commits and push to GitHub
* [ ] Understand the usual flow for saving and sharing changes

### [Intro to Using AI](/course-content/foundation/intro-to-using-ai)

* [ ] AI Literacy:
  * [ ] Describe how Large Language Models (LLMs) work at a basic level.
  * [ ] Explain what Generative AI (AI) is, what it's good at, and its limitations.
  * [ ] Identify appropriate and inappropriate uses of AI in the workplace.
  * [ ] Practice how you can use AI to help you learn effectively, rather than just providing answers.
  * [ ] Recognize common risks related to AI usage, such as bias, copyright, hallucinations, misinformation, and privacy concerns.
  * [ ] Reflect on how AI is changing work and skill expectations (and what we don't know yet!).
* [ ] Prompting:
  * [ ] Apply simple prompting techniques to get useful outputs from GitHub Copilot.
  * [ ] Evaluate AI outputs critically for accuracy and relevance.
  * [ ] Integrate AI prompting alongside other learning resources such as documentation, tutorials, and mentors.
  * [ ] Prompt responsibly to support your learning, in line with HYF guidelines and expectations.

### [Intro to JavaScript](/course-content/foundation/intro-to-javascript)

* [ ] Understand what JavaScript is and what it's used for
* [ ] Use basic programming concepts such as variable definitions, types and operators
* [ ] Practice reading and fixing errors
* [ ] Use conditional logic to implement more advanced functionality
* [ ] Write basic functions with parameters and arguments
* [ ] Understand global vs local scope
* [ ] Using objects and arrays to store, access and manipulate more complex data

### [Intro to Web Architecture](/course-content/foundation/intro-to-web-architecture)

* [ ] Understand the key components of a web application
* [ ] Know what happens when you enter a URL in a web browser
* [ ] Be able to describe the difference between frontend and backend functionality
* [ ] Describe the role of HTML, CSS and JavaScript
* [ ] Understand what HTTP is and its methods
* [ ] How APIs are provided and used

### [Databases](/course-content/foundation/databases)

* [ ] Explain what a database is and why we use them
* [ ] Understand basic relational data terminology: table, row, column, primary key, foreign key
* [ ] Perform basic SQL operations: SELECT, INSERT, UPDATE, DELETE
* [ ] Use simple filtering and sorting techniques
* [ ] Understand simple database design & schemas

### [Intro to Backend](/course-content/foundation/intro-to-backend)

* [ ] Introduction to Node.js
  * [ ] [What is node and why node?](https://www.youtube.com/watch?v=pU9Q6oiQNd0)
  * [ ] V8 vs the browser that runs js?
  * [ ] What can you build with Node.js?
    * Utilities
    * Web server
    * Much more
* [ ] Building a simple webserver
  * [ ] Creating simple GET endpoints to return data, including from databases
* [ ] Sending requests
  * [ ] What is Postman
  * [ ] Making GET, POST AND DELETE requests to APIs using Postman
* [ ] Database interaction
  * [ ] What is CRUD (Create, Read, Update, Delete)
  * [ ] CRUD vs REST
  * [ ] Connecting to a database using JavaScript
  * [ ] Executing queries (i.e. CRUD)

### [Intro to Frontend](/course-content/foundation/intro-to-frontend)

* [ ] Understand the browser environment
  * [ ] HTML vs CSS vs JS
  * [ ] Client vs server
  * [ ] Where is the script tag being loaded
* [ ] How to use the DOM to implement dynamic functionality
  * [ ] What is it and what do developers use the DOM for?
  * [ ] DOM manipulation
    * [ ] Get elements
    * [ ] Insert elements
    * [ ] Element manipulation (style, innerHTML, text)
    * [ ] Window object
    * [ ] Document object
* [ ] How to use Event Listeners to implement interactivity
  * [ ] Document onload
  * [ ] Click, submit, change, input - Focus on usage
* [ ] Displaying external data
  * [ ] Fetch (No promise explanation! Focus on usage)

### [Intro to Agile](/course-content/foundation/intro-to-agile)

* [ ] What is project management and why is it important
* [ ] Understand the main principles and values of Agile
* [ ] Understand the very basics of Scrum
* [ ] Understand how to use a simple tool to manage tasks, backlog, a board, and a simple project workflow
* [ ] Be able to apply basic prioritisation using MoSCoW
* [ ] Feel equipped to apply basic task and project organisation in your next project (e.g. final project)

### [Career Training](/course-content/foundation/career-training)

* [ ] Understand where to look for suitable jobs and internships
* [ ] Understand what you should do in order to be an attractive candidate on the Danish job market
* [ ] Learn how to identify and communicate your competencies
* [ ] Understand what HYF can do to support you on your job hunt
* [ ] Know how to assemble an effective CV and LinkedIn profile
* [ ] Learn how to perform well in a screening interview

### [Foundation Project](/course-content/foundation/final-project)

* [ ] Practice working in a team on the same project
* [ ] Develop self-guided learning skills (i.e. finding answers to your own problems)
* [ ] Practice building a project from a brief
* [ ] Practice interpreting requirements and making assumptions
* [ ] Developing your own additional requirements (i.e. adding your own flair to the project)
* [ ] Practice breaking big problems down into smaller tasks
* [ ] Managing your own tasks within a tight deadline
* [ ] Understanding how and when to ask for help at the right time
* [ ] Taking a project from idea to completion, including deploying it to the web


# HTML & CSS

During this module you will setup your development environment, review the concepts learned from the [Pre-Course](/course-content/pre-course) materials on HTML and CSS, and discuss the solution of the [order form task](/course-content/foundation/html-and-css/week1/preparation).

| Week | Topic                                                                                                               | Preparation                                                              | Session Plan                                                               | Assignment                                                             |
| ---- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| 1.   | IDE setup, rerun of HTML & CSS concepts with hands on exercises, quick Figma introduction, teamwork & peer-learning | [Preparation](/course-content/foundation/html-and-css/week1/preparation) | [Session Plan](/course-content/foundation/html-and-css/week1/session-plan) | [Assignment](/course-content/foundation/html-and-css/week1/assignment) |

## Learning goals

* [ ] Setup VSCode
* [ ] Round-up the [Pre-Course](/course-content/pre-course) materials on HTML and CSS
* [ ] Spend a lot of time with hands-on coding practice
* [ ] Learn to work efficiently with your team members
* [ ] Briefly introduce Figma


# Week 1

## Contents

* [Preparation](/course-content/foundation/html-and-css/week1/preparation)
* [Session Plan](/course-content/foundation/html-and-css/week1/session-plan) (for mentors)
* [Assignment](/course-content/foundation/html-and-css/week1/assignment)

## Session Learning Goals

See [module learning goals](/course-content/foundation/html-and-css).


# Preparation

During the Pre-Course you've already gone through the basics of HTML, CSS, and JavaScript. Before you come to the first session, we would like you to put all this knowledge to practice by building a simple order form page.

## Order Form Task

### The Design

You can find the design for the order form here: [Order Form Design](https://www.figma.com/file/VwksDkp1vSPhpfa62LWIAz/HTML%2FCSS-session1?type=design\&node-id=0-1\&mode=design\&t=seawrJIXVyPoIt9L-0) (Figma). You should build your solution to match this design.

If you are new to Figma, watch this [10 min intro for developers](https://youtu.be/fZ-OU_7aBv4?feature=shared\&t=68) to get a head start.

### The Code

We have provided some initial code and images for you here: [Code & Images](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/html-and-css/order-form-task). Feel free to use these as a starting point.

Make sure that your code is:

* Properly formatted and indented
* Looking good on both desktop and mobile
* Using CSS class selectors instead of IDs or tags ([Why you should avoid using IDs in CSS](https://medium.com/@clairecodes/reasons-not-to-use-ids-in-css-a42204fb0d97))
* Having no unused CSS properties (avoid using the copy code function in Figma)
* Using correct and semantic HTML ([MDN Web Docs - Semantics in HTML](https://developer.mozilla.org/en-US/docs/Glossary/Semantics#semantics_in_html))

### Submitting the task

Please submit the task using [CodePen](https://codepen.io), and share the link in your team's Slack channel before the session.

### Installing VSCode

Before you come to the session, please also download and install [Visual Studio Code](https://code.visualstudio.com/). You will learn more about how to use the tool in the session. You are welcome to already use VSCode to build this task, if you like, but you still need to submit it via CodePen at the end.


# Session Plan

## Session outline

* Introduction by everyone - you as Session Lead, the Session Assistant(s), the Trainees
* Integrated Development Environments (IDE) and Visual Studio as the standard out there
* Mix of HTML concepts intertwined with VS Code settings as "format on save" and "auto safe on focus change"
* Lots of session exercises
* Emphasize use of autocomplete and copy/paste
* Teach through raising questions and demonstrating how to search for the answers online
* Focus on how to read documentation, MDN - W3Schools, Stack Overflow

## Visual Studio Code

You can either demonstrate the following tips all at once or integrate them throughout the session as appropriate. Remember, the primary focus of this session is HTML and CSS; the VS Code tips are intended to support and accelerate your workflow with these technologies.

* Demonstrate the basics
  * Switching between light and dark themes
  * Open and close different panels (Explorer, Search, Extensions, Terminal, Editor Layout)
  * How to load/drag folders and projects in
  * How to create files
* Recommend extensions (no need to explain all upon install)
  * Prettier - Code formatter
  * Live Server
  * Code Spell Checker
* Important User Settings
  * Auto save on focus change
  * Prettier on focus change
* Extra for the curious
  * Select multiple instances of a string on file `CMD + D`
  * Select and edit multiple lines `Option + Shift`
  * Demonstrate how to add dummy copy through `Lorem10` where the number is equal to the number of words

## HTML

What does it stand for? Emphasize that it's not a programming language. What role does it play in Web Development?

* Explain the document structure - head, body; what goes in the head, what in body (meta tags, styles, scripts)
* Demonstrate the advanced HTML document autocomplete command with `! + Tab`
* Block vs Inline elements
* Attributes (image tags, forms)
* Demonstrate the importance of predictable indentation, nesting, and formatting
* Demonstrate Emmet (Zen coding)
  * Example `ul>li*6>a`
* Tables
* Forms (mention `<label>` tags' `for` and `id` attributes)

### Exercise 0: "Hi, my name is..."

**Objective:** Practice identifying and using block-level vs inline-level elements, and understand their behaviour in layout.

**Instructions:** Create a simple "About Me" bio section using the following requirements:

* Add a header section with heading with your name and tag line of your profession
* Follow with a short paragraph introducing yourself or simply use `lorem50`
* Inside the paragraph, bold your profession and italicize your hobbies
* Create an unordered list of the last 3 movies you've watched
* Add another paragraph (`Lorem25`)
* Follow with an ordered list of the last 3 books you read
* Add an image inside of a container tag (use a placeholder as [PlaceBeer](https://placebeer.com/) or [PlaceCats](https://placecats.com/))
* Make sure the image has caption or `alt` tag
* Upload to [CodePen](https://codepen.io) and share with the team

Challenge Goal:

* Ensure that block elements stack vertically
* Use inline elements inside the paragraph and the image caption, showing they do not force line breaks
* Use proper indentation and nesting

### Exercise 1: Product Table

**Objective:** Practice using the various table tags and learn how to structure tabular data.

**Instructions:** Create a table to display a list of 3 fictional products. The table should include:

* Header rows with column titles for Product Name, Price, In Stock
* Three rows of product data (you can make up the names/prices)
* Use appropriate HTML tags: `table`, `thead`, `tbody`, `tr`, `th`, and `td`
* Caption reading "Available Products"
* Format the code with clean indentation

Bonus: Use Emmet to speed up creation

### Exercise 2: Create a Basic Contact Form

**Objective:** Practice using form-related tags, attributes (`for`, `id`, `name`, `type`, `placeholder`), and improve form semantics.

**Instructions:** Build a simple contact form that includes:

* A `<form>` tag with a submit button
* A field for "First Name"
* "Last Name"
* A dropdown field for "Title" or "Salutation" (Eg., "Mr", "Ms", "Mrs", "Miss", "Dr", "Sir")
* A field labelled "Email"
* Field labelled "Message"
* Enhanced accessibility through associated `<label>` fields with `<input>` fields by using `for` attributes
* Include placeholders for each input field
* Mark at least one field as `required`

Bonus: Use Emmet to scaffold quickly

### Exercise 3: Semantically speaking

**Objective:** Use semantic elements like `<header>`, `<main>`, `<section>`, `<aside>`, and `<footer>` to structure a simple web page.

**Instructions:** Create a mockup of a simple personal blog page with the following sections:

* Header:
  * Include the page title (`h1`) and a short tagline (`p` or `h2`).
* Main:
  * Contain two `section`s:
    * A featured article with a heading and a paragraph (use [Cupcake Ipsum](https://cupcakeipsum.com/) if tired or the `lorem10` ipsum)
    * Second Section that lists recent posts (use `ul>li*4>a`, add `#` for the `href` attribute)
* Aside with a small bio or a list of favourite links
* Footer with copyright disclaimer and current year

Focus on:

* Consistent indentation and proper nesting
* Using tags for structure, not for styling
* Adding comments (`<!-- like this -->`) to identify non-semantic tags

## CSS

What does it stand for? What role does it play in Web Development?

* Ways to write CSS (inline, internal, external)
* Selectors - tag, class, id
* Touch upon specificity
* Inline and block elements
* Box model - padding, border, margin, outline
* Shorthand
* Positioning
* Responsive, mobile first, media queries
* CSS units - px, em, rem, %, vh, vw
* Variables
* Normalize, reset

### Exercise 4

**Objective:** Apply core CSS concepts to style one of your previous HTML exercises using external CSS (the right way to use CSS).

**Instructions:**

* Use external CSS
* Add a normalize or reset stylesheet
* Make one element absolute or fixed positioned (e.g., sticky nav)
* Use at least one media query
* Add hover and focus state to clickable elements such as `a` and `button`


# Assignment

Complete all exercises from the Sunday session.

Make sure to:

* Add some CSS animations
* Use CSS variables
* Use semantic markup

Upload your solutions to CodePen and share with the rest of the team through Slack. Have a look at the implementations of others, and reach out to learn how they've made them.

![Jim Carrey as the eponymous "Bruce Almighty", busily typing away](https://media.giphy.com/media/13GIgrGdslD9oQ/giphy.gif)


# Git

The main goal of this session is to introduce you to Git and how to work with Commits, Pull Requests, and Branches.

| Week | Topic               | Preparation                                                     | Session Plan                                                      | Assignment                                                    |
| ---- | ------------------- | --------------------------------------------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------- |
| 1.   | Introduction to Git | [Preparation](/course-content/foundation/git/week1/preparation) | [Session Plan](/course-content/foundation/git/week1/session-plan) | [Assignment](/course-content/foundation/git/week1/assignment) |

## Learning goals

* [ ] Understand what version control is
* [ ] Understand what Git is used for
* [ ] Know the difference between Git and GitHub
* [ ] Successfully install and configure Git
* [ ] Practice command line basics
* [ ] Know how to create a repo, branches, commits and push to GitHub
* [ ] Understand the usual flow for saving and sharing changes


# Week 1

## Contents

* [Preparation](/course-content/foundation/git/week1/preparation)
* [Session Plan](/course-content/foundation/git/week1/session-plan) (for mentors)
* [Assignment](/course-content/foundation/git/week1/assignment)

## Session Learning Goals

See [module learning goals](/course-content/foundation/git).


# Preparation

Readings:

* What is Version Control: <https://www.atlassian.com/git/tutorials/what-is-version-control> (5 min)
* What is Git: <https://www.atlassian.com/git/tutorials/what-is-git> (6 min)

Github:

* please, create an account on [Github.com](https://github.com/) if you haven't created one yet

Git:

* Install Git before the Sunday session:
* Mac: it should be sufficient to run `brew install git` in the Terminal
  * Homebrew is a popular package manager for macOS (and Linux), used to easily install and manage software via the command line. You can install it easily by following the instructions on <https://brew.sh/>
* Ubuntu (or any Debian based Linux system): run `sudo apt-get install git` in the Terminal
* Windows: [download and install Git for Windows](https://gitforwindows.org/). Step by step instructions:

  ![Git for Windows download page](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-dbe358cc4316976798ae3d192593e6a5e3369883%2Fgit-windows.jpg?alt=media)

  1. Scroll to the bottom of the [download git page](https://github.com/git-for-windows/git/releases/latest) and download the latest version `.exe` file. It would generally be the most downloaded file from the list.
  2. execute the file you downloaded
  3. on the `Information` screen, click next
  4. on the `Select Destination Location` screen, click next
  5. on the `Select Components` screen, click next without changing anything
  6. on the `Select Start Menu Folder` screen, click next
  7. `Choosing the default editor used by Git`, select `Use Vim` and click next
  8. `Adjusting the name of the initial branch in new git repositories`, select `Let Git decide`
  9. `Adjusting your path environment`, select `Use Git from Git Bash only` and click next
  10. `Choosing HTTPS transport backend`, select `Use the OpenSSL library` and click next
  11. `Configuring the line ending conversions`, select `Checkout Windows-style, commit Unix-style line endings` and click next
  12. `Configuring the terminal emulator to use with Git Bash`, select `Use MinTTY` and click next
  13. `Choose the default behaviour of "git pull"`, choose `Default (fast-forward or merge)`
  14. `Choose a credential helper`, choose `Git Credential Manager Core`
  15. `Configuring extra options`, select `Enable file system caching` and `Enable Git Credential manager`, click next
  16. `Configuring experimental options`, do not select any of them, and click install
  17. and you should be pretty much done :)
* it is **\*very important** that you set up your SSH keys by following those [instructions on Github](https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent), or [this video](https://drive.google.com/file/d/1qDA4g3WcaHI_qbvOgB4cVLoVsi8HCcC2/view?usp=sharing)

Optionally, if you are using Windows and want to use Git Bash on VS Code, [follow the instructions in this StackOverflow answer](https://stackoverflow.com/a/50527994/1121986). Linux and MacOS users don't need to do anything related to that - Git Bash on VS Code works right out of the box.


# Session Plan

## Session materials

These are some examples of previously created materials by mentors that you can use yourself, or for inspiration.

* [Introduction to Git](https://radical-somersault-80b.notion.site/Introduction-to-Git-184dc1cafb9480ffad0de16e6ea8b379) (by [@aina21](https://github.com/aina21), Team 31)
* [Git Basics](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/git/week1/session-materials/Git-basics.pdf)
* [Git Branches](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/git/week1/session-materials/Git-branches.pdf)

## Session outline

1. What is version control?
   * Version control is like a super-organized notebook that keeps a history of all the changes made to your project folders and files. It lets you:
     * Go back to older versions if something goes wrong
     * See who made each change
     * Work with others without overwriting each other’s work
   * Google docs demonstration
2. Git - the most popular version control system
   * Git is a version control system, widely used by software developers (and not only). Think of it as a smart time machine for your files—especially code or text documents.
     * **Save a snapshot** of your project (called a **commit**) at any point
     * **Compare** changes between versions
     * **Work together** with other people and combine everyone’s work smoothly
     * **Experiment** with new ideas safely, without messing up the main project
3. Git vs. GitHub ([Slide 3 from Git-basics.pdf](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/git/week1/session-materials/Git-basics.pdf))
   * Git
     * Version control software on your computer
     * Works offline (no need for internet)
     * Command-Line Interface based, but has various graphical interface alternatives as GitHub Desktop, GitKraken, SourceTree
   * GitHub
     * Website that hosts Git repositories in the cloud
     * Web interface for viewing code and changes
     * Collaboration tools (pull requests, projects, issues, comments)
     * Enabled social coding (followers, stars, forks, use profiles)
4. Install Git if not done already
5. Configure Git
   * `git config --global user.name "name"`
   * `git config --global user.email "email"`
   * `git config --global core.editor "code -w"` (without `-w` the commit is aborted with empty message)
6. Command line basics
   * `pwd`, and explain how paths work
   * `ls`
   * `cd`
   * `cd ..`
   * `mkdir`
   * do a little exercise
7. What is a repository and how to create one ([Slide 4, Git-basics.pdf](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/git/week1/session-materials/Git-basics.pdf))

   * kind of a folder, but not all files in the folder have to be in the repository
   * `git init`
   * Clone an existing repository

   Golden rule:

   * ALWAYS make sure you are not inside a git repository when you create a new one. You can check by typing `git status` in your Terminal. If you get an error it means you are not inside a git repository and you can safely create a new one.
8. The commit ([Slide 7, Git-basics.pdf](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/git/week1/session-materials/Git-basics.pdf))
   * a snapshot of the entire repository
   * who made the changes
   * when the changes were made
   * a message describing the changes in the commit
9. Demonstration to making a commit
   * what happens after each `git add` and `git commit`
   * show how to `git add` all changes, or specific files
   * show `git status` and `git log`
10. Explain what happens after `git push`
11. Branches (Exercise 2, [Git-branches.pdf](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/git/week1/session-materials/Git-branches.pdf))
    1. Create a branch
    2. Make a commit
    3. push changes to remote
12. Pull Requests
    1. Create a pull request
    2. Reviewing a pull request (commenting, approving, requesting changes)
    3. Merging a pull request
    4. Updating local `main`
13. Forks
    * Your "copy" of a source repository
    * How forks are useful for collaboration
14. Useful VS Code extensions
    * GitLens - Git supercharged
    * GitHub Pull Requests

### Exercise 1

**Objective:** The goal is to set up your assignment repository fork and create your first PR (Pull Request).

> \[!NOTE] You will use this repository to hand in your assignments during the entire HackYourFuture program.

1. Create a repository fork on your GitHub and clone it locally, following the instructions from [HackYourFuture-CPH/hyf-assignment-template](https://github.com/HackYourFuture-CPH/hyf-assignment-template)
2. Check out to a new branch called `html-and-css`
3. Add the session exercises from the previous week to the `html-css/week1` folder
4. Create a PR (Pull Request) [to your own repository](https://github.com/HackYourFuture-CPH/hyf-assignment-template?tab=readme-ov-file#2-submission-process), from your `html-and-css` branch to merge changes into the `main` branch
5. Finally, have the person on your right review this PR before you agree to merge it to `main`.

**Tips for this exercise:**

* Use descriptive `commit` messages
* Make a commit for each folder/exercise you add (makes it easier to track changes/updates)
* Switch between the Terminal and GitHub on each `commit` and `push` to learn better what each command exactly does
* Merge, after the person on your right has reviewed and **approved**. You might need to first address any comments they might have.

### Exercise 2

1. When you are on `main` branch, of the assignment repository create a branch named `git-week1/exercise-1/<your-name>` and move to it
2. Create a folder named `session-playground` in the `git` folder, under `/week1`
3. Create the following files inside the `session-playground` folder: `apples-file.txt`, `bananas-file.txt`, `oranges-file.txt`
4. Add some text to each of the files
5. Add and commit the `apples-file.txt`
6. Add and commit both the `oranges-file.txt` and the `bananas-file.txt`
7. Add more text to the `apples-file.txt`
8. Add and commit the changes in the `apples-file.txt`
9. Push your changes to GitHub
10. Go to the branch on GitHub and look at the commits, analyze and discuss how it looks and how it connects with what you just did

### Exercise 3

**Objective:** The goal of this exercise is to practice the assignment workflow.

1. When you are on `main` branch, create a branch named `git-week1/exercise-3/<your-name>` and move to it
2. Create a file named `my-assignment.txt` in the `git` folder, under `/week1/session-playground`
3. Add some text to the `my-assignment.txt` file
4. Add and commit the changes in the `my-assignment.txt` file
5. Add more text to the `my-assignment.txt` file
6. Add and commit the changes in the `my-assignment.txt` file
7. Push your changes to GitHub
8. On GitHub, create a pull request (on your own fork) from the exercise branch to `main`
9. On your computer add some more text to the `my-assignment.txt` file
10. On your computer, add and commit the changes in the `my-assignment.txt` file
11. Push the changes to GitHub
12. On GitHub, check what happened to the pull request you created in step 8.
13. Merge the pull request.
14. Locally, go to the `main` branch and update `main` by "downloading" the new commits from GitHub: `git pull origin main`.

### Exercise 4

**Objective:** Face your first Git error and try to find a solution online on your own.

1. On your assignment repository go to the branch `main`, create a branch `git-week1/exercise-4/<your-name>` and move to it
2. In the `git` folder, under `/week1/session-playground`, create a file named `colors.txt`
3. Add two colors to the file `colors.txt`, one per line
4. Add and commit the changes in the `colors.txt` file
5. Push the branch `git-exercise-4` to GitHub.
6. **On GitHub**, go to the branch `git-exercise-4` and add a color in the last line of the file `colors.txt`, commit your changes
7. **On your computer**, add a color in the first line of the file `colors.txt`, add and commit your changes
8. Push the branch `git-exercise-4` to GitHub. Discuss what is happening and how to solve it.

### Exercise 5

**Objective:** Learn to handle a common mistake of forgetting to checkout to the right branch, when already having a few commits pushed.

1. On your assignment repository **DON'T** go to the main branch, make sure to stay on the branch from the previous exercise.
2. Create a branch `git/week1/exercise-5/<your-name>` and move to it
3. In the `git` folder, under `/week1/session-playground`, create a file named `movies.txt`
4. Add two movie names to the file `movies.txt`, one per line
5. Add and commit the changes in the `movies.txt` file
6. Push the branch `git-exercise-5` to GitHub.
7. On GitHub, create a pull request from your new branch to `main`.
8. See what commits you have there - do you only have commits from this exercise? Do you have commits that should not be here? Discuss why it happened and how to solve this situation.

### Exercise 6: Into the deeps

**Objective:** Get comfortable with branching. Take notes of the answers to the questions in points 14, 15, 16, 17, 18, 19, 22, 23, 25, and 26. Discuss the answers in pairs.

1. Create a new folder in your Desktop called `branch-exercise`
2. Using the command line go to that folder and create a new repository there (`git init`)
3. Create a new file in that folder called `countries.txt`
4. Add two country names (one per line) to the `countries.txt` file
5. Commit your changes
6. Create a new branch named `add-countries`, move to that branch
7. Add two more country names (one per line) to the `countries.txt` file
8. Commit your changes
9. Go back to `main`
10. Create a new branch named `add-cities`, move to that branch
11. Create a new file named `cities.txt`
12. Add two city names (one per line) to the `cities.txt` file
13. Commit your changes
14. Go back to `main` and take a look around your folder. Which files do you see? What are their contents?
15. Do `git log --oneline`. Which commits do you see?
16. Go to the `add-countries` branch and take a look around your folder. Which files do you see? What are their contents?
17. Do `git log --oneline`. Which commits do you see?
18. Go to the `add-cities` branch and again take a look around your folder. Which files do you see? What are their contents?
19. Do git `log --oneline`. Which commits do you see?
20. Now go to `main`
21. Merge the branch `add-countries` with main (`git merge add-countries`)
22. Take a look at your folder, which files do you see? What are their contents?
23. Do `git log --oneline`. Which commits do you see?
24. Now merge the branch `add-cities` with main (`git merge add-cities`)
25. Take a look at your folder, which files do you see? What are their contents?
26. Do `git log --oneline`. Which commits do you see?

## Other material and links

* [**Cheat-sheet**](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/git/week1/session-materials/cheatsheet.md) - sheet of the commands used during the session
* [**Git Basics**](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/git/week1/session-materials/Git-basics.pdf) - the slides used to teach some concepts during the session.
* [**Learn Git Branching**](https://learngitbranching.js.org/) - interactive website for... learning Git branching
* [**Oh My Git**](https://ohmygit.org/) - open source game for learning everything Git


# Assignment

Finish all exercises from the session, then do the following:

## Exercise 1

In this exercise you will get some practice submitting your assignment by pushing it to GitHub and then creating a pull request. You will be using this workflow every week to submit your assignment, so it's important that you get comfortable with it. You will also practice adding/committing files one by one.

You will use the Assignment repository created on the last session. Here are the instructions:

1. In your terminal, navigate to your assignment repository on your computer
2. Go to branch `main`
3. Pull the latest changes to make sure your local `main` is up to date
4. Create a branch for your assignment, named `git-week1/your-name`, and move to that branch
5. Inside the folder `git/week1` create 3 new files:
   * a file named `my-favourite-food.txt`, inside the file write your favourite dish recipe (you can just find a random recipe on Google and paste it in the file ;)
   * a file named `my-second-favourite-food.txt`, inside the file write the recipe for your second favourite dish
   * a file named `countries.txt`, where you list three countries that you have visited (this doesn't need to be true, you can just write the names of three random countries)
6. Add and commit the file `my-favourite-food.txt`
7. Add and commit the file `my-second-favourite-food.txt`
8. Add and commit the file `countries.txt`
9. Push your changes into your assignment repository on GitHub
10. Go to GitHub and create a pull request (PR) from the branch `git-week1/your-name` to `main`

> \[!TIP] In the future, you can find a reminder of how to submit your assignments in the "Readme.md" file in your assignments repo, under the heading "Completing the assignments".

## Cheat sheet / tips

Commands that you will need:

* `git branch <branch-name>` - to create a new branch named `<branch-name>`
* `git checkout <branch-name>` - to move to a branch named `<branch-name>`
* `git add <file_name>` - tell git to start tracking a file and to update what will be committed
* `git add .` - add all modified files to staging for commit
* `git commit -m "commit_message"` - commit (save) your changes
* `git push origin <branch-name>` - push (upload) your changes in your current branch to your GitHub repository into the branch named `<branch-name>`.

***Note*** For the sake of consistency (and to avoid mistakes), make sure that when you push you do it to a branch with the same name as the branch where you are, e.g. if you are on a branch named `git-week1` then push to a branch named `git-week1` by typing `git push origin git-week1`.

When pulling, if you want to pull from a branch named, for instance `main`, make sure that you are in a branch with the same name (`main`) on your computer as well, and only then do `git pull origin <branch-name>`.

Other useful git commands:

* `git status` - remember, it is your best friend, it tells you what is the state of your repository and sometimes what you should do.
* `git branch` - this is your second best friend, it tells you in which branch you are (you can also see where you are when you do `git status`)
* `git log`
* `git log --oneline`
* `git pull origin <branch-name>` - pull (download) your changes from your GitHub repository in the branch named `<branch-name>`, into your current local branch.

Command line commands that might be useful:

* `pwd`- print working directory, to know where you are
* `cd <folder_name>` - to go inside a folder named `<folder_name>`
* `cd ..`- to go to the parent folder of your current folder
* `mkdir <folder_name>` - to create a new folder
* `ls`- list all the folder contents
* `ls .*` - list all the folder contents, also invisible folders/files (e.g. the git folder)


# Intro to Using AI

This module aims to introduce you to the world of AI, what it means, how it works, and basic use cases where it can help you learn and develop your technical skills and knowledge in an effective way.

## Contents

| Week | Topic                                                                         | Preparation                                                                   | Session Plan                                                                                  | Assignment                                                                  |
| ---- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| 1.   | [AI Literacy & Prompting](/course-content/foundation/intro-to-using-ai/week1) | [Preparation](/course-content/foundation/intro-to-using-ai/week1/preparation) | [Session Plan](/course-content/foundation/intro-to-using-ai/week1/session-plan) (for mentors) | [Assignment](/course-content/foundation/intro-to-using-ai/week1/assignment) |

## Learning Goals

By the end of this module, you will be able to:

* [ ] AI Literacy:
  * [ ] Describe how Large Language Models (LLMs) work at a basic level.
  * [ ] Explain what Generative AI (AI) is, what it's good at, and its limitations.
  * [ ] Identify appropriate and inappropriate uses of AI in the workplace.
  * [ ] Practice how you can use AI to help you learn effectively, rather than just providing answers.
  * [ ] Recognize common risks related to AI usage, such as bias, copyright, hallucinations, misinformation, and privacy concerns.
  * [ ] Reflect on how AI is changing work and skill expectations (and what we don't know yet!).
* [ ] Prompting:
  * [ ] Apply simple prompting techniques to get useful outputs from GitHub Copilot.
  * [ ] Evaluate AI outputs critically for accuracy and relevance.
  * [ ] Integrate AI prompting alongside other learning resources such as documentation, tutorials, and mentors.
  * [ ] Prompt responsibly to support your learning, in line with HYF guidelines and expectations.


# Week 1

## Contents

* [Preparation](/course-content/foundation/intro-to-using-ai/week1/preparation)
* [Session Plan](/course-content/foundation/intro-to-using-ai/week1/session-plan) (for mentors)
* [Assignment](/course-content/foundation/intro-to-using-ai/week1/assignment)

## Session Learning Goals

See [module learning goals](/course-content/foundation/intro-to-using-ai).


# Preparation

## Mandatory

### Refresher on the HYF AI guidelines

Re-read our guideline so you're clear on the acceptable (and unacceptable) usages of AI at HYF:

* [Using Generative AI at HackYourFuture](https://program.hackyourfuture.dk/trainee/agreements/ai-usage)

### What is Generative AI and how to use it?

* Watch [Generative AI Explained In 5 Minutes - Simplilearn](https://www.youtube.com/watch?v=NRmAXDWJVnU) (5 mins)
* Watch [AI in a Minute: Prompt Engineering - Microsoft](https://www.youtube.com/watch?v=vGdyePbGNaE) (1 mins)
* Watch [Essential AI prompts for developers - Microsoft](https://www.youtube.com/watch?v=H3M95i4iS5c) (8 mins)
* Watch [Master the core principles of prompt engineering with GitHub Copilot](https://www.youtube.com/watch?v=hh1nOX14TyY) (6 mins)

### Installing Copilot

The AI tool of choice at HYF is GitHub Copilot. It integrates nicely with VSCode, which you already have installed. Follow the instructions below to install Copilot before you come to the session.

* [Getting started with GitHub Copilot | Tutorial](https://www.youtube.com/watch?v=n0NlxUyA7FI) (10 mins)

## Optional

If you'd like to gain a deeper understanding of Generative AI, watch the below:

* Watch [Introduction to Generative AI - Google](https://www.youtube.com/watch?v=G2fqAlgmoPo) (22 mins)
* Watch [Fundamentals of Generative AI - Microsoft](https://learn.microsoft.com/en-us/shows/on-demand-instructor-led-training-series/ai-900-05-fy25) (40 mins)

Further reading on environmental and ethical impacts of using AI:

* Read opinion piece [Big tech's selective disclosure masks AI's real climate impact](https://ketanjoshi.co/2025/08/23/big-techs-selective-disclosure-masks-ais-real-climate-impact/) (15 mins)


# Session Plan

## Session materials

These are some examples of previously created materials by mentors that you can use yourself, or for inspiration.

* [Introduction to Generative AI](https://docs.google.com/presentation/d/1nj1H-6Oz6ZDRRwfq9u_m3k8y5RosHdPU/edit?slide=id.p1#slide=id.p1) (by [@hosseinzahed](https://github.com/hosseinzahed))
* [AI Risks and Ethics (slides)](https://docs.google.com/presentation/d/1I20KMYhkZJJAUad6mFgAOT5CVeHV-eKSI4VRF1QEuiQ/edit?usp=sharing) (by [@axelsorensen](https://www.linkedin.com/in/axel-sorensen/))
* [Kahoot Quiz](https://play.kahoot.it/v2/?quizId=fc4f12d6-7f17-48e4-b755-5c567a6e2d0c) - Interactive quiz comparing trainees' best guesses on the most likely next token to that of an LLM, demonstrating bias (feel free to edit and shorten) (by [@axelsorensen](https://www.linkedin.com/in/axel-sorensen/))

## Part 0: Review AI HYF AI Guidelines (10 mins)

* Run through the [HYF AI Guideline](https://program.hackyourfuture.dk/trainee/agreements/ai-usage) and see if anyone has any questions to clarify.

It is really important that everyone is in alignment of how AI can and should be used as part of the HYF programme. Answer all relevant questions from the trainees before moving on.

Key points to reiterate:

* The world of AI is changing rapidly, and we don't have all the answers yet.
* We know many workplaces are testing AI in different ways, which is why we want you to have some practice using it.
* It can easily stunt learning if used incorrectly, which is why we have strong opinions on the right way to use it during HYF.
* You don't *have* to use AI to support your learning during other modules. If you do, it should be combined with other forms of learning and documentation. You'll learn more about this today!

## Part 1: Foundations of Generative AI (40 mins)

* Icebreaker: "Where have you already seen AI being used?"
* **Mini-lecture + short video**: What is Generative AI? (LLMs, what they can/can’t do)
* Activity: Students sketch a quick analogy (“LLM is like…”) to explain AI simply.
* Discussion: Benefits vs. limitations in workplace and learning.

## Part 2: AI Literacy in Practice (45 mins)

* Risks & Ethics: Bias, misinformation, copyright, hallucinations, privacy.
  * Bias: AI may reproduce or amplify unfair stereotypes present in its training data.
    * An AI CV screener favors male applicants over female ones because it was trained on biased hiring data.
    * An image generator depicts “CEO” as only men and “nurse” as only women.
    * A chatbot gives more positive descriptions for English text than for the same text written in another language.
  * Misinformation: AI can generate content that looks convincing but is factually incorrect.
    * A language model says the capital of Australia is Sydney (when it’s actually Canberra).
    * An AI health assistant suggests drinking soda as a cure for illness.
    * A generative AI summarizes a news event but mixes up key details, like dates or people involved.
  * Copyright: AI outputs may unintentionally reuse or mimic protected material without permission.
    * An AI tool generates code that is almost identical to proprietary code from GitHub repos.
    * A generative art model produces an image nearly identical to a famous cartoon character.
    * An AI text generator reproduces long paragraphs from a copyrighted book word-for-word.
  * Hallucinations: AI sometimes invents details or answers that sound plausible but are not true.
    * An AI chatbot “cites” fake academic papers that don’t exist.
    * A travel assistant AI invents a train schedule for a route that isn’t actually running.
    * A programming assistant suggests using a non-existent JavaScript function.
  * Privacy: Using AI tools can risk exposing personal or sensitive information if not handled carefully.
    * A student pastes their friend’s phone number into ChatGPT to “test” a feature, unknowingly sharing private data.
    * An employee uploads confidential customer records to an AI assistant to generate a report.
    * A medical chatbot stores patients’ health details without their consent.
  * Environmental: High demands for energy and hardware, and high waste, together raise serious considerations for AI usage.
    * Training and running large AI models consumes significant energy and water, contributing to carbon emissions.
    * Continuous need for powerful hardware accelerates mining, manufacturing, and disposal of electronic components.
    * Environmental burdens (e.g. mining, data center siting) often fall disproportionately on vulnerable communities, raising ethical concerns.
* Case study: Short scenarios where AI could be helpful or harmful.
* Group activity: Sort examples into *appropriate vs inappropriate* uses.
* Reflection: “How might AI change the skills needed in your future jobs?”

## Break (10 mins)

## Part 3: Learning with AI (60 mins)

Demonstrate using Copilot to support learning through an example task. It is important to set a good example inline with the AI Usage guidelines, since this is the first time we are introducing AI to the trainees.

### The AI questions framework

Every time a trainee uses AI to support their learning or completing tasks, they should ask themselves these questions:

1. Do I understand everything it has written? If not, ask it to explain or choose a different solution!
2. Does the answer really fit my use case? If not, edit the code yourself or try again!
3. Am I sure the answer is correct? If not, validate it with other sources!

Run through the task below and use this framework at each step. There are examples below, but feel free to freestyle.

### The task

Let's look at using AI to help us create a simple HTML page with some content. Here's what we want to build:

* A HTML page with a heading, a paragraph, and a list of 3 items.
* The heading should be centered, the paragraph text color should be blue, and the list items bold.
* When the page loads, an alert should pop up and say "Welcome".

### 1. Getting started

"You have all created HTML pages before, but maybe it isn't easy to remember everything you need to include in a new HTML page."

Prompt:

```
I'm creating a new HTML page. Remind me what a basic html page should look like. I need a very simple starting point.
```

Go through the AI questions, and make follow up prompts or changes to the code before moving on.

1. Do I understand everything it has written? **No!**

Prompt:

```
Explain what "<meta charset="utf-8" />" means in simple terms.
```

2. Does the answer fit my use case? **Mostly, but it added some extra things that aren't needed right now (that could be some text, extra elements, or external stylesheets). Remove these manually.**
3. Am I sure the answer is correct? **Yes! We've seen similar HTML many times before, so we are feeling confident.**

#### Exercise 1

The trainees should now follow similar steps on their own:

1. Create their own basic HTML page
2. Go through each AI question
3. Write down and share three learnings from the first question

Discuss some of the learnings together in the team.

### 2. Adding the content

"For the sake of this task, let's assume we can remember how to add a header, paragraph and a list, so we will write this code manually together. You're not sure know how to center a header though, so get some help from AI:"

Prompt:

```
What options do I have for centering a header? Explain the pros and cons to each.
```

Talk through each of the options, and discuss with the trainees what the right solution might be. Make the change in the code.

Review the AI questions:

1. Do I understand the solution? **If there is something trainees don't understand, make a follow up prompt together.**
2. Does it fit my use case? **Yes, it appears to be correct based on the pros and cons.**
3. Am I sure the answer is correct? **Yes, the header becomes centered and nothing else breaks.**

#### Exercise 2

The trainees should make these changes in their code as well, along with the two other styling changes (blue text and bold list items).

Similar to the centering prompt, trainees should ask AI to help with at least one of these other requirements.

Get some trainees to share with the team what options they learned about, what they chose and why. Discuss any differences.

### 3. New functionality

"Now we need to add an alert when the page loads. We need to learn something new here."

Prompt:

```
How can I add the functionality so when the page loads an alert pops up and says "Welcome"?
```

1. Do I understand everything it has written? **No, this is all new to use! Let's pretend we haven't used JavaScript before.**

Prompt:

```
Can you explain the script tag solution line by line?
```

2. Does the solution fit my use case? **Yes, it appears to do what I need in a simple way.**
3. Am I sure the answer is correct? **It's new to me, so we're not 100% confident. Let's research it some more...**

#### Exercise 3

Brainstorm together other ways to validate the solution(s) suggested by AI. These could include:

* Asking a mentor/more experienced colleague
* Googling for other perspectives
* Official documentation
* and more

Ask the trainees to find some official documentation to validate the solution we are thinking to use. They should share their findings with the group.

(If they need more direction, guide them towards MDN, W3School etc. for ["alert"](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert) and ["DOMContentLoaded" event](https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event), and read through it together).

### 4. The Comparison

So now have a html page built in line with the requriements. Do a quick run through of all the things the team has learned along the way (from AI). Literally count them by going through the prompt history, and asking trainees. Write the number down - it's just a rough estimate, but we need it later!

"AI can also produce all of this code upfront, with one prompt (or so). It's very impressive! Let's look at in action."

Prompt:

```
Create a web page with the following requirements:
- A HTML page with a heading, a paragraph, and a list of 3 items.
- The heading should be centered, the paragraph text color should be blue, and the list items bold.
- When the page loads, an alert should pop up and say "Welcome".
```

Compare the AI generated code with the one you built as a team. Discuss any differences. Looks for things like:

* Parts that AI "made up" like choosing a font, text, styles, layouts that we didn't ask it to do
* Overcomplicated parts like additional CSS classes or styling that is unnecessary in our task

#### The conclusion

If we used this prompt at the start of the task, we wouldn't have learned all we did along the way. This is bad, since we're here at HYF to learn as much as we possibly can.

In the first approach, we learned X things (quote the number from before), and this was all from just this one exercise!

Simple maths for impact: You learned X new things just today. Over the 36 weeks of HYF, that that could easily mean Y new learnings if you follow these steps for using AI effectively. Don't miss out on your learning and development by using AI the wrong way!

## Part 4: Prompting Techniques & Critical Evaluation (50 mins)

Now the basic workflow for using AI is understood, dive deeper into prompting techniques and evaluating its outputs.

"Think of AI as a study partner, not a code vending machine. The better you explain what you need, the better the help you’ll get."

### Tips & tricks

1. Give context – Mention what you already know, your goal, and where you’re stuck.
2. Be specific – Instead of “Explain CSS”, ask “Can you explain how CSS flexbox works with an example for aligning items horizontally?”
3. Ask step by step – Break problems into smaller questions.
4. Request explanations, not just answers – Say “explain in simple terms” or “walk me through your reasoning” instead of “give me the code.”
5. Compare and contrast – Ask “What’s the difference between…” or “When should I use X vs Y?”
6. Ask for examples and analogies – Concrete examples help more than abstract, theoretical descriptions.
7. Check your understanding – After reading the answer, try rephrasing it yourself and ask: “Is this correct?”
8. Iterate on answers – If the first answer isn’t clear, ask the AI to simplify, rephrase, or tweak your question.
9. Study buddy - AI makes a great learning partner. Ask it to ask you questions to check your understanding, provide cheat sheets, mini exercises and other learning resources. It will check your answers too!

### Prompting template

This template captures some of the tips above to form a good starting point:

```
I am learning [topic, e.g. JavaScript loops].
I already understand [what you know so far, e.g. JavaScript variables].
I am stuck on / I want to learn [specific question or confusion, e.g. different ways for looping over an array].

Can you:
1. Explain it step by step, attaching links to relevant documentation
2. Show me a simple example
3. Ask me a question to check my understanding
```

#### Exercise 4

Let's add new functionality to our HTML page. We want the page to display differently depending on the screen size using responsive design. Choose a part of the design (e.g. font size, colours, layouts - use your imagination!) to display differently on mobile vs desktop sized screens.

1. Use the prompting template above to learn more about how you'd implement the functionality
2. Compare prompts with the person next to you and the output it gave. Which was more effective, accurate and useful? Why?
3. Implement the changes in your code. Remember: ask yourself the "AI questions" from earlier before making any changes!

## Part 5: Reflection & Wrap-Up (30 mins)

* Group discussion: What worked well with Copilot? What was frustrating? When should you trust Copilot, and when should you double-check? How can you double-check?
* Reflective writing: “How will I use AI responsibly to support my learning?”
* Quick Q\&A: Connect AI literacy to long-term skill growth.
* Recap of key takeaways (AI Usage guideline, AI questions, tips, prompting template)

## Extra Notes

Some notes from previous conversations, that could be used as inspiration/included somehow:

* [Suggestions from @te-online](https://github.com/HackYourFuture-CPH/programme/pull/118#issuecomment-3070705560)
* [Github has a whole bunch of public training content for copilot, which we could heavily base ours on](https://skills.github.com/#take-flight-with-github-copilot)


# Assignment

## Build & reflect on a Personal Portfolio

### Task overview

Many people choose to have a personal portfolio website to showcase their projects, skills and experiences. It can be a nice website to share during job applications too, for hiring managers to get a quick and visual insight into who you are.

In this task, you will create the starting point of your very own portfolio. You will create a single, simple, styled page using **HTML, CSS, and JavaScript** with the support of **GitHub Copilot**. Along the way, you’ll practice writing prompts, evaluating Copilot’s outputs, and reflecting on responsible use of AI in learning.

For each step, remember to follow:

1. [The Prompting Template](/course-content/foundation/intro-to-using-ai/week1/session-plan#prompting-template)
2. [The AI Questions Framework](/course-content/foundation/intro-to-using-ai/week1/session-plan#the-ai-questions-framework)

### Part 1: Build the page

1. **Basic structure** - Create a page with a heading "About Me", a short introduction paragraph about yourself, and a list of 3 interests/skills.
2. **Add styling** - Add styling to the page to centre the heading, add a custom font, and a background color.
3. **Add interactivity** - Add a fun button on the page that changes the background to a random color when it's clicked.
4. **Make it responsive** - Use media queries to style the page for mobile and desktop size screens.

### Part 2: Reflection

Answer the following questions with short answers (3-5 sentences):

1. Identify and share **3 new things** you learned from AI in the above task.
2. Where did you have to tweak or correct Copilot’s suggestions to suit your needs?
3. How would you explain the difference between using Copilot to **generate code** for you vs. using it as an effective **learning partner**?
4. Identify **3 risks of relying too much on AI tools** when learning at HackYourFuture.

### Submission

Submit your code as usual, and create a text file named `reflection.md` alongside your code to write your answers to the above questions.

### What next?

After you've submitted this assignment, feel free to continue building and updating your portfolio as you progress through the course.

If you need some ideas about what you can add, think about:

* Project showcases - Describe and link to projects you build.
* Skills and certifications - As your learn new skills in the course, or outside of HYF, add them to your portfolio so people know what you're experienced in.
* Blog - A place to share your learnings, thoughts and write more about your projects.
* A little personality - Add photos, mini biographies, and your own design style help visitors see a little more of your personality.
* Play around and have fun - Your portfolio is a personal project that you can use to test out new technologies, tools, design ideas and fun features, so treat it like a playground to try new things.
* Host it online - Later in the course you'll learn more about deploying projects to the web. If you're too excited to wait, look into trying [GitHub Pages](https://docs.github.com/en/pages).

Need more inspiration? Find some online! Our very own mentor, Hossein, has a great example of a personal website at [hossein.dk](http://hossein.dk). There's also plenty of blog posts out there like ["Top 23 Web Developer Portfolio Examples to Inspire Your Own"](https://www.wearedevelopers.com/en/magazine/161/web-developer-portfolio-examples), so start here and explore more yourself.


# Intro to JavaScript

Here you can find course content and the assignments for the Intro to JavaScript module.

| Week | Topic                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | Preparation                                                                     | Assignment                                                                    | Session Plan                                                                      |
| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| 1.   | Intro JavaScript (What is it, what can you use it for); Setup js either via browser or via node; [Variables: var, let, const](/course-content/foundation/intro-to-javascript/week1#variables); Console.log; [Types](/course-content/foundation/intro-to-javascript/week1#Types): [String](/course-content/foundation/intro-to-javascript/week1#String), [number](/course-content/foundation/intro-to-javascript/week1#Number), boolean, [null, undefined](/course-content/foundation/intro-to-javascript/week1#Null--undefined), [array](/course-content/foundation/intro-to-javascript/week1#Array); [Operators](/course-content/foundation/intro-to-javascript/week1#comparison-operators) | [Preparation](/course-content/foundation/intro-to-javascript/week1/preparation) | [Assignment](/course-content/foundation/intro-to-javascript/week1/assignment) | [Session Plan](/course-content/foundation/intro-to-javascript/week1/session-plan) |
| 2.   | Conditions; [Functions](/course-content/foundation/intro-to-javascript/week2#Functions); Global vs local scope; For loop                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | [Preparation](/course-content/foundation/intro-to-javascript/week2/preparation) | [Assignment](/course-content/foundation/intro-to-javascript/week2/assignment) | [Session Plan](/course-content/foundation/intro-to-javascript/week2/session-plan) |
| 3.   | Arrays (continued); [Objects](/course-content/foundation/intro-to-javascript/week3#Objects); [Call stack](/course-content/foundation/intro-to-javascript/week3#Call-stack)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | [Preparation](/course-content/foundation/intro-to-javascript/week3/preparation) | [Assignment](/course-content/foundation/intro-to-javascript/week3/assignment) | [Session Plan](/course-content/foundation/intro-to-javascript/week3/session-plan) |
| 4.   | Recap of js basics; Solving problems                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         | [Preparation](/course-content/foundation/intro-to-javascript/week4/preparation) | [Assignment](/course-content/foundation/intro-to-javascript/week4/assignment) | [Session Plan](/course-content/foundation/intro-to-javascript/week4/session-plan) |

> **Kind note:** The JavaScript modules are tough. Very tough! We expect you to **always** come prepared to the session on Sunday.

## Learning goals

* [ ] Understand what JavaScript is and what it's used for
* [ ] Use basic programming concepts such as variable definitions, types and operators
* [ ] Practice reading and fixing errors
* [ ] Use conditional logic to implement more advanced functionality
* [ ] Write basic functions with parameters and arguments
* [ ] Understand global vs local scope
* [ ] Using objects and arrays to store, access and manipulate more complex data


# Week 1

## Learning goals

* [ ] Intro JavaScript (What is it, what can you use it for)
* [ ] Setup js either via browser or via node
* [ ] Console.log
* [ ] [Variables: var, let, const](#variables)
* [ ] [Types](#types): [String](#string), [number](#number), boolean, [null, undefined](#null-and-undefined), [array](#array)
* [ ] [Operators](#comparison-operators): Comparison, addition, subtraction, multiplication, division, modulus, increment, decrement
* [ ] Errors: How to read and fix errors

Focus on how to read documentation, google answers and google errors

## Relevant links

* [Preparation](/course-content/foundation/intro-to-javascript/week1/preparation)
* [Assignment](/course-content/foundation/intro-to-javascript/week1/assignment)
* [Session Plan](/course-content/foundation/intro-to-javascript/week1/session-plan)

## Variables

A "variable" is a place where you can store information, such as a string, or a number. New variables in JavaScript are declared using one of three keywords: let, const, or var.

> Think of variables names like **labels** on boxes, while the value of the variable are the **contents** of the box - you could change the contents of a box and leave the label intact, the contents of the boxes can have different types, the boxes should have good labels (a box of books being labelled pens would be very confusing),
>
> ![Variables are like boxes](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-872c8022118fa2ac94e46264d487423d44c42d63%2Fbox.png?alt=media) Photo from [Khan Academy](https://cs-blog.khanacademy.org/2013/09/teaching-variables-analogies-and.html)

### Variable declaration

Variables are "declared" using the `var`, `let` or `const` keyword:

```js
var x;
let foo;
const bar;
```

### `let` and `const`

* read about [let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)
* read about [const](https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Statements/const)
* [let vs const](https://wesbos.com/let-vs-const/)

Here, we say: "declare variable x and initialize it with the integer (number) 5".

```js
let foo; // declare variable `foo`
```

```js
let foo = 6; // declare and assign a variable at the same time
```

You can also assign a value to an existing variable:

```js
foo = 4; // change variable `foo`
```

## Types

All variables have a type. In our example above, the variable `x` is a `number`. JavaScript supports the following types:

* `String`, e.g. "HackYourFuture"
* `Number`, e.g. 5
* `Float`, e.g. 10.6
* `Boolean`, e.g. `true` or `false`
* `Array`\*, e.g. `[1, 2, 3]` or `['what', 'is', 'your', 'name']`
* `Object`, e.g. `{name: 'John', age: 24}`, or the special object `null`
* `Function`, e.g. `function () { return 4; }`

In addition, a variable may be `undefined`. This is also a special type.

To get the type of a variable, use the following code:

```js
let x = 5;
let typeOfX = typeof x; // -> 'number'
```

Note that I've put an asterisk behind 'array'. That is because in JavaScript, array is a special kind of object:

```js
let arr = [1, 2, 3];
let typeOfArr = typeof arr; // -> 'object'
```

However, in our communication, we will call these variables arrays.

### `null` and `undefined`

The values `null` and `undefined` are very similar in JavaScript, but they behave a bit differently. The difference is that `null` always has type "object", and `undefined` always has type "undefined".

Whenever you declare a variable, but you don't set a value, the variable will become `undefined`. JavaScript will never make a variable `null` unless you explicitly program it - it represents [the intentional absence of any object value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null).

```js
let x;
console.log(typeof x); // -> 'undefined'
```

### `typeof`

You can use `typeof` to get the type of a certain variable as you have seen in the above section 'Variable types'. As you can see in the following examples it returns the type of data that you have stored in your variable.

## String

In JavaScript you can store a series of characters inside a variable, you then call this a string. You can store all sorts of characters (text/numbers, spaces or phrases) in strings. By using the `''` you define that something is a string. You can also use `""` to create a string. Both are fine as long as you are consistent (just make a choice on which one you prefer and stick to it).

```js
let foo = "42";
typeof foo; //-> 'string'
```

### String indexes and string properties

The index of a string always starts at 0. Strings also have properties, for example `.length` you can use this to find the length of a string.

So for example:

```js
let baz = "Hello World";
baz[0]; //-> "H"
baz.length; //-> 11
```

### String methods

More about [string methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String).

## Number

All numbers in JavaScript are considered numbers with or without decimal

```js
let foo = 42;
typeof foo; //-> 'number'

let bar = 3.3333;
typeof bar; //-> 'number'
```

## Array

Variables that are arrays contain a list of things, instead of just one thing. What's inside the array, we typically call "elements". So, the array `[1, 2, 3]` has three elements. The array `[]` has no elements and is therefore empty. The number of elements in an array is called its "length".

When you want to access an element inside an array, you use an "index". This is the number that you put between brackets (`[]`).

Given the following code:

```js
var arr = ["john", "jane", "jack"];
console.log(arr[0]);
```

The number `0` is the "index of the first element of array `arr`". Conversely, the element "at index 0 in array `arr` is `'john'`".

Instead of a number, you can also use a variable to access elements in an array, *as long as this variable is a number*:

```js
let arr = ["john", "jane", "jack"];
let a = 1;
console.log(arr[a]); // -> jane
```

If the index you use is not an integer (a whole number), or if it's less than `0` or if it's greater than or equal to the array's length, you will get back `undefined`.

More about [arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)

### Comparison operators

> Note the two different uses of the equals sign: A single equals sign (=) is used to assign a value to a variable. A triple equals sign (===) is used to compare two values (see Equality Operators).

#### Equality operators

* Equality `==`
* Inequality `!=`
* Identity / strict equality `===`
* Non-identity / strict inequality `!==`

How does this work in practice?

```js
1 == 1; // -> true
7 == "7"; // -> true
1 != 2; // -> true
5 === 5; // -> true
9 === "9"; // -> false
3 !== 3; // -> false
3 !== "3"; // -> true
```

> why does `7 == '7'` returns true and `9 === '9'` returns false?

#### Relational operators

* Greater than operator `>`
* Greater than or equal operator `>=`
* Less than operator `<`
* Less than or equal operator `<=`

```js
4 > 3; // -> true
3 >= 3; // -> true
13 < 12; // -> false
3 <= 4; // -> true
```

More about [comparison operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)

### Arithmetic operators

* Addition `+`
* Subtraction `-`
* Multiplication `*`
* Division `/`
* Remainder (sometimes called modulo) `%`. This returns the remainder left over after you've shared the left number out into a number of integer portions equal to the right number.

```js
8 + 9; // -> 17, adds two numbers together.
20 - 12; // -> 8, subtracts the right number from the left.
3 * 4; // -> 12, multiplies two numbers together.
10 / 5; // -> 2, divides the left number by the right.
8 % 3; /// -> 2, as three goes into 8 twice, leaving 2 left over.
```

More about [Arithmetic\_Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#.25_.28Modulus.29)


# Preparation

![Reading](https://media.giphy.com/media/l0MYtRl33WaN4HGBq/giphy.gif)

* [ ] [Read this](https://exploringjs.com/es5/ch01.html) up to and including the *Strings* chapter (it’s okay if you don’t understand all of it yet, we will cover these concepts in the session as well. Do make sure to write or document the questions you have so we can discuss them in the session) (15 min)
* [ ] [JavaScript Introduction at MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Introduction) (10 min)

*Please go through the material and come to session prepared!*

## Flipped classroom videos

* [Javascript - data type](https://www.youtube.com/watch?v=tQByWsZeYrM)
* [Javascript - variables](https://www.youtube.com/watch?v=sfqt3ZotOhw)
* [Javascript - make variable names descriptive](https://www.youtube.com/watch?v=0bgIUXj5BF8)
* [Javascript - the subtle difference between let and var](https://www.youtube.com/watch?v=9yFx81K9b4k)
* [Javascript - operators and errors](https://www.youtube.com/watch?v=wVs6rzTReD8)


# Session Plan

* Intro JavaScript
  * What is it, what can you use it for
* Setup js either via browser or via node.
  * Mentors decision.
* Console.log
  * Depending on node or browser explain where the logs can be found.
* Variable declaration and assignment
  * `var`
  * `let`
  * `const` - Always use `const` until it won't `let` you
* Variable types
  * Typeof
  * `String`
    * Indexes - low priority
    * `.length` - low priority
    * `.toLowerCase` - low priority
  * `Number`
    * Show float and int is just a number in js
  * `Array`
    * Creation
    * Indexing
    * Items
    * No map, filter, push etc!
  * `Boolean` - Trainees investigate `boolean` and explain for fellow trainees
  * [Code inspiration](#inspiration-variable-types)
  * [Exercises](#exercise-variable-types)
* Comparison operators
  * Equality operators
    * Equality `==`
    * Inequality `!=`
    * Identity / strict equality `===`
    * Non-identity / strict inequality `!==`
    * Why does `7 == '7'` returns true and `9 === '9'` returns false?
  * Relational operators
    * Greater than operator `>`
    * Greater than or equal operator `>=`
    * Less than operator `<`
    * Less than or equal operator `<=`
  * [Code inspiration](#equality)
* Arithmetic operators
  * Addition `+` - also for strings
  * Subtraction `-`
  * Multiplication `*`
  * Division `/`
  * Remainder (sometimes called modulo) `%` - Trainees investigate how modulo works
  * [Code inspiration](#arithmetic-operators)
  * [Exercise](#follow-up-exercises)
* Errors
  * How to read and fix errors. Show some practical examples.
  * [Exercise](#fix-the-errors)
* [Last exercise, pizza project](#pizza-project)

Here is a Notion Zoey Zou made: <https://www.notion.so/JS1-Week1-2fdc88fdd4344c958091346efe3ba48b>

## Flipped classroom videos

[Flipped classroom videos](https://github.com/HackYourFuture-CPH/JavaScript/blob/main/javascript1/week1/preparation.md#flipped-classroom-videos)

## Code inspiration

### Inspiration: Variable types

```js
console.log("Hello world");

var x;
x = 22;

x = 33;
var x = 22;

const test = 1;
// Bad, we get an error!
test = 2;

let letTest = 4;
console.log(letTest);
letTest = 20;
console.log(letTest);

// types:
// Number
let numberConst = 2;
console.log(numberConst);
console.log(typeof numberConst);
// BAD BAD BAD NAMING!!!!
numberConst = "hello";
console.log(typeof numberConst);

// String
const stringConst = "Write some text";
console.log(stringConst);

// Boolean
const booleanConst = false;
console.log(booleanConst);
console.log(typeof booleanConst);

// Array
const arrayConst = [];
const shoppingList = ["egg", "apples", "flour", 3, false];
console.log(shoppingList);
const shoppingListType = typeof shoppingList;
console.log(typeof shoppingListType);

console.log(shoppingList[1]);
console.log(typeof shoppingList[4]);

const shoppingListApples = shoppingList[1];
const lastItemShoppingList = shoppingList[4];
console.log(lastItemShoppingList);
console.log(typeof lastItemShoppingList);

// undefined
const undefinedExample = shoppingList[5];

let undefined1;
console.log(undefined1);
console.log(typeof undefined1);

console.log(typeof "0");
const stringConst2 = " asd";
console.log(stringConst2);

console.log(stringConst2[0]);
console.log(shoppingList.length);
console.log(stringConst2.length);
```

### Equality

```js
console.log(1 == 1);
console.log(1 == 2);

console.log(1 != 2);

console.log("HELLO" == 2);

console.log("1" == 1);
// both value and type should be true
console.log("1" !== 1);

console.log(1 > 8);

console.log(1 < 8);

console.log(1 <= 1);

console.log(1 === 1 && 3 === 4);
console.log((1 !== 1 || 3 === 4) && true);
```

### Arithmetic operators

```js
console.log(1 + 2);

console.log(1 - 2);

console.log(10 / 5);

console.log(10 * 5);
console.log(21 / 5);
console.log(21 % 5);

console.log("hello " + 23);
console.log("hello " + "23");
```

## Exercises

## Exercise: Variable types

With pen and paper write down what is logged out:

```js
// Types
console.log(typeof 3);
console.log(typeof -33);
console.log(typeof "3");
const threeConst = 3;
console.log(threeConst);
let threeLet = 3;
console.log(threeLet);
console.log(typeof 'console.log("console.log(console.log(""))")');
console.log(typeof typeof 45);
const names = ["benjamin", "Christopher"];
console.log(typeof names[0]);
console.log(typeof [3][0]);
console.log(typeof true);
```

### Follow up exercises

1. Create a variable that is 24 times 55
2. Create a const and set it to be equal to your name
3. With javascript `console.log` the first character in your name
4. Create an array with 3 strings, three numbers and three booleans
5. `console.log` the 4. element in the array made above
6. *Optional* with javascript `console.log` the last character in your name.

### Fix the errors

Fix the errors in this script:

```js
const name = "benjamin";
name = "benjamin-better";

const pizzaPrice = 78;
const pizzaPriceDiscounted = pizzaprice - 10;

const users = ["peter", "Johnny", "Børge"];

const lastUser = users[3];
console.log(lastUser);
```

### Pizza project

#### Part 1

1. Create a special new folder called "pizza-exercise"
2. Inside the folder create a new html file called "index.html"
3. Also inside the folder create a new JavaScript file called "pizza.js"
4. Remember to Include the pizza.js script in the html file
5. Write a log statement, so you know that your javascript code is running:

   `console.log("I love pizza");`
6. Create a variable to store the name of your favourite pizza
7. Create a variable to store the price of the pizza
8. Now log a statement to the console that will show the chef the entire pizza order in a language they understand, e.g. like this:

   `New pizza order: <name of pizza>. The price of the pizza is: <price of pizza>`

#### Part 2

Now we will modify the program so you can order multiple pizzas and decide whether the order is takeaway.

1. Create a new variable to store the amount of pizzas you would like to order
2. Create a new variable to store whether or not the order is for takeaway
3. Now write a formula to calculate the total price of your pizza order, and save it in a variable called totalPrice
4. Modify the log statement for the chef so it includes whether or not the order is for takeaway, and now show the total price of the order:

   `New pizza order (takeaway: <takeaway or not?>): <amount of pizzas> <name of pizza>. Total cost for the order is: <total price>`
5. Try to change the price of the pizza and then check if the total price is calculated correctly


# Assignment

![Hacking](https://media.giphy.com/media/eCqFYAVjjDksg/giphy.gif)

## Step 1: Before you start with the assignment

1. Watch: [What is programming?](https://www.khanacademy.org/computing/computer-programming/programming/intro-to-programming/v/programming-intro). Just watch the 2 min video, you do not have to do the entire JavaScript course (It could be useful later on though).

If you struggle to do this weeks assignment, read up on [JavaScript basics](/course-content/foundation/intro-to-javascript/week1#variables).

## Step 2: Javascript warm up part one

Let's get started with some warm up exercises: On freeCodeCamp.com do the [Basic JavaScript](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript) exercises up and until the **"Manipulate Arrays With push()"** exercise (there are some topics we did not cover but you can do it).

Please add your freeCodeCamp username as answer for this exercise!

You have finished the warmup exercises, well done!

## Step 3: Smart-ease - We help where we can

Enough warm up, let's get to the real problems! We will assume a real world business case where you (the developer) needs to help a business that is starting up (a startup) with solving some of their problems related to JavaScript! Here we go:

***

Let's imagine that we have just started a cool new tech startup called **Smart-ease**. And let's imagine we even have this cool website url: `smart-ease.io` Now we are in business!

At **Smart-ease** we focus on solving real world problems. We venture into the world to help people, and by helping people, we create a sustainable business.

Cool now let's venture into the world and see which problems we can solve with some of these cool products that Smart-ease will develop with your help:

![Adventure](https://media.giphy.com/media/oj2GhTqAIoNIk/giphy.gif)

### Age-ify (A future age calculator)

> You are talking to a friend who suddenly looks at you and asks: "How old will you be in 2045?" Hmm you remember the year you were born and try to do some calculation: Born in 1987 + 3 that's 1990. 90 - 40 is 50 + 5 that's 58. I will be 58! Wow that was painful! Let's fix that by making some code that automatically does this!

Create two variables called `yearOfBirth` and `yearFuture`. Assign these your birth year and a future year. What type will these two variables be? Using `yearOfBirth` and `yearFuture` calculate the age and store that in a variable called `age`.

Log out this string: "You will be 40 years old in 2027". With 40 being the result of the `age` variable and 2027 being the `yearFuture` variable. (Hint use string concatenation)

### Goodboy-Oldboy (A dog age calculator)

> The same friend (who by the way loves dogs) asks how old his dog will be in 2045. Hmm you think, let's make this into a product as well! Dogs age can either be measured in dog years or in human years, this we want to take into consideration!

Like before, let's create three variables, but this time we call them `dogYearOfBirth`, `dogYearFuture` and `dogYear`. We add an extra variable called `shouldShowResultInDogYears`. If it is `true` we should show the result in dog years, if it is false we should show it in human years. What do we call this type of variable? Now dependent on `shouldShowResultInDogYears` log this string out: "Your dog will be 10 human years old in 2027" or "Your dog will be 70 dog years old in 2027"

### Housey pricey (A house price estimator)

> Two of your friends are considering buying a house, but cannot figure out what the right price should be. Your friends know the width, the height and the depth of the house and the garden size. Let's help them figure out if they paid too much:

We have made our own formula for calculating the price of a house. This formula is VERY simplified and not at all close to the real calculation which can get [quite complicated](https://www.kaggle.com/erick5/predicting-house-prices-with-machine-learning):

```js
housePrice = volumeInMeters * 2.5 * 1000 + gardenSizeInM2 * 300;
```

Your friend Peter is considering a house that is 8m wide, 10m deep and 10m high. The garden size is 100m2. The house costs 2.500.000. Your friend Julia is considering a house that is 5m wide, 11m deep and 8m high. The garden size is 70m2. This house costs 1.000.000.

Figure out if Peter and Julia are paying too much or too little using Javascript and the formula specified above.

### Ez Namey (Startup name generator) *Optional*

> At a meetup you overhear a conversation between two developers. It went something like this: "I wish picking a startup name was easier! You need to be creative, funny and interesting, it's nearly impossible!" Another problem to solve, awesome!

Let's help people who struggle finding a startup name by creating some code!

Create two arrays called `firstWords`, `secondWords`. The arrays should have 10 elements containing strings of possible startup names. Some examples could be: "Easy", "Awesome", "Corporate".

Create a variable called `startupName` that will contain the created startup name.

Using a random index (you choose) of the arrays and concatenation of strings, create and log the new startup name and the number of characters in it. An example could be: "The startup: "Easy Corporation" contains 16 characters"

Hint: you can use this code to generate a random number from 0-9, if you don't want to specify the indexes yourself.

```js
const randomNumber = Math.floor(Math.random() * 10);
```

***

4 projects from one startup, that's incredible! Let's hope one or more of these projects actually becomes popular!

To be continued...


# Week 2

## Learning goals

* [ ] Conditions: if, elseif, else. Negated.
* [ ] [Functions](#functions): [Calling](#calling-a-function-on-something), defining, [parameters, arguments](#parameters-and-arguments)
* [ ] Global vs local scope
* [ ] For loop

Teaching note. Start off explaining functions with how to use a function e.g. explain why the Math.random function is smart, or Math.max.

## Relevant links

* [Preparation](/course-content/foundation/intro-to-javascript/week2/preparation)
* [Assignment](/course-content/foundation/intro-to-javascript/week2/assignment)
* [Session Plan](/course-content/foundation/intro-to-javascript/week2/session-plan)

### Recap Logical operators

```js
0 = false
1 = true
```

#### AND `&&`

| `&&` | 0 | 1 |
| ---- | - | - |
| 0    | 0 | 0 |
| 1    | 0 | 1 |

#### OR `||`

| `\|\|` | 0 | 1 |
| ------ | - | - |
| 0      | 0 | 1 |
| 1      | 1 | 1 |

So you can say that false in combination with `&&` always returns false

```js
true && false; //-> false
false && true; //-> false
false || true; //-> true
true || false; //-> true
```

### Typeof

`typeof` always returns the data type in a string.

So for example:

```js
let bar = 42;
typeof bar; //-> 'number'
typeof typeof bar; //->  'string'
```

So the data type of what `typeof` returns is always a string, bar on the other hand is still a number.

## Functions

A function is a reusable piece of code. It is used to hide away abstraction! Functions are *very* important in JavaScript, to the extent that some people call JavaScript a "function-oriented" language.

### Two sides of a function

There are two sides to using function, using a function (calling a function) and creating a function.

#### Function usage

When you call a function some javascript code is run. Here's a simple example:

```js
const randomNumber = Math.random();
console.log(randomNumber); // logs out some number between 0 and 1
```

Here `Math.random` is a function. To activate the function we call it using parentheses `()`. When calling it we get a randomNumber! We now don't need to think about all the code it takes to create a random number in javascript, we simply call the function and get a random number. Code has been abstracted away for us!

Some functions is called with arguments, for example:

```js
const maxNumber = Math.max(3, 5); // 3 and 5 are arguments
console.log(maxNumber); // logs out 5
```

Arguments are used to control the code inside a function.

#### Function creation

When we create a function we use the function keyword:

```js
let todoItem = "Buy Groceries";
console.log(todoItem);

// Create the function
function checkItem() {
  todoItem = todoItem + " - done";
}

// use the function by calling it using ()
// If we don't call the function that code will NEVER EVER IN A MILLION YEARS run!
checkItem();
console.log(todoItem);
```

#### Parameters and arguments

```js
// a and b are called parameters. This function has two parameters
function sum(a, b) {
  return a + b;
}
```

```js
// 5 and 10 are called arguments now when called in a function
// Arguments are "passed" to the function: "we pass `4` and `5` to the function sum
const returnedSum = sum(5, 10);
console.log(returnedSum); // logs 15
```

So remember the difference between the word "parameter" and "argument". Many people confuse them, and that's not a big problem, but understanding the difference is always nice:

* A parameter is the name you want to give to the variable that is available inside of the function.
* An argument is the actual value you want to assign to the parameters when you call the function.

Parameters acts as a placeholder for the arguments. The value of the parameter will get substituted with the value of the argument.

```js
function multiply(a, b) {
  // the value of a will be substituted with the value of 10!
  // the value of b will be substituted with the value of 4!
  console.log(a, b); // logs out 10 4
  return a * b;
}

multiply(10 * 4);
```

**Return value**

Sometimes we want to get a value back when calling a function. e.g. in the sum example. We want to call the function and get the sum back!

```js
function sum(a, b) {
  return a + b;
}
const returnedSum = sum(5, 10); // the variable returnedSum captures the return value from calling the function!
console.log(returnedSum); // logs 15

// If we don't return, we cannot capture the returned value!
function sumNoReturn(a, b) {
  a + b; // no return!
}
const returnedSum = sum(5, 10);
console.log(returnedSum); // logs undefined
```

If we don't return anything from the function, it will automatically return `undefined`. This is the functions way of saying that nothing was returned.

### Calling a function on something

In JavaScript, you can call functions *on* something. By this, we mean that you use the dot to call the function. For instance, when we say "call method `trim` on string `s`", we mean:

```js
let s = " this is a string  ";
s.trim(); // -> "this is a string"
```

However, there are functions that you don't call on anything:

```js
function sum(a, b) {
  return a + b;
}
sum(4, 5); // -> 9
```

Here, you call the function `sum` on nothing.


# Preparation

* [Functions](https://javascript.info/function-basics) (15 min)
* [Conditions](https://javascript.info/ifelse) (10 min)
* Read from [For loops](https://javascript.info/while-for#the-for-loop) to and with [for loops continue](https://javascript.info/while-for#continue) (10 min)

![Cosy rain](https://media.giphy.com/media/k28n1OPefBEeQ/giphy.gif)

*Please go through the material and come to session prepared!*

## Flipped classroom videos

* [Javascript conditions](https://www.loom.com/share/6affdcf03b4f43ceac56424ff04975e5)
* [Javascript loops](https://www.loom.com/share/4663f4fa5c784fff9ab67f2b91166c9b)
* [Javascript function](https://www.loom.com/share/61fadf80906d481497e3b40273897d20)
* [Javascript scope](https://www.loom.com/share/b8874230724040598860e8f059d8e369)


# Session Plan

* Conditions
  * [Code inspiration](#if-statements)
  * [Exercises](#if-statements-exercise)
* Functions (<https://twitter.com/wesbos/status/1105907924088565762>)
  * General description - A function is a reusable piece of code.
  * Function usage
    * Arguments
  * Function creation
    * Parameters - Acts as placeholders
    * Parameters vs arguments
    * Return value - Variable can capture return value.
    * Calling a function on something `Math.random` - calling the function random on Math
  * [Code inspiration](#functions)
  * [Code inspiration 2](#if-and-function)
  * [Exercise](#function)
* Global vs local scope
  * Lexical scope - inner functions contain the scope of parent functions even if the parent function has returned.
  * [Code inspiration](#scope)
  * [Exercise](#exercise-scope)
* For loop
  * Try start off with giving the trainees the [Exercise string logger](#for-loop-in-a-function) and not explain for loop. Let them figure it out through the exercise (problem based learning)
  * [Code inspiration](#for-loop)
  * [Exercise string logger](#for-loop-in-a-function)
  * [Exercise send emails](#send-emails)

The trainees really struggle with the **return** value. What it means, how it is captured. What happens when nothing is returned etc. Try really hammering in this concept with lots of simple examples and exercises! e.g. if a function is called get something. That means that something is returned from that function.

Zoey Zou made a nice Notion session plan here: <https://www.notion.so/JS1-Week2-8f2d4b7e7ba0425ea4a9e97816e9ceb7>

## Flipped classroom videos

[Flipped classroom videos](https://github.com/HackYourFuture-CPH/JavaScript/blob/main/javascript1/week2/preparation.md#flipped-classroom-videos)

## Code inspiration

### `if` statements

```js
const age = 14;

// if-else statement, `age > 18` is called an expression
// `age > 18` is called a boolean expression
if (age > 18) {
  console.log("Allowed");
} else {
  console.log("Denied");
}

if (age < 18) console.log("You're not old enough");

// Boolean operators
// && is called AND
// || is called OR
// ! is called NOT

// Chained if statement
if (age > 0 && age < 13) {
  console.log("You are a child");
} else if (age >= 13 && age < 20) {
  console.log("You are a teenager");
} else if (age <= 0) {
  console.log("You are an infant");
} else {
  console.log("You are an adult");
}

if (age < 18 || age === 18) {
  // same as saying `age <= 18`
  console.log("You are almost there");
}

// New example
const userRole = "guest";
const isAdmin = userRole === "admin";
const isLoggedIn = userRole !== "guest";

if (isAdmin) {
  console.log("You are in charge");
} else if (isLoggedIn) {
  console.log("Welcome user");
} else {
  console.log("Welcome guest");
}
```

### Functions

```js
// usage
const randomNumber = Math.random();
console.log(randomNumber); // logs out some number between 0 and 1

const maxNumber = Math.max(3, 5); // 3 and 5 are arguments
console.log(maxNumber); // logs out 5

// Creation
let todoItem = "Buy Groceries";
console.log(todoItem);

// Create the function
function checkItem() {
  todoItem = todoItem + " - done";
}

// use the function by calling it using ()
// If we don't call the function that code will NEVER EVER IN A MILLION YEARS run!
checkItem();
console.log(todoItem);

// a and b are called parameters. This function has two parameters
function sum(a, b) {
  return a + b;
}

// 5 and 10 are called arguments now when called in a function
// Arguments are "passed" to the function: "we pass `4` and `5` to the function sum
const returnedSum = sum(5, 10);
console.log(returnedSum); // logs 15

function multiply(a, b) {
  // the value of a will be substituted with the value of 10!
  // the value of b will be substituted with the value of 4!
  console.log(a, b); // logs out 10 4
  return a * b;
}

multiply(10, 4);

// Return value
function sum(a, b) {
  return a + b;
}
const returnedSum = sum(5, 10); // the variable returnedSum captures the return value from calling the function!
console.log(returnedSum); // logs 15

// If we don't return, we cannot capture the returned value!
function sumNoReturn(a, b) {
  a + b; // no return!
}
const returnedSum = sum(5, 10);
console.log(returnedSum); // logs undefined

// Calling a method on something
let s = " this is a string  ";
// calling a function (trim) on the string s
s.trim(); // -> "this is a string"
```

### `if` and `function`

```js
function isAuthenticated(userRole) {
  // userRole here is different from `var userRole`
  const isAdmin = userRole === "admin";
  const isLoggedIn = userRole !== "guest";

  if (isAdmin) {
    return true; // if this is run, all other code after is ignored inside the function
  } else if (isLoggedIn) {
    return true;
  }

  return false;
}

console.log(userRole);
console.log(isAuthenticated(userRole));
console.log(isAuthenticated("admin"));
```

### Scope

```js
// Global scope
const globalScopeVariable = "globalScopeVariable";
function outerFunction() {
  // function scope A
  console.log(globalScopeVariable);
  const outerFunctionScope = "outerFunctionScope";

  function innerFunction() {
    // Function scope B
    console.log(globalScopeVariable);
    console.log(outerFunctionScope);

    const innerFunctionScope = "innerFunctionScope";
  }

  console.log(innerFunctionScope);

  innerFunction();
}

outerFunction();

if (true) {
  const blockScope = "blockScope";
}

console.log(blockScope);
```

### `for` loop

```js
function spam(number) {
  let repeated = ""; // Define the simplest case

  // Think about the condition. How many times do we want to repeat
  for (let i = 0; i < number; i++) {
    repeated = repeated + "hue"; // What is our update rule
  }

  return repeated; // Return in the end
}

console.log(spam(1));

// Test cases. I always do "empty" (here zero), once, and then a bunch of times
console.log(spam(0) === "");
console.log(spam(1) === "hue");
console.log(spam(6) === "huehuehuehuehuehue");
console.log(spam(14) === "huehuehuehuehuehuehuehuehuehuehuehuehuehue");
```

## Exercises

### `if` statements exercise

Use `if` statements to give a user a message based on their bank account balance. Use the `balance` variable and change that.

* If a user has 0 or less balance log out 'Please deposit some money!'
* If a user has more than 0 and at most 1000 log out 'Your balance is looking okay'
* If a user has more than 1000 and at most 3000 log out 'Your balance is looking good'
* If a user has more than 3000 and at most 10000 log out 'Your balance is fantastic'
* If a user has more than 10000 log out 'Your balance is AMAZING!'

```js
const balance = 1000;
```

### Function

Create a function called `getCircleArea`. It should have the `radius` of the circle as parameter and return the circle area. What happens if we don't return anything in the function?

Create a function called `celsiusToFahrenheit` it should have a parameter called `celsius`. It should return the temperature in fahrenheit.

Try call the function and check with google if the function returns the right value.

### Exercise: Scope

With pen and paper write what is logged out.

```js
const global = "global";
function scopeTest() {
  console.log(functionScope);
  console.log(global);
  const functionScope = "functionScope";

  function tester() {
    console.log(global);

    const testerVariable = "testerVariable";
  }

  tester();
  console.log(testerVariable);
}

scopeTest();
```

### `for` loop exercises

#### Simple `for` loop

Create a for loop that logs out the numbers from 74 - 98

#### `for` loop in a function

Create a function that has two parameters: `stringToLog` and `numberOfTimesToLog`

When calling the function it should log out the `stringToLog` the amount of times specified in `numberOfTimesToLog`. Use a for loop.

```js
logString("hello", 3);
// hello
// hello
// hello
```

### Send emails

Imagine we work at a company. Anna from the HR department wants us to send out a couple of emails to some recipients. The only problem is that she sent us the email in a weird format: `benjamin@gmail.com|peter@gmail.com|hans@gmail.com|ahmad@gmail.com|sana@gmail.com|virgeen@gmail.com|mohammed@gmail.com`

Use the `sendEmailTo` function to send an email to all the recipients that we got from Anna.

*Hint* use the `.split` method and look up `iterating an array js for loop` on google.

```js
// This function emulates sending emails to recipients
function sendEmailTo(recipient) {
  // But really it only logs out a string
  console.log("email sent to " + recipient);
}
```


# Assignment

## Why should I even do this assignment?

Functions and conditions are some of the basic building blocks of javascript. Functions ensure that we don't repeat ourselves when writing code. Conditions ensure that we can handle different cases when programming.

If you struggle to do this weeks assignment, read up on [JavaScript basics](/course-content/foundation/intro-to-javascript/week2#recap-logical-operators).

## Javascript warmup

Just like last the last assignment, let's **warm up our brains**!

Do these freeCodeCamp challenges. We know this seems like a lot, but the tasks are not so big, so hang in there! If you get stuck on one of the tasks, just go to the next and then return to the difficult task later on.

* [ ] [Passing values to functions with arguments](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments/)
* [ ] [Return a value from a function with return](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/return-a-value-from-a-function-with-return/)
* [ ] [Assignment with a returned value](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/assignment-with-a-returned-value/)
* [ ] [Local scope and functions](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions/)
* [ ] [Global vs local scope in functions](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/global-vs--local-scope-in-functions/)
* [ ] [Introducing else if statements](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements/)
* [ ] [Logical order in if else statements](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements/)
* [ ] [Iterate with javascript for loops](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops/)
* [ ] [Iterate through an array with a for loop](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop/)

Please add your freeCodeCamp username as answer for this exercise!

## Step 3: Smart-ease - Goes Global!

Following the massive success of Smart-ease's first couple of products things have been quite hectic at Smart-ease's shared office space. The phone is constantly ringing from journalists wanting to interview the genius behind the success and the greatest developers want to work for you. [Wired](https://www.wired.com) wrote an article with the headline "Smart-ease as good as Smarties"

BUT people are asking: What will be the next product that truly defines Smart-ease as the startup of the century?

### Flight booking fullname function

Even for a startup as successful as Smart-ease there needs to be money in the bank. A customer from a flight booking website has asked for our help creating a specific part of their application:

When a user books a flight they **write their firstName and surname**, but when the ticket is printed a **fullname should be displayed**. It is our responsibility to create that.

Create a function called `getFullName` that returns a fullname. It should have two parameters: `firstName` and `surname`.

```js
getFullName("Benjamin", "Hughes"); // returns "Benjamin Hughes"
```

Now try to create two variables `fullName1` and `fullName2` these two variables should be assigned to calling the `getFullName` function.

Log out the two fullname variables.

#### Formal fullname

On the flight website the user has the possibility to **check a checkbox** that **indicates** if the user wants to be **addressed formally**. Let's also change `getFullName` to include support for formal name.

Create an extra parameter `useFormalName` that is a boolean. If it is true the function should add a `Lord` in front of the name.

```js
getFullName("Benjamin", "Hughes", true); // returns "Lord Benjamin Hughes"`
getFullName("Benjamin", "Hughes", false); // returns "Benjamin Hughes"
```

What do we do if `useFormalName` is not given as an argument?

Remember to consider someone calling the function with an empty string as `firstName` and `lastName`.

Try out your code by pasting your `getFullName` function in the javascript part of this codePen: <https://codepen.io/hackyourfuture-cph/pen/jJWwbN>

But what if the person is a woman? Describe how you would fix the `getFullName` so it also works for women

### Event application

Another customer has contacted us. They work for a secret company that rhymes with foogle. The customer works on their calendar application. They need some functionality to help with writing what weekday an event is held.

You specify how many days from today an event is being held. The function then figures out what weekday the event is being held. Here is an example:

Today is Sunday and the event is in 5 days. Therefore the event will be held on a Friday.

```js
// With today's weekday a tuesday
console.log(getEventWeekday(9)); // Outputs "Thursday"

// With today's weekday a Friday
console.log(getEventWeekday(2)); // Outputs "Sunday"
```

You should get the today's day from the system.

Hint: use remainder operator, array indexes and investigate `new Date` in js.

### Weather wear

Create a function (that you have to name) that has temperature as parameter. Based on the temperature it should return a string with what the user should wear. You decide what the user should wear based on the temperature.

An example is:

```js
const clothesToWear = youCreateThisFunctionName(18);
console.log(clothesToWear); // Logs out: "shorts and a t-shirt"
```

![Wearing jackets](https://media.giphy.com/media/26u6dryuZH98z5KuY/giphy.gif)

### Student manager

A coding school have contacted us to make some functionality for managing their classes. We will create functionality for adding students to a class.

For this exercise you need to figure out how `Array.push` works. Learn about the concept by researching about it.

Copy the following code into your assignment js file

```js
const class07Students = [];
function addStudentToClass(studentName) {
  // You write code here
}

function getNumberOfStudents() {
  // You write code here
}
```

#### `addStudentToClass` function

The `addStudentToClass` should add the `studentName` to the `class07Students` array.

But there are some other requirements:

* There can be only 6 students in a class. If more students are tried to be added, log out the following: "Cannot add more students to class 07".
* The same person cannot be added to the class. If the same person is added to the class, log out the following: 'Student Benjamin is already in the class' where Benjamin is substituted for the `studentName`.
* We are very fond of our Queen in Denmark, so if the Queen is added to the class she should always get a space. Even if the class has been filled out.
* You cannot add an empty string to a class

#### `getNumberOfStudents` function

`getNumberOfStudents` should simply return the number of students in the class.

#### Now let's try and use the functions!

Try out all the cases:

* Add some students to the class.
* Add more students than there is space for
* Add a student that is already in the class
* Add the Queen to a full class
* Call the `getNumberOfStudents` to log out the number of students.

To see your code applied on a webapp, go here: <https://codepen.io/hackyourfuture-cph/pen/PLPmOB> and paste your javascript code.

### Candy helper *optional*

> We are at the candy store. We have taken some shovels of the **caramel-strawberry-cola-lemon-gravy wine gums**, a few of the **banana chocolate diesel-motors** and a handful of the **salmon-potato covered toffee encrusted pizzas**. But what is all this worth? And can you even afford it?

Let's solve this problem with some functions.

#### `addCandy` function

Create a function called `addCandy`. It has two parameters:

* `candyType` - specifies the candy type. Could be 'sweet, chocolate, toffee or chewing-gum'
* `weight` - specifies the weight of the candy in grams

The function should **add the price of the candy** to an array called `boughtCandyPrices` using [push](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)

Here is an example of the usage:

```js
addCandy("sweet", 20); // Adds the price of 20 grams of sweets to the array boughtCandyPrices
```

Candy table prices

| Candy type  | Price per gram |
| ----------- | -------------- |
| Sweet       | 0.5            |
| Chocolate   | 0.7            |
| Toffee      | 1.1            |
| Chewing-gum | 0.03           |

#### Can I buy more?

Now create a variable called `amountToSpend` and assign it to `Math.random() * 100`. You can [read about `Math.random`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random).

Create a new function called `canBuyMoreCandy`. This function returns a boolean indicating if the user can buy more candy using the `boughtCandy` array.

Try use the function by adding some pieces of candy and checking if you can buy more. If the user can buy more candy the `console.log` the following: "You can buy more, so please do!". If the user can't buy more `console.log` the following: "Enough candy for you!"

Hint: Use a for loop to calculate the total price of the candy pieces.

*Optional* Use a [while loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while) instead of a for loop.


# Week 3

## Learning goals

* [ ] Arrays continued: pop, push, shift, unshift, length, indexOf. No map, filter or reduce
* [ ] [Objects](#objects): Access properties two ways, key value. Array of objects. Use real world examples (users, products, house listings)
* [ ] [Call stack](#call-stack)

## Relevant links

* [Preparation](/course-content/foundation/intro-to-javascript/week3/preparation)
* [Assignment](/course-content/foundation/intro-to-javascript/week3/assignment)
* [Session Plan](/course-content/foundation/intro-to-javascript/week3/session-plan)

## Objects

Variables that are objects also contain a list of things, but instead of them being in some specific order, they can be assigned to words, called "keys". Instead of "elements" the things that are inside objects are called "properties".

```js
let obj = { name: "John", age: 24 };
```

This object has two properties: `name` and `age`. The "value" of the property `name` is the string `'John'`. The "value" of the property `age` is the number `24`.

When accessing object properties, you can use the dot-notation: `obj.name` or the bracket-notation: `obj["name"]`. Note that the latter looks a lot like the way to access array elements. However, here what's inside the bracket (called "key" for objects, instead of "index") must be a string.

```js
console.log(obj.name); // -> 'John'
console.log(obj["name"]); // -> 'John'
```

Just like with arrays, you can also use a variable to access properties, as long as these variables are strings. In this case you cannot use the dot-notation!

```js
var ageKey = "age";
console.log(obj[ageKey]); // -> 24
```

Remember that there is a very big difference between `obj[name]` and `obj["name"]`.

> Note:
>
> Thinking back of arrays, the length of an array can be retrieved by `arr.length`. So as mentioned before, arrays are just like other JavaScript objects. You could even write `arr['length']` to access the `length` property of the array. JavaScript will look: is what we put between brackets a number? Then it is an index and we'll look up the correct array element. If it's a string, it's a key and we will look up the corresponding property.

## Call stack

When a function is called it is pushed to the call stack. When a function is finished the function gets shifted from the call stack.

Visualize here: <http://latentflip.com/loupe>

```js
function pickUpKids() {
  // pickUpKids function gets pushed to call stack WHEN CALLED!
  console.log("Kids picked up");
  // pickUpKids function now gets shifted from the call stack!
}

function buyCarrots() {}

function buyVegetables() {
  buyCarrots();
}

function getGroceries() {
  // buyVegetables pushed to call stack
  buyVegetables();
  // buyVegetables shifted from call stack
}

function doWork() {}

pickUpKids();
// getGroceries pushed to call stack
getGroceries();
doWork();
```


# Preparation

* [Array](https://javascript.info/array) up until and with [internals](https://javascript.info/array#internals) (10 min)
* [Objects](https://javascript.info/object) (15 min)

*Please go through the material and come to session prepared!*

## Flipped classroom videos

* [Javascript callstack](https://www.loom.com/share/d09d10ea84da45e2bddd9ffa05396ed3)
* [Javascript objects](https://www.loom.com/share/312a9ec3e2ed42beb6017f4a4167bd46)
* [Javascript array](https://www.loom.com/share/06cdd6a4a3834cb696db8dd941ea6550)


# Session Plan

* Objects
  * Access properties two ways: .keyname and \[keyname]
  * Key - value
  * Array of objects
  * Let the trainees explain iterating an array of objects
  * Use real world examples (users, products, house listings)
  * [Code inspiration](#inspiration-objects)
* Arrays continued
  * `pop`, `push`, `shift`, `unshift`
    * Let trainees investigate `shift` and `unshift`
    * The longest of the word pairs unshift, push makes the array longer!
  * `includes` - Let the trainees investigate this
  * Looping through an array
  * No `forEach`, `map`, `filter` or `reduce`
  * [Code inspiration](#inspiration-arrays)
* [CodeWar exercises](#codewar-exercises)
* Call stack
  * Used for figuring code flow in js! Where does my function go when it is done here.
  * <http://latentflip.com/loupe>
  * [Code inspiration](#inspiration-call-stack)
  * [Exercise](#exercise-call-stack)

Zoey Zou has created a nice session plan here: <https://www.notion.so/JS1-Week3-a0f122866ac34fc3b98b7a41870046f4>

## Flipped classroom videos

[Flipped classroom videos](https://github.com/HackYourFuture-CPH/JavaScript/blob/main/javascript1/week3/preparation.md#flipped-classroom-videos)

## Code inspiration

### Inspiration: Objects

```js
const user = {
  name: "Emil",
  age: 25,
  role: "Teacher",
  classes: ["Javascript 1", "Javascript 2"],
  hobbies: {
    favourite: "computers",
    sports: "running to class",
  },
};

console.log(user);

// Add new property
user.lastName = "Bay";

console.log(user);

delete user.lastName;

console.log(user);

console.log(user.hobbies.favourite);
console.log({ favourite: "computers", sports: "running to class" }.favourite);

function graduatedClass(student, className) {
  if (student.classes.includes(className)) return "Error";

  student.classes.push(className);
}

console.log(user);
graduatedClass(user, "HTML");
console.log(user);
graduatedClass(user, "HTML");

const newUser = {
  name: "",
  age: "",
};

var students = [];
function addStudent(student) {
  if (student.name == null && typeof student.name === "string") return "Error";
  if (student.age == null) return "Error";

  students.push(student);
}

addStudent({ name: "Rahim" });
console.log(students);

// ways to access properties

user.name;
user["name"];

const prop = "name";
user[prop];

user["name"] = "Maria";
user[0] = "Hello world";

console.log(user);
```

### Inspiration: Arrays

```js
// one way to have multiple data about a student is with an array
// for each piece of data
const studentNames = ["Fowad", "Emil", "Zoey"];

const studentAges = [32, 25, 28];

console.log(studentNames);
console.log(studentAges);

// Another, more ergonomic way is with objects
const students = [
  { name: "Fowad", age: 32 },
  { name: "Emil", age: 25, teacher: true },
  { name: "Zoey", age: 28 },
];

console.log(students);
// We can access properties with `.`
console.log(students[0].name);

for (let i = 0; i < students.length; i++) {
  const currentStudent = students[i];
  console.log(typeof currentStudent);
  console.log(currentStudent.name);
}

students.push({ name: "Ahmad", age: 27 });

// One object that we have seen before
const Math = {
  random: function () {
    return 42;
  },
  round: function (x) {},
};
```

### Inspiration: Call stack

```js
function a() {
  // add to call stack
  b();

  return "a";
  // remove from call stack
}

function b() {
  //throw 'hello';
  return "b";
}

a();
```

## Exercises

## Exercise: Call stack

Draw the call stack array at every draw point

```js
function bookPlaneTickets() {
  // draw
  console.log("Plane tickets booked");
  requestVacationDays();
  // draw
}

function bookHotel() {
  console.log("Hotel booked");
  // draw
  planItinerary();
  // draw
}

function requestVacationDays() {
  // draw
  console.log("Vacation days requested");
  // draw
}

function planItinerary() {
  console.log("Itinerary done");
  // draw
}

function planTrip() {
  bookPlaneTickets();
  // draw
  bookHotel();
  // draw
  console.log("Trip planned");
}
// draw
planTrip();
// draw
```

### CodeWar exercises

* [CodeWars - Add property to every object](https://www.codewars.com/kata/add-property-to-every-object-in-array/train/javascript)
* [CodeWars - Color Association](https://www.codewars.com/kata/colour-association/train/javascript)
* [CodeWars - Unfinished loop](https://www.codewars.com/kata/unfinished-loop-bug-fixing-number-1/train/javascript)
* [CodeWars - Is this my tail](https://www.codewars.com/kata/is-this-my-tail/train/javascript)
* [CodeWars - Longest word](https://www.codewars.com/kata/squash-the-bugs/train/javascript)
* [CodeWars - Who's Online](https://www.codewars.com/kata/whos-online/train/javascript)


# Assignment

## Why should I even do this assignment?

`Array` has lots of helper functions that are used all the time when developing js applications. It is super helpful to be able to **manipulate an array** like **removing elements** or **adding elements** at specific indexes. Another helpful function of arrays is to know **where a specific item is** in the array.

Objects can be used for **representing data** and it can **help structure your code**. An object can e.g. represent a user that has a first name, surname, profile picture and a list of friends. It is constantly used in javascript and **essential to learning the language**.

If you struggle to do this weeks assignment, read up on [objects and arrays](/course-content/foundation/intro-to-javascript/week3#objects).

## Javascript warmup

It's warmup time!

![Warm up](https://media.giphy.com/media/Cfw4WE617UgUw/giphy.gif)

### Item array removal

Remove the item in `names` that is equal to `nameToRemove`

Copy the code below to your assignment

```js
const names = [
  "Peter",
  "Ahmad",
  "Yana",
  "kristina",
  "Rasmus",
  "Samuel",
  "Katrine",
  "Tala",
];
const nameToRemove = "Ahmad";

// Write some code here

// Code done

console.log(names); // ['Peter', 'Yana', 'kristina', 'Rasmus', 'Samuel', 'Katrine', 'Tala']
```

### When will we be there??

Write a function where you specify your speed in `km/h` and how far you have to go in `km`. The function has to return the time it will take to arrive at your destination. The time should be formatted like this: `3 hours and 34 minutes`.

*Hint:* For formatting your best friend is Google!

```js
const travelInformation = {
  speed: 50,
  destinationDistance: 432,
};

const travelTime = notThisFunctionName(travelInformation);
console.log(travelTime); // 8 hours and 38 minutes
```

### Series duration of my life

```js
const seriesDurations = [
  {
    title: "Game of thrones",
    days: 3,
    hours: 1,
    minutes: 0,
  },
  {
    title: "Sopranos",
    days: 3,
    hours: 14,
    minutes: 0,
  },
  {
    title: "The Wire",
    days: 2,
    hours: 12,
    minutes: 0,
  },
];
```

How much time of my life have I been watching series on tv? Let's find out! Calculate **how much time a tv series** have taken as a **percentage of an average lifespan** of 80 years.

Firstly change the `seriesDurations` array found above to include your favourite series. Find the duration of a series here: <https://tiii.me/>

Create a function that logs out the following text using the `seriesDurations` array:

```
Game of thrones took 0.01% of my life
Sopranos took 0.012% of my life
The Wire took 0.007% of my life

In total that is 0.2% of my life
```

Here is an example:

```js
const seriesDurations = [
  {
    title: "Game of thrones",
    days: 3,
    hours: 1,
    minutes: 0,
  },
];

function logOutSeriesText() {
  // write code here
}

logOutSeriesText(); // logs out the text found above
```

## Smart-ease - Back to the basics!

Smart-ease is going back to the basics. As always Smart-ease starts by helping people fix their problems. So let's venture out into the real world and see what we find:

### NOnoN0nOYes (Note taking app)

> You are sitting at a meeting. A person is presenting some interesting thought that you want to write down. You check your bag, but realise that you forgot to bring your notepad. Hmm you check the internet for an online solution. But you need to signup for them all, too bad... Maybe this could be a worthwhile problem so solve. Let's create a simple and easy to use notepad 📝

#### Save a note

The first thing we will create is the functionality to **save a note**: Create a variable called `notes` and assign it to an empty array. Create a function called `saveNote`. The `saveNote` has two parameters:

* `content` parameter is a string.
* `id` is a number.

The `saveNote` function should push an object to the `notes` array with the keys `content` and `id`. Here is an example

```js
const notes = [];

function saveNote(content, id) {
  // write some code here
}

saveNote("Pick up groceries", 1);
saveNote("Do laundry", 2);

console.log(notes); // [{content: 'Pick up groceries', id: 1}, {content: 'Do laundry', id: 2}]
```

#### Get a note

**Now a user can save a note**, but what if a user wants to **see a specific note**, but only remembers the id? Let's create that functionality:

Create a function called `getNote`. The function has one parameter called `id`. When calling this function with an id it should return the relevant note object that corresponds to the id. If no id is specified or if the id is not a number, log out an error string. Hint: Use a for loop.

```js
function getNote(id) {
  // your code here
}

const firstNote = getNote(1);
console.log(firstNote); // {content: 'Pick up groceries', id: 1}
```

#### Log out notes

Now a user can both save and get a note. What if the user just wants to **read all their notes?** Let's also create that functionality:

Create a function `logOutNotesFormatted`. When calling the function it should log this string out for every note: "The note with id: 1, has the following note text: "some example note"."

```js
function logOutNotesFormatted() {
  // your code here
}

logOutNotesFormatted(); // should log out the text below

// The note with id: 1, has the following note text: Pick up groceries
// The note with id: 2, has the following note text: Do laundry
```

#### Unique feature

Suddenly you get this great idea for making the note app even better!

Come up with a unique feature **you think would make this app better.** Write down the idea and see if you can implement it. If not don't worry :) If it is too hard to implement try and ask in the slack channel :)

Try an [**interactive version 💻 of your code**](https://codepen.io/dalsHughes/pen/poJGejX). Remember to insert your code in the top of the codePen :)

### CactusIO-interactive (Smart phone usage app) *optional*

> After a long day you come home to relax. The first thing you do is find your phone and start watching some youtube. Then check facebook, and then reading some news. Suddenly a hour has passed. What happened to all that time you think to yourself. Maybe we can create some program to help with this problem! What if we could help users manage their smart phone usage?

It's going to work like this: A user can add smartphone activities. Then they can see a status on how their smartphone usage is going.

#### Adding an activity

Let's create the first part of the functionality that is **adding activities.**

Create a variable called `activities` that stores all activities of the day. What type of variable would you think would make sense? Create a function called `addActivity`. It should have three parameters: `date`, `activity` and `duration`. The `date` should be a string, the `activity` a string and the `duration` a number. To save the activity push an object that contains the date, the activity and the duration to the activities variable.

Now a user can add an activity by writing:

```js
addActivity("23/7-18", "Youtube", 30);

/*
activities should now look like this
[{
    date: '23/7-18',
    activity: 'Youtube',
    duration: 30,
}]
*/
```

Just adding activities won't help the user very much, we need to **add some functionality** to show the user how **their smart phone usage is going.**

#### Show my status

Create a function called `showStatus`. This function should use the activities variable and return a string saying the following: "You have added 3 activities. They amount to 78 min. of usage"

```js
showStatus(activities); // will log out this "You have added 3 activities. They amount to 78 min. of usage"
```

Now what happens if we call `showStatus` and `activities` is empty? We need to take that into consideration: If `activities` is empty log out a string that says: "Add some activities before calling showStatus"

#### Usage limit

A user asks us if it is possible to **set a limit for their smartphone usage.** "Off course it is" we promptly reply! We need to store that limit somewhere, but where and what type should this be? So how should it work? When `showStatus` is called and the user's usage is above the limit that they set, log out the following string: "You have reached your limit, no more smartphoning for you!"

Try and add some activities and call `showStatus`

#### Extra feature

Come up with one feature you think would be helpful for this program.

Optional

* Let's improve the `addActivity`, so that we don't need to specify the date, but the function automatically figures out what the date is. Check out this link: <https://stackoverflow.com/a/34015511>
* Improve the `showStatus` function by only showing the number of activities for that specific day.
* Create a function for calculating the activity a user has spent the most time on.

## Bonus assignment

The bonus assignment for this week (for those of you want an extra challenge) do the following:

* <https://www.codewars.com/kata/job-matching-number-1/train/javascript>
* <https://www.codewars.com/kata/job-matching-number-2/train/javascript>
* <https://www.codewars.com/kata/unfinished-loop-bug-fixing-number-1/train/javascript>


# Week 4

## Learning goals

* [ ] Recap of js basics
  * [ ] Variables
  * [ ] Types
  * [ ] Conditionals
  * [ ] Functions
  * [ ] For loop
  * [ ] scope
  * [ ] Arrays
  * [ ] Objects
* [ ] Solving problems

## Relevant links

* [Preparation](/course-content/foundation/intro-to-javascript/week4/preparation)
* [Assignment](/course-content/foundation/intro-to-javascript/week4/assignment)
* [Session Plan](/course-content/foundation/intro-to-javascript/week4/session-plan)


# Preparation

Go through the learning goals of week 1, week 2 and week 3 of javascript. Make sure you understand the concepts!

* [Week 1 learning goals](/course-content/foundation/intro-to-javascript/week1)
* [Week 2 learning goals](/course-content/foundation/intro-to-javascript/week2)
* [Week 3 learning goals](/course-content/foundation/intro-to-javascript/week3)

*Please go through the material and come to the session prepared!*


# Session Plan

* Recap of js basics
  * Variables
  * Types
  * Conditionals
  * Functions
  * For loop
  * scope
  * Arrays
  * Objects
  * Ask the trainees what they need to get repeated. Or figure it out by doing some code example.
* Solving problems
  * <https://dev.to/aprietof/5-steps-to-solving-programming-problems--502d>
* [Code inspiration](#fibonacci-sequence)
* [Exercises](#exercises)

This session is about getting the basics hammered down. We have had a lot of trainees who think the js module is too difficult. That is why this session is here, to ease the steepness of the js learning curve.

Focus on

* Recapping what the trainees struggle with
* Letting the trainees learn a framework for solving problems
* Lots and lost of exercises 💪

## Typical misconceptions

* Difference between return and console.log
* What console.log does and what it is made for

## Code inspiration

### Fibonacci Sequence

Given a specific position in the Fibonacci sequence, return the Fibonacci number.

```js
// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

fib(5); // 3
fib(10); // 34
```

Try not to just solve the problem, but explain what you are doing and thinking!

Try using this as a framework for solving the problem: <https://dev.to/aprietof/5-steps-to-solving-programming-problems--502d>

## Exercises

### Fizz buzz

This is a classic programming task.

Create a function that prints the numbers from 1 to 100. But for multiples of three print `Fizz` instead of the number and for the multiples of five print `Buzz`. For numbers which are multiples of both three and five print `FizzBuzz`.

When that works. Make the two number for multiples into parameters. So it can be called like this:

`fizzBuzz(4, 12);`

### Build a sentiment analyser

A sentiment analyser is some functionality that figures out how positive/negative a sentence is.

For example, the sentence \`I am mega super awesome happy" Should have a high score The sentence "I hate doing boring stuff" should have a low score.

Create a function that takes a string as a parameter. calling the function will return an object with `score`, `positiveWords` and `negativeWords`. You decide how the score should be implemented and what words are negative and positive.

Here is an example of using the function:

```js
const sentimentScoreObject = getSentimentScore("I am mega super awesome happy");

console.log(sentimentScoreObject);
/*
{
  score: 3,
  positiveWords: ['happy', 'awesome', 'super'],
  negativeWords: [],
}
*/
```

### Credit card number formatter

This is a very real world example of a problem I got at my previous work. I was tasked to implement one of the smart credit card input fields, where the credit card numbers are separated with a space. e.g. inputting 123456789 would show 1234 5678 9.

![Credit card formatter](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-9a481ce179a1edc7ecc1dffa810ea126ca109579%2Fcredit-card-formatter.gif?alt=media)

Create a function that takes a number as parameter. The function should return the following object:

```js
const formattedCreditCardObject = formatCreditCardNumber(123456789);
console.log(formattedCreditCardObject);
/*
{
  original: 123456789,
  formatted: "1234 5678 9",
}
*/
```

Thins to consider:

* What should happen if the function is called with an argument that is not a number?

### Character frequencies

Write a function that counts the frequency of characters in a string:

```js
console.log(getCharacterFrequencies("happy"));
/*
{
  h: 1,
  a: 1,
  p: 2,
  y: 1
}
*/
```

The expected output above allows for a relatively simple solution mechanism. Hint: Think about using object property accessors. For a bigger challenge, you can try to write the same function for a different expected output as seen below. It will require implementing some additional logic.

```js
/*
{
  characters: [
    {
      character: 'a',
      count: 1
    },
    {
      character: 'h',
      count: 1
    },
    {
      character: 'p',
      count: 2
    },
    {
      character: 'y',
      count: 1
    }
  ], length: 5
}
*/
```

### Palindromic substring

Write a function that finds the longest palindromic substring of a given string.

### Credit card info

Similar to the format credit card number, now we need to identify the credit card type.

```js
console.log(getCardInfo(4781321334789876)); // 'visa'
```

How can we find out what rules there are for credit cards? Programmers best friend is always available :)

### Tic Tac Toe

Draw a tic tac toe game.

Write a function called `getRenderedGame(position)` that takes `position` as parameter. `position` is a two dimensional array that shows the position of a game.

Here is an example:

With the following two dimensional array

```js
const position = [
  ["x", "o", " "],
  [" ", "o", " "],
  [" ", "o", "x"],
];

const renderedGame = getRenderedGame(position);
console.log(renderedGame);

/*
 *******
 *x*o* *
 * *o* *
 * *o*x*
 *******
 */
```

Create a new function called `getGameInfo(position)`. Calling the function should return an object with `winner` key, `loser` key, `hasEnded` and `nextPlayer`.

EXAMPLES!!!!

```js
const position = [
  ["x", "o", " "],
  [" ", "o", " "],
  [" ", "o", "x"],
];

const gameInfo = getGameInfo(position);
console.log(gameInfo);

/*
{
  winner: 'o',
  loser: 'x',
  hasEnded: true
}
*/
```

```js
const position = [
  ["x", "o", " "],
  [" ", " ", " "],
  [" ", "o", "x"],
];

const gameInfo = getGameInfo(position);
console.log(gameInfo);

/*
{
  winner: undefined,
  loser: undefined,
  hasEnded: false
}
*/
```

Try and make the game playable! *optional*

### Conway's game of life *optional*

<https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life>

And finally, feel free to fill out the form to help us improve the module and the exercises. The [survey](https://forms.gle/irckYkBdvSb6Tdz57) here is addressed to the session lead and session assistant, while this [survey](https://forms.gle/ttdDLcSJ88ksz6xe7) is for assignment helpers.


# Assignment

## Why should I even do this assignment?

Understanding the basics of Javascript is SUPER important. Therefore this assignment focuses on repeating the basics to really have a solid understanding of this.

If you struggle to do this weeks assignment, go through the last 3 weeks readme files: [Week 1: Variables](/course-content/foundation/intro-to-javascript/week1#variables), [Week 2: Logical Operators](/course-content/foundation/intro-to-javascript/week2#recap-logical-operators), [Week 3: Objects](/course-content/foundation/intro-to-javascript/week3#objects).

## Finishing session exercises

Finish the exercises from the session!

## CodeWars

Complete these Katas in codeWars:

* [7kyu Vowel Count](https://www.codewars.com/kata/54ff3102c1bad923760001f3)
* [7kyu Digit\*Digit](https://www.codewars.com/kata/546e2562b03326a88e000020)
* [7kyu Highest and Lowest](https://www.codewars.com/kata/554b4ac871d6813a03000035)

Post a link to your codeWars profile when you submit the assignment!

## Voice assistant

You will be building a voice assistant 🤖! Is that even possible in javascript, YES! EVERYTHING is possible in javascript 💪 (nearly)

Create a function called `getReply(command)`. The function should return a response that corresponds to the command!

These are the commands you should be able to give the voice assistant:

* `Hello my name is Benjamin` - Should save the name benjamin. and respond with "nice to meet you Benjamin". What if someone writes this twice?
* `What is my name` - should respond with the name of the person. What if the name has not yet been mentioned?
* `Add fishing to my todo` - Should respond with "fishing added to your todo". Should add fishing to a list of todos
* `Add singing in the shower to my todo` - Should add singing in the shower to a list of todos
* `Remove fishing from my todo` - Should respond with "Removed fishing from your todo"
* `What is on my todo?` - should respond with the todos. e.g. you have 2 todos - fishing and singing in the shower
* `What day is it today?` - Should respond with the date in a human readable format. E.g. if today is 30/8/2019 then it should respond with 30. of August 2019
* Should be able to do simple math. e.g. `what is 3 + 3` should respond with 6. Or `what is 4 * 12` should respond with 48
* `Set a timer for 4 minutes` - Should respond with "Timer set for 4 minutes". When 4 minutes is up: "Timer done". How do we set a timer in js? Google is your friend here!
* Add one or more command to your voice assistant

Here is an example of usage:

```js
console.log(getReply("Hello my name is Benjamin")); // "Nice to meet you benjamin"
console.log(getReply("What is my name?")); // "Your name is Benjamin"
console.log(getReply("Add fishing to my todo")); // "fishing added to your todo"
```

When you are done, add your `getReply` function and global variables to this CodeSandbox and try the voice command out with both commands and speech!

\---> <https://codesandbox.io/s/beautiful-worker-gnhbw> <## Assignment checklist

Go over your assignment one last time:

* [ ] Does every file run without errors and with the correct results?
* [ ] Have you used `const` and `let` and avoided `var`?
* [ ] Do the variable, function and argument names you created follow the [Naming Conventions](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/naming_conventions.md)?
* [ ] Is your code well-formatted (see [Code Formatting](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/code_formatting.md))?


# Intro to Web Architecture

The purpose of this module is to provide a mental model of how web sites work, some of the key terminology and how these concepts relating to the coming modules on the course.

You'll be introduced to lots of new concepts in this module, and it's not important to *remember* or *deeply understand* everything that's covered. What's important is you understand that they exist and how they fit together. You'll learn a lot more about how they work throughout the rest of the course.

| Week | Topic             | Preparation                                                                     | Session Plan                                                                      | Assignment                                                                    |
| ---- | ----------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| 1.   | How web apps work | [Preparation](/course-content/foundation/intro-to-web-architecture/preparation) | [Session Plan](/course-content/foundation/intro-to-web-architecture/session-plan) | [Assignment](/course-content/foundation/intro-to-web-architecture/assignment) |

## Learning goals

* [ ] Understand the key components of a web application
* [ ] Know what happens when you enter a URL in a web browser
* [ ] Be able to describe the difference between frontend and backend functionality
* [ ] Describe the role of HTML, CSS and JavaScript
* [ ] Understand what HTTP is and its methods
* [ ] How APIs are provided and used


# Preparation

## Pre-reading

Before the session, please read/watch these materials to get familiar with the basic concepts:

* [Intro to Web Architecture](https://medium.com/storyblocks-engineering/intro-to-web-architecture-a3224e126947) - Comprehensive introduction to web architecture fundamentals
* [Everything You Need to Know to Become a Junior Web Developer](https://medium.com/geeks-for-tech/everything-you-need-to-know-to-become-a-junior-web-developer-7ff429df477) - Explains client-server model and roles
* [Client server model](https://www.youtube.com/watch?v=L5BlpPU_muY) (6 min)
* [The structure of a web application](https://www.freecodecamp.org/news/how-the-web-works-part-ii-client-server-model-the-structure-of-a-web-application-735b4b6d76e3/) - Read up until the "That's all folks! (Well, sorta…)" part
* [HTTP and Everything You Need to Know About It](https://www.freecodecamp.org/news/http-and-everything-you-need-to-know-about-it) - Comprehensive but beginner-friendly HTTP guide

## For the exercises

* [Sequence Diagram Tutorial](https://creately.com/guides/sequence-diagram-tutorial/) - Complete guide with examples

These resources will help you understand the fundamental concepts we'll be discussing in the session.


# Session Plan

## Session materials

These are some examples of previously created materials by mentors that you can use yourself, or for inspiration.

* Intro to Web Architecture ([key](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/intro-to-web-architecture/session-materials/web-architecture-101.key), [pdf](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/intro-to-web-architecture/session-materials/web-architecture-101.pdf), [zip](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/intro-to-web-architecture/session-materials/web-architecture-101.zip) by [@rvedotrc](https://github.com/rvedotrc))

## Session outline

### Introduction

Key points:

* This module is rather different from the other technical modules
* You don't have to remember everything in this module
* The purpose of this module is to give an understanding of how the remaining modules fit together

### HTTP

Key points:

* The structure of a URL (scheme, host, path)
* Finding a host with DNS
* Establishing a connection (TCP)
* Content-Type instead of file extension
* An HTTP GET request/response, at the most simple level

### Front end vs back end

Key points:

* To make our web page available, we have to have a server
* That server needs to run some software: a web (http) server
* The server needs whatever software *it* runs, plus files for the browser
* Some of our code runs in the browser; some of our code runs on the host
* This is "front end" and "back end"
* The frontend and backend communicate via HTTP. Frontend makes a request, and backend answers with a response.
* We get to write software for both sides.

### The front end

Key points:

* Usually the starting URL is going to be `text/html`
* How HTML refers to other resources
* JavaScript is the only available language
* What JavaScript in the browser can and can't do
* Typical things we'll do with front-end JavaScript, like manipulating web pages and making requests to servers

### The back end

Key points:

* The primary goal is to send back responses for every HTTP request
* HTTPS listen, handle request
* What HTTP requests/responses "look like"
* Serving static content
* It is just software. We can extend it!
* Any language, but we'll be using JavaScript
* We can also do things like read and write files (on the server), talk to a database or to other servers

### Data and APIs

Key points:

* What an API is
* JSON as the common data format
* **CRUD** stands for **Create, Read, Update, Delete** - the four basic operations for managing data. Conceptual introduction - we'll explore CRUD in detail in the databases module
* These operations map to HTTP methods:
  * **Create** → add new data
  * **Read** → retrieve data
  * **Update** → modify existing data
  * **Delete** → remove data
* Most web applications are essentially CRUD applications with a user interface
* HTTP methods:
  * `GET` = retrieve data = R(ead) in CRUD
  * `POST` = send data = C(reate) in CRUD
  * `PUT` = update data = U(pdate) in CRUD
  * `DELETE` = delete data = D(elete) in CRUD
* How different methods carry data:
  * `GET` → uses query parameters
  * `POST`, `PUT` → use request body
  * `DELETE` → usually no data
* Role of content type: servers specify how to interpret data (e.g. `application/json`)
* Idea that "the page" and "the data" are separate things
* Data store services (in the abstract). Persisting data away from the web server.

### More complex setups

Key points:

* This section talks about things *beyond* what Hack Your Future covers
* It's a taster of what things start to look like in larger, real-world scenarios
* The client/server terminology
* Adding a database server
* Multiple environments
* Deployment is about making sure the server has all the code, files and settings that it needs

## Exercises

### HTTP Request Analysis

Analyze the following URL and break it down into its components:

`https://api.github.com/users/octocat/repos?sort=created&per_page=10`

1. Identify the scheme, host, path, and query parameters
2. What HTTP method would be used to access this URL?
3. What Content-Type would you expect in the response?
4. What happens when you type this URL in a browser?

### Frontend vs Backend vs Database Classification

Categorize the following statements into: **Frontend**, **Backend** or **Database**:

* "Runs in the user's browser"
* "Handles HTTP requests and responses"
* "Can manipulate the DOM"
* "Stores user information permanently"
* "Sends JSON data to the server"
* "Validates user input before saving"
* "Renders HTML pages"
* "Connects to a database"
* "Executes JavaScript on the server"
* "Serves static files like CSS and images"
* "Processes form submissions"
* "Shows a loading spinner while waiting for data"
* "Encrypts passwords before storing them"
* "Updates the page without refreshing"
* "Sends emails to users"

Work in small groups and present your categorization to the team.

### API Design

Design an API for an advanced to-do list application for teams.

*Note: You don't need to create proper REST endpoints - just focus on the basic structure and HTTP methods.*

Design endpoints for:

* Getting all tasks
* Getting a specific task
* Creating a new task
* Updating a task (e.g., changing status, assigning to user)
* Deleting a task

For each endpoint, specify:

* HTTP method
* URL path
* Request format (if applicable)
* Response format
* Status codes

Example:

```markdown
GET /api/tasks
Response: 200 OK
Content-Type: application/json
Body: [{"id": 1, "title": "Fix login bug", "description": "Debug authentication issue", "status_id": 2, "user_id": 2, "created": "2024-01-15 10:30:00", "updated": "2024-01-15 14:20:00", "due_date": "2024-01-20 17:00:00"}]
```

*Note: This design will be revisited in upcoming modules - you'll create the database in the databases module and implement these endpoints in the intro-to-backend module!*

### System Architecture Design

*This should be done as a collaborative demo with the mentor leading and asking questions to trainees.*

#### Part 1: Architecture Diagram (Mentor Demo)

Design a simple to-do list application with basic CRUD operations:

1. **Create**: Add a new todo item
2. **Read**: Display all todo items
3. **Update**: Mark a todo as completed
4. **Delete**: Remove a todo item

**Mentor should:**

* Help trainees to visualize application first
* Draw the architecture diagram on a whiteboard/digital tool while asking trainees questions
* Guide trainees to identify: frontend, backend, database components
* Ask: "Where should the todo data be stored?" "How does the frontend talk to the backend?"
* Keep it simple - just one page with a list of todos and basic functionality
* Show a simplified example (not professional-level complexity)

#### Part 2: Sequence Diagrams (Mentor Demo + Trainee Exercise)

**Mentor Demo (first 2 flows)**

* Explain what sequence diagrams are with simple examples
* Demonstrate CREATE and READ flows step-by-step
* Show the communication: User → Frontend → Backend → Database
* Use simple format like:

  ```
  User → Frontend → Backend → Database
  User clicks "Add Todo" button
  Frontend sends POST /todos with todo data
  Backend saves data to database
  Backend sends success response
  Frontend updates the page
  ```

**Trainee Exercise**

* Work in pairs to create sequence diagrams for UPDATE and DELETE flows
* Share results with the rest of the trainees
* Mentor shows "correct" examples at the end

*Note: This prepares trainees for the assignment, therefore can't be skipped.*


# Assignment

## Design Recipe Collection App

Design the architecture for a simple recipe collection application where users can manage their favorite recipes.

### Requirements

The app should allow users to:

* **Create**: Add a new recipe (title, ingredients, instructions)
* **Read**: View all recipes and individual recipe details
* **Update**: Edit existing recipes
* **Delete**: Remove recipes they no longer want

### Your Task

1. **Draw a simple diagram** showing the architecture of this recipe app
2. **Identify the components**:
   * Where is the recipe data stored?
   * How does the frontend communicate with the backend?
   * What happens when a user adds a new recipe?
3. **Create sequence diagrams** showing the communication flow for:

   * Adding a new recipe
   * Viewing a specific recipe
   * Editing an existing recipe

   Use this format to show how different parts communicate:

```markdown
User → Frontend → Backend → Database
User clicks "Add Recipe" button
Frontend sends POST /recipes with recipe data
Backend saves data to database
Backend sends success response
Frontend updates the page
```

*Need help with sequence diagrams? Check out this* [*tutorial on sequence diagrams*](https://creately.com/guides/sequence-diagram-tutorial/)*.*

### Deliverables

Submit a document (text, image, or diagram) that includes:

* Your architecture diagram
* Brief explanations of each component
* Sequence diagrams for the three user flows

Keep it simple and focus on the basic structure - you don't need to worry about complex features like user authentication or advanced search.

### Tools for Creating Diagrams

Need help creating your diagrams? Here are some free drawing tools you can use:

* [**Excalidraw**](https://excalidraw.com/) - Simple, collaborative whiteboard tool perfect for technical diagrams
* [**Draw.io**](https://app.diagrams.net/) - Free online diagramming tool with many templates
* [**Google Drawings**](https://docs.google.com/drawings/) - Simple drawing tool integrated with Google Workspace

### Tips

* Think about what the user sees (frontend) vs what happens behind the scenes (backend)
* Consider where recipe data needs to be stored permanently
* Remember that the frontend and backend need to communicate somehow
* For sequence diagrams, show the step-by-step communication between User → Frontend → Backend → Database
* Include HTTP methods (GET, POST, PUT, DELETE) in your sequence diagrams


# Databases

In this session, trainees will be introduced to the core concepts of databases, including why we use them, how data is modeled, and how to interact with a relational database using SQL.

| Week | Topic                                                                   | Preparation                                                           | Assignment                                                          | Session Plan                                                            |
| ---- | ----------------------------------------------------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| 1.   | [Introduction to databases](/course-content/foundation/databases/week1) | [Preparation](/course-content/foundation/databases/week1/preparation) | [Assignment](/course-content/foundation/databases/week1/assignment) | [Session Plan](/course-content/foundation/databases/week1/session-plan) |

## Learning Goals

* [ ] Explain what a database is and why we use them
* [ ] Understand basic relational data terminology: table, row, column, primary key, foreign key
* [ ] Perform basic SQL operations: SELECT, INSERT, UPDATE, DELETE
* [ ] Use simple filtering and sorting techniques
* [ ] Understand simple database design & schemas


# Week 1

In this session, trainees will be introduced to databases, including why we use them, how data is modeled, and how to interact with a relational database using SQL.

## Learning Goals

See [this module's learning goals](/course-content/foundation/databases#learning-goals).

## Main Topics

* **What is a database?** Why we use databases, real-life data models, and the role of databases in software systems.
* **Relational data terminology:** Table, row, column, primary key, foreign key.
* **Schemas and entities:** How to design and understand simple schemas.
* **Basic SQL operations:**
  * SELECT: Retrieving data
  * INSERT: Adding data
  * UPDATE: Modifying data
  * DELETE: Removing data
* **Filtering and sorting:** WHERE, LIKE, ORDER BY, LIMIT


# Session Materials


# DBeaver UI

## Create a New SQLite Connection

1. Click the **"New Database Connection"** button (plug icon) in the toolbar or `Ctrl+Shift+N` ![Create new connection](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-89f18e844342ef77c181eb1d5e7a7f8bfb87f184%2Fcreate-new-connection.png?alt=media)
2. Select **SQLite** from the list of databases ![Choose sqlite](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-6d0e6d1d5a21cae3ec49088e0abdcd84ec4250eb%2Fchoose-sqlite.png?alt=media)
3. Click **Next**
4. In the **Path** field, click **Browse** and choose where to save your database file ![Create save path](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-ce46ebd0be14fcc0c259350b4fc3b12c271cf043%2Fcreate-save-path.png?alt=media)
5. Name your database file: `tasks.sqlite3` **EXTENTION IS IMPORTANT**
6. Click **Test Connection** to verify everything works
7. Click **Finish**

## Browse through database

![View your database](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-ffaa2e33b98d03856b81adf4bd4432b94485908f%2Fdatabase-view.png?alt=media)

## Create and run queries

Open a new SQL script to write your queries in. ![Open new script](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-9dff3a4256bffccb8e15f085050f777a21206c91%2Fnew-sql-script.png?alt=media)

When running queries it is important to remember few things: ![Run your queries](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-0418e0a89b898d44f30ca202a9c541da209bb005%2Frun-queries.png?alt=media)

1. Orange triangle will only **run the selected query**.
2. Little document with triangle will **run the entire script file**.
3. **Query is selected** when it is **manually selected** or **the cursor is standing on the query**.
4. **Always remember to end queries with semi-colon**: `;`! Otherwise the edit does not know when query ends!

## Errors will be marked

In case of errors, DBMS will mark them red. If you hover on the error, **DBMS will tell you the exact issue with your query**! ![Errors](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-9ec3d07a4e57ca61d9736bc0cbac6b80f55995b7%2Ferrors.png?alt=media)

## Saving queries for homework

When done with queries, save them to your homework repo using this "Save As" like from any other software. Remember the `.sql` extention! ![Save as for homework](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-ac254325d6e94151f60d3f6bf6566ce03eec09c9%2Fsave-queries.png?alt=media)


# Preparation

We will use **SQLite** for all exercises, as it requires no installation and works out-of-the-box with most environments.

## Prerequisites

We're going to use Dbeaver, a free and open-source database management tool that supports SQLite and many other databases.

* [ ] Download and install [Dbeaver](https://dbeaver.io/download/)
  * [ ] \[Optional] Have a look around the interface <https://dbeaver.com/docs/dbeaver/Application-Window-Overview/>
* [ ] There's also a VSCode extension for SQLite called [SQlite Viewer](https://marketplace.visualstudio.com/items?itemName=qwtel.sqlite-viewer).

## Reading list

* [Introduction to Databases](https://mariadb.com/docs/general-resources/database-theory/introduction-to-relational-databases)
* [Relational Database Terms](https://mariadb.com/docs/general-resources/database-theory/relational-databases-basic-terms)

## Extra materials

* [DBeaver Playlist](https://www.youtube.com/playlist?list=PLkh7-EMxQiV2DAiruEWgh-i4jreuyX1rP)
* [SQLite Tutorial](https://www.sqlitetutorial.net/)
* [w3schools SQL Tutorial](https://www.w3schools.com/sql/)
* [SQL Tutorial](https://www.sqltutorial.org/)


# Session Plan

## Session Materials

* [Database Diagram](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/databases/week1/session-materials/database-diagram.jpg) - The diagram of the database to be created in this session
* [Sample Tasks database](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/databases/week1/session-materials/tasks.sqlite3) - Pre-created SQLite database with the contents of [this SQL file](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/databases/week1/session-materials/session-data.sql)

## Session Outline

1. [Introduction to Databases](#what-is-a-database)
   * Briefly explain what a database is and why we use them.
   * Discuss the importance of databases in modern applications.
2. [Creating Your First Database](#creating-your-first-database)
   * Guide trainees through creating a new database.
   * Execute the provided SQL file to create tables and insert sample data.
   * Ensure everyone has the same starting point.
   * Introduce key terms: table, row, column, primary key, foreign key.
3. [Interacting with your database](#interacting-with-your-database)
   * Demonstrate basic SQL commands: SELECT, INSERT, UPDATE, DELETE.
   * Show examples of filtering and sorting data using WHERE, ORDER BY, and LIMIT clauses.
   * Encourage trainees to follow along and execute commands on their own databases.

## What is a database?

A database is an organized collection of structured information, or data, typically stored electronically in a computer system. Think of it as a digital filing cabinet where you can store, retrieve, and manage information efficiently.

### Real-Life Examples

#### 1. Personal Use

* **Contact List**: Your phone's contact list is a simple database storing names, phone numbers, and email addresses
* **Photo Library**: Your phone's photo app is a database organizing images by date, location, or album
* **Excel Spreadsheets**: When you track your monthly expenses or create a shopping list, you're essentially using a simple database

#### 2. Business Use

* **Inventory Management**: Stores use databases to track products, their quantities, and prices
* **Customer Records**: Businesses maintain databases of customer information, purchase history, and preferences
* **Employee Management**: Companies store employee details, attendance, and payroll information

#### 3. Everyday Services

* **Banking Systems**: Your bank uses databases to track your account balance, transactions, and personal information
* **Social Media**: Platforms like Facebook or Instagram store user profiles, posts, and connections
* **Online Shopping**: E-commerce sites use databases to manage product catalogs, customer orders, and shipping information

### What do we gain from using a database?

1. **Organization**: Databases help keep information structured and easy to find
2. **Efficiency**: They allow quick access to specific pieces of information
3. **Data Integrity**: They help maintain accurate and consistent data
4. **Security**: They provide controlled access to sensitive information
5. **Scalability**: They can handle growing amounts of data efficiently
6. **Reliability**: Data is protected from loss or corruption
7. **Shareability**: Multiple users can access the same data

Think of a database as a well-organized digital library where you can store and retrieve information quickly and efficiently, just like how you might use a filing cabinet or spreadsheet, but with more power and flexibility.

### Databases in Software Architecture

In modern software applications, databases serve as the backbone of data storage and management. Let's look at some common examples:

* Imagine a recipe website where users can share their favorite dishes. The database stores all the recipes, user profiles, comments, and ratings. When someone searches for "chocolate cake," the website queries the database to find all relevant recipes.
* A movie streaming platform uses databases to store information about movies, user watchlists, and viewing history. When you log in, the system retrieves your preferences and watch history from the database to recommend new movies.
* Even a simple blog needs a database to store articles, comments, and user information. Without a database, these applications would be like a library without a catalog system - you might have all the information, but finding and managing it would be extremely difficult.

## Database vs Database Management System

### Real-Life Example - Online Store

Imagine you're running an online store. You need to maintain such data entries like:

* inventory
* orders
* customer information
* and many more.

Now, a customer X makes an order. To process the order, you must update the inventory, check the customer data, update the order status at each way of the process, add order to customer information etc. Seems like a lot of work, doesn't it?

What if that work could be automated and better, validated on the go, so all of the records match each other? This is where **DBMS** comes into the scene!

1. **Without DBMS**: You'd need to manually update spreadsheets for inventory, orders, and customer information
2. **With DBMS**:
   * When someone places an order, the system automatically:
     * Updates inventory
     * Creates an order record
     * Sends confirmation emails
     * Updates customer history
   * All of this happens instantly and accurately

Think of a DBMS as your digital assistant that helps you manage your data efficiently, securely, and reliably, just like how a librarian helps manage a library's collection of books.

### Popular DBMS Options

#### 1. [MySQL](https://www.mysql.com/)

* **Often used for**: Web applications, small to medium businesses
* **Why**: Free, reliable, and widely supported
* **Example**: Many WordPress websites use MySQL to store their content

#### 2. [PostgreSQL](https://www.postgresql.org/)

* **Often used for**: Complex applications, large datasets
* **Why**: Powerful features, great for complex queries
* **Example**: Instagram uses PostgreSQL to store user data and photos

#### 3. [MongoDB](https://www.mongodb.com/)

* **Often used for**: Applications with changing data structures
* **Why**: Flexible, can handle different types of data easily
* **Example**: Many mobile apps use MongoDB for its flexibility

#### 4. [SQLite](https://sqlite.org/)

* **Often used for**: Small applications, mobile apps
* **Why**: Lightweight, no setup required
* **Example**: Many mobile apps use SQLite for local storage

## Creating Your First Database

The next step is creating a database to have a playground for learning SQL. Also it will help us explore the concepts of tables, rows, columns, primary keys, and foreign keys.

### Step 1: Create a New SQLite Connection

1. Click the **"New Database Connection"** button (plug icon) in the toolbar or `Ctrl+Shift+N`
2. Select **SQLite** from the list of databases
3. Click **Next**
4. In the **Path** field, click **Browse** and choose where to save your database file
5. Name your database file: `tasks.sqlite3`
6. Click **Test Connection** to verify everything works
7. Click **Finish**

[Guide with screenshot and additional DBeaver information](/course-content/foundation/databases/week1/session-materials/dbeaver-ui).

You can find more information in the [DBeaver documentation for Sqlite](https://dbeaver.com/docs/dbeaver/Database-driver-SQLite/).

### Step 2: Understanding Database Structure

So we just created our database. Before we create tables, let's understand the key concepts:

#### Database Terminology

* **Database**: The entire collection of related data (like a filing cabinet)
* **Table**: A collection of related records (like a folder in the filing cabinet)
* **Row (Record)**: A single entry in a table (like one document in a folder)
* **Column (Field)**: A specific piece of information in each row (like name, date, etc.)
* **Primary Key**: A unique identifier for each row
* **Foreign Key**: A reference to a primary key in another table

### Step 3: Create Tables and Insert Sample Data

1. On the [Session materials](#session-materials) you can find a sample SQL file. Copy the contents of this file.
2. In DBeaver, right-click on your database connection → **SQL Editor** → **Open SQL Script**
3. Paste the copied SQL commands into the editor
4. Click the **Execute SQL Script** button or press `Alt+X`. This will execute the whole script.

### Step 4: Explore Your Database

After executing the SQL file, you should see a database like the diagram this one.

![Database Diagram](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-2f023ab33082ed49d8de3255949819e65fda622e%2Fdatabase-diagram.jpg?alt=media)

#### Exercise 1

1. Follow the above steps if you haven't already.
2. **Explore your database** in DBeaver:
   1. What kind of **tables** can you find?
   2. Can you find how to see a **diagram** for your database?
   3. Select the `task` table. What kind of **properties** does it have?
   4. What kind of **data** is there? Can you explore the data in DBeaver?
   5. What is the `title` value in the row 18?

## Data types

Open the **properties** tab of `task` table again. What are these INTEGER, TEXT, DATETIME, etc?

When creating tables, we define the type of data each column will hold. This helps the database understand how to store and manage the data efficiently.

| Data Type | Description       | Usage                           |
| --------- | ----------------- | ------------------------------- |
| INTEGER   | Whole numbers     | For IDs, counts, ages           |
| REAL      | Decimal numbers   | For prices, measurements        |
| TEXT      | Text strings      | For names, descriptions, emails |
| BOOLEAN   | True/False values | For flags, status indicators    |
| DATE      | Date values       | For dates                       |
| TIME      | Time values       | For time                        |
| DATETIME  | Date and time     | For timestamps                  |
| BLOB      | Binary data       | For images, files               |

> \[!NOTE] No need to remember all of these Keep in mind, you can alway refer back to [cheatsheets](https://www.w3schools.com/sql/sql_datatypes.asp) or use any [documentation](https://www.sqlite.org/datatype3.html) when in doubt!

## Interacting with your database

Now that we have our database set up with tables and sample data, let's learn how to interact with it using **SQL (Structured Query Language).**

### What is SQL?

**SQL** (**S**tructured **Q**uery **L**anguage) is a specialized programming language designed for managing and manipulating data in relational database management systems. Unlike general-purpose programming languages such as JavaScript or Python, SQL is specifically focused on data operations.

Key Characteristics:

* **Declarative Language**: You describe what data you want, not how to get it
* **Standardized**: While different database systems may have variations, the core SQL commands are standardized
* **Powerful**: Complex data operations can often be performed with just a few lines of code
* **Used Everywhere**: From small mobile apps to large enterprise systems, SQL is the backbone of data management

4 main operations:

1. **SELECT**: Reading data from the database
2. **INSERT**: Adding new data to the database
3. **UPDATE**: Modifying existing data
4. **DELETE**: Removing data from the database

These four operations (collectively known as **CRUD** - Create, Read, Update, Delete) form the foundation of almost all database interactions.

Let's explore each of these operations in detail.

### SELECT - Retrieving Data

The SELECT statement is used to retrieve data from one or more tables. This is the most common SQL operation.

Basic Syntax:

```sql
SELECT column1, column2, ... FROM table_name;
```

Examples:

```sql
-- Retrieve all columns from the user table
SELECT * FROM user;

-- Retrieve only specific columns
SELECT name, email FROM user;

-- Retrieve data with a limit
SELECT * FROM user LIMIT 3;
```

### WHERE - Filtering Data

The WHERE clause is used to filter records based on specific conditions.

Basic Syntax:

```sql
SELECT column1, column2, ... FROM table_name WHERE condition;
```

Examples:

```sql
-- Find users with a specific name
SELECT * FROM user WHERE name = 'John Smith';

-- Find tasks with a certain status
SELECT * FROM task WHERE status = 'In Progress';

-- Find tasks created after a specific date
SELECT * FROM task WHERE created > '2023-01-01';
```

### ORDER BY - Sorting Data

The ORDER BY clause is used to sort the results in ascending or descending order.

Basic Syntax:

```sql
SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC|DESC];
```

Examples:

```sql
-- Sort users alphabetically by name
SELECT * FROM user ORDER BY name;

-- Sort tasks by creation date (newest first)
SELECT * FROM task ORDER BY created DESC;

-- Sort tasks by status and then by title
SELECT * FROM task ORDER BY status_id, title;
```

#### Exercise 2

Now that your database is set up, you're ready to practice SQL queries. Below are some exercises to help you get started.

1. List the names and phones of all of the users.
2. List all of the users, ordering them by name alphabetically.
3. Find the name of the user of id 10.
4. Find 3 oldest (by create date) tasks.

> \[!NOTE] Interested in more options? Refer back to [intro to sql cheatsheet](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/databases/pre-read/intro-sql.md) and practice some more complex queries!

### JOIN

JOIN allows to combine data from multiple tables. To join tables, you can use **foreign keys**!

**Example:**

```sql
-- Find task and it's status name
SELECT task.title, status.name
FROM task
JOIN status
ON task.status_id = status.id;
```

#### Exercise 3

1. Select all tasks which have status `In progress`.
2. Display list of tasks with the user names of the users attached to the tasks.

### INSERT - Adding Data

The INSERT statement is used to add new records to a table.

Basic Syntax:

```sql
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
```

Examples:

```sql
-- Add a new user
INSERT INTO user (name, email, phone) VALUES ('Jane Doe', 'jane@example.com', '555-1234');

-- Add a new task
INSERT INTO task (title, description, created, updated, status_id, user_id)
VALUES ('Learn SQL', 'Practice basic SQL operations', DATETIME('now'), DATETIME('now'), 1, 1);
```

### UPDATE - Modifying Data

The UPDATE statement is used to modify existing records in a table.

Basic Syntax:

```sql
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
```

> \[!IMPORTANT] ⚠️ Always include a WHERE clause with UPDATE statements. You don't want to update all records by mistake! 😵

Examples:

```sql
-- Update a user's email
UPDATE user SET email = 'new.email@example.com' WHERE id = 1;

-- Mark a task as completed
UPDATE task SET status_id = 3 WHERE id = 3;

-- Update multiple fields at once
UPDATE task SET title = 'New Title', description = 'New Description' WHERE id = 5;
```

### DELETE - Removing Data

The DELETE statement is used to remove records from a table.

Basic Syntax:

```sql
DELETE FROM table_name WHERE condition;
```

> \[!IMPORTANT] ⚠️ Same warning as with UPDATE. Don't forget your WHERE clause.

Examples:

```sql
-- Delete a specific user
DELETE FROM user WHERE id = 10;

-- Delete completed tasks
DELETE FROM task WHERE status_id = 3;
```

### Interactive Practice

Now, let's practice these operations together:

1. Run the following query to see all tasks:

   ```sql
   SELECT * FROM task;
   ```
2. Add a new task:

   ```sql
   INSERT INTO task (title, description, created, updated, due_date, status_id, user_id)
   VALUES ('Prepare presentation', 'Create slides for the team meeting', DATETIME('now'), DATETIME('now'), null, 2, 1);
   ```
3. Verify the task was added:

   ```sql
   SELECT * FROM task ORDER BY id DESC LIMIT 1;
   ```
4. Update the task status:

   ```sql
   UPDATE task SET status_id = 2 WHERE title = 'Prepare presentation';
   ```
5. Check that the update worked:

   ```sql
   SELECT * FROM task WHERE title = 'Prepare presentation';
   ```

#### Exercise 4

Combine all the queries you learned!

1. Add yourself as a new user in the `user` table
2. Create 2 or more tasks assigned to yourself
3. Update the task you just created to change its status to "In Progress" (status\_id = 2)
4. Retrieve only the title and description of all tasks assigned to you
5. Delete a task that you no longer need


# Assignment

Write SQL queries to answer the following:

1. How many tasks are in the task table?
2. How many tasks in the task table do not have a valid due date?
3. Find all the tasks that are marked as done.
4. Find all the tasks that are not marked as done.
5. Get all the tasks, sorted with the most recently created first.
6. Get the single most recently created task.
7. Get the title and due date of all tasks where the title or description contains **database**.
8. Get the title and status (as text) of all tasks.
9. Get the name of each status, along with a count of how many tasks have that status.
10. Get the names of all statuses, sorted by the status with most tasks first.

## How to submit

1. After running your queries in DBeaver, make sure to save them in one script file.
2. Make sure the file is of type `.sql`
3. Add task items as comments before your queries so it is easier to review:

```sql
-- 1. How many tasks are in the task table?
SELECT ... FROM ...;
-- 2. How many tasks in the task table do not have a valid due date?
SELECT ... FROM ...;
-- etc...
```

4. Create a pull request in your assignment repo as usual.


# Intro to Backend

Here you can find module content and assignments for the Intro to Backend module.

| Week | Topic                                                                                                                                           | Preparation                                                                  | Assignment                                                                 | Session Plan                                                                   |
| ---- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| 1.   | [How to build a simple webserver, creating and testing APIs, and interacting with databases](/course-content/foundation/intro-to-backend/week1) | [Preparation](/course-content/foundation/intro-to-backend/week1/preparation) | [Assignment](/course-content/foundation/intro-to-backend/week1/assignment) | [Session Plan](/course-content/foundation/intro-to-backend/week1/session-plan) |

## Learning goals

* [ ] Introduction to Node.js
  * [ ] [What is node and why node?](https://www.youtube.com/watch?v=pU9Q6oiQNd0)
  * [ ] V8 vs the browser that runs js?
  * [ ] What can you build with Node.js?
    * Utilities
    * Web server
    * Much more
* [ ] Building a simple webserver
  * [ ] Creating simple GET endpoints to return data, including from databases
* [ ] Sending requests
  * [ ] What is Postman
  * [ ] Making GET, POST AND DELETE requests to APIs using Postman
* [ ] Database interaction
  * [ ] What is CRUD (Create, Read, Update, Delete)
  * [ ] CRUD vs REST
  * [ ] Connecting to a database using JavaScript
  * [ ] Executing queries (i.e. CRUD)


# Week 1

For almost any web application, it is essential to have a backend. The backend is a place where we, the developers, can store our data, communicate with users and let the users communicate with us, do smart things like calculations, data processing etc.

There are many languages for this. We might've heard of Java, C, C++, Go, Python, Ruby, PHP and the list goes on. There are two reasons why we at HYF choose Node.JS over others:

1. You already know JavaScript, so it's easier to get started than other languages
2. Node.js is great for making web APIs because it is asynchronous by nature and thus allows for high input/output. By this we mean that it allows many users to make very light requests at the same time.

## Learning goals

See [this module's learning goals](/course-content/foundation/intro-to-backend#learning-goals).


# Preparation

## Basics of Backend development

* [Client server model](https://www.youtube.com/watch?v=L5BlpPU_muY) (6 min)
* [HTTP and HTML](https://www.youtube.com/watch?v=1K64fWX5z4U) (7 min)
* [Video about node](https://www.youtube.com/watch?v=pU9Q6oiQNd0) (13 min)
* [The structure of a web application](https://www.freecodecamp.org/news/how-the-web-works-part-ii-client-server-model-the-structure-of-a-web-application-735b4b6d76e3/) Up until the "That’s all folks! (Well, sorta…)" part

Try to formulate answers to these questions and bring your answers to the session:

1. What is the server and what is the client?
2. What is http?
3. What is Node.js?

## Basics of Node.js

* [First GET request (code introduction)](https://www.youtube.com/watch?v=QNw9q4YXR4E) (15 min)
* [Refresh on REST](https://fullstackopen.com/en/part3/node_js_and_express#rest)
* [A basic GET Request](https://fullstackopen.com/en/part3/node_js_and_express#fetching-a-single-resource)
* [A basic DELETE request](https://fullstackopen.com/en/part3/node_js_and_express#deleting-resources)
* [What is POSTMAN and how to install](https://fullstackopen.com/en/part3/node_js_and_express#postman) - Please install this before the session!

## Installation preparation

### Node

1. Setup `node` on your computer (skip to step 2 to check):
   1. Download from: [nodejs.org/en/download](https://nodejs.org/en/download/)
   2. Check if node is installed in your system by running the following commands in Command Prompt/PowerShell/Git Bash:
      * `node -v`
      * `npm -v`
      * In either case you should see the version of `node` or `npm` installed.

### Postman

[What is POSTMAN and how to install it](https://fullstackopen.com/en/part3/node_js_and_express#postman)


# Session Plan

***

**Code inspiration**: To find the code examples for this class as well as prepared Postman collection, navigate to [session materials](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/intro-to-backend/week1/session-materials/README.md) and follow the setup instructions in the readme.

***

## What is Node.js? (25 mins)

### Run your first app (10 mins)

[Node.js](https://nodejs.org/en/about) is a software that allows you to use JavaScript to write the application part of the backend. The application can be written in different .js files, which are then read and executed using the \`node\`\` command in the Command Line. For example:

```bash
node script.js
```

**Read the following article and code along:** [**Introduction into Node.js**](https://dev.to/sojida/introduction-to-nodejs-4ne8)

After completing the article, you see that in just one JavaScript file you can create and run a simple web server!

### Building Node applications (15 mins)

Software builds on other software. Node.js is powerful because it allows us to use software others have written to help build our own unique applications. In Node.js these are called **modules/packages/dependencies** (can be used interchangeably). An easy way to get access to these is by using the [Node Package Manager](https://docs.npmjs.com/about-npm), also known as `npm`.

**Read the following article and code along (chapter 3 & 4):** [**NPM basics for new developers**](https://daily.dev/blog/npm-basics-for-new-developers)

It is also powerful because we can use the language we already know, JavaScript, to write backend applications!

## Building a simple HTTP webserver (10 mins)

While there are many ways to achieve this, the most common package to use when making webservers is [Express](https://expressjs.com/).

To create a simple Node application and run Express, we need to follow few simple steps below. If you followed the previous part, you already have points 1 and 2 covered!

1. Run `npm init` in your directory of choice and follow the step to setup a simple Node app.
2. Run `npm install express` to install the Express package.
3. Navigate to your main js file (most likely `index.js`)
4. Import `express` into the file.
5. Initiate the server using `const app = express()`
6. Setup the listener for your server.

The finished code should look as follows:

```javascript
import express from "express";
const app = express();

app.listen(3000, function () {
  console.log(`> Ready on http://localhost:3000`);
});
```

At this point we have a server!!!

Looks similar? We did the same in the first section! This time, we can build on top of it and create our first serious Node application.

## Creating endpoints (5 mins)

Our server is up and running, but it certainly doesn't do much at this point. We need to add some **methods** to access or modify the data via server. Below is a simplified structure for such a method:

```javascript
app.get(
  // or .post .put .delete -> this tells the server what KIND of HTTP request this endpoint will handle
  "/", //path to the endpoint
  () => {}, // callback function to act on the endpoint call
);
```

**Callback function** in the Express endpoint has a predefined structure as well. For starters, it has certain **arguments**:

1. First is `request` argument. It can contain additional information about the **request** for the server. [Read more](https://expressjs.com/en/5x/api.html#req)
2. Second is `response`. It has methods to communicate the **response** out of the server back to the requester. [Read more](https://expressjs.com/en/5x/api.html#res.app)

Let's stop here and take a look:

```javascript
app.get("/", (request, response) => {
  //perhaps get some information from request here

  //then the response data using the response object methods
  response.send();
});
```

> **IRL example**: The arguments can have any names, as it is order that matters! Most often teams use `req` and `res`.

### GET request (10 mins)

In HTTP webpage, the GET request is also how we can obtain the HTML documents.

*Navigate to `examples/pages.js` to showcase this.*

For example, one might fetch simple HTML structure like this:

```javascript
app.get("/", (_request, response) => {
  response.send(`
      <h1>Main page</h1>
      <h2>Shows main content</h2>
  `);
});
```

GET request might receive additional arguments, either in the form of subpaths, but also **query parameters**.

Any endpoint can also perform much more logic than just fetching/setting data.

*Navigate to `examples/math.js` to showcase this.*

```javascript
app.get("/add", (request, response) => {
  console.log("Your query: " + request.query); // you can access your request query

  if (!request.query.a && !request.query.b)
    // you can add some validation if the query is correct
    return response.send(`
    <h1> No values to add! </h1>
    Append <code>?a=2&b=3</code> to the url
  `);

  const { a, b } = request.query; // you can fetch the information from the query
  const sum = Number(a) + Number(b); // you can perform operations

  response.send(sum); // you can send back the output
});
```

#### Exercise (15 mins)

Try it yourself in [exercise 1](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/intro-to-backend/exercises/exercise1.md): Run a simple webserver and add a basic route.

## Fetching data from database (45 mins)

Let's connect to previous module where we created a small database in Sqlite. This is one of the most common uses of the backend architecture, **to serve as a middle layer between a user and a database**.

To communicate with the database, we are going to use another library called [knex](https://knexjs.org/). To make this work, we need to run a CLI command to install the necessary packages:

```bash
npm i sqlite3 knex
```

*Navigate to `examples/data.js` to showcase this.*

### Connecting to database (5 mins)

No matter what kind of database you are using, first you need to establish a connection with it.

In Sqlite this is simple, we just need a **path** to the database and a Knex method to establish a connection.

```javascript
import knexLibrary from "knex";

const dbFile = "PATH_TO_THE_FILE/test.sqlite3";

const knex = knexLibrary({
  client: "sqlite3",
  connection: {
    filename: dbFile,
  },
});
```

...and we are connected!

### Fetching data (10 mins)

To fetch data from the database, we will of course use SQL like you learned in [previous module](/course-content/foundation/databases). We will combine the queries with Knex library method called `raw` like this:

```javascript
const results = await knex.raw("SELECT * FROM some_table");
```

Now we can create a simple GET endpoint and fetch our Task data from the database like so:

```javascript
app.get("/", async (request, response) => {
  // we use async here to show that we are going to be awaiting something
  const tasks = await knex.raw(`SELECT * FROM task`);
  // we use 'await' to make sure get back the information from the database to send back to the client
  response.json(tasks);
});
```

> **IRL example:** Knex is actually a very powerful library used commonly in node backend projects. When researching, you will encounter many more methods than `raw`. Read more [in the knex documentation](https://knexjs.org/guide/query-builder.html#knex) if you're interested :)

#### Exercise (30 mins)

Try it yourself! Follow the [exercise 2](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/intro-to-backend/exercises/exercise2.md): Connect to a database and returning more complex data.

## Postman (25 mins)

### Using Postman (10 mins)

Using Postman we can execute more elaborate queries, as well as easily test our code.

> **IRL example:** Teams use Postman to document their API and test the endpoints against development database!

1. Launch Postman app
2. Make sure your Node server is running
3. (Optional) Import Postman collection available in [session materials](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/intro-to-backend/week1/session-materials/README.md)
4. Run your queries

### POST request (10 mins)

Save some data in your database! Refresh the CRUD queries from the [last module](/course-content/foundation/databases). Here is an example endpoint to do so:

```javascript
app.post("/status", async (request, response) => {
  const { id, name } = request.body;

  if (!id || !name || name.length === 0) return response.sendStatus(400);

  await knex.raw(`insert into status(id, name) values(${id}, "${name}")`);
  response.sendStatus(200);
});
```

Test it in Postman. Remember to add the **body to your request** with required data! Remember as well that Express requires to be notified of potential data objects coming via requests. To do so, remember to add:

```javascript
app.use(express.json());
```

### Postman possibilities (5 mins)

It is a very powerful tool that enables you to create and test all sorts of endpoints. Make sure to explore the options and find out more in the [Postman docs](https://learning.postman.com/docs/sending-requests/requests/)

***

## Exercises

1. [Exercise 1](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/intro-to-backend/exercises/exercise1.md): Run a simple webserver and add a basic route
2. [Exercise 2](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/intro-to-backend/exercises/exercise2.md): Connect to a database and returning more complex data


# Assignment

## 1. Extend your webserver

In the session, you added plenty of useful routes to your API, but let's not stop there!

1. **Add 3 new routes**

   Think of 3 new useful routes yourself, and implement them.
2. **Extend the home route**

   Routes don't only have to return text or JSON, they can also return HTML content to be displayed in the browser.

   Update the `/` route to return a HTML page that fetches the count value from the `/user-count` route you've implemented previously. Style the HTML so it displays in a visually pleasing way. Now you've created a nice page to view the total number of users in your database!

## 2. Practice using Postman

Who doesn't love dogs? Ok... save the cat vs dog debate until after you've completed this exercise!

You'll be using the Dog API, where you can retrieve lots of doggy pictures. You can find the documentation on their website [dog.ceo/dog-api](https://dog.ceo/dog-api/).

You should create a collection in Postman, and set up requests for each of these tasks:

1. Get 5 random dog images (any breed)
2. List all the dog breeds
3. Get 3 dog images from the "beagle" breed
4. List all the sub-breeds of the poodle
5. Get all the dog images from the "toy poodle" sub breed

Share the link to your saved Postman Collection as part of submitting this assignment.


# Intro to Frontend

Here you can find module content and assignments for the Intro to Frontend module.

| Week | Topic                                                                                                                   | Preparation                                                                   | Assignment                                                                  | Session Plan                                                                    |
| ---- | ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| 1.   | [The browser environment, DOM, event listeners and making requests](/course-content/foundation/intro-to-frontend/week1) | [Preparation](/course-content/foundation/intro-to-frontend/week1/preparation) | [Assignment](/course-content/foundation/intro-to-frontend/week1/assignment) | [Session Plan](/course-content/foundation/intro-to-frontend/week1/session-plan) |

## Learning goals

* [ ] Understand the browser environment
  * [ ] HTML vs CSS vs JS
  * [ ] Client vs server
  * [ ] Where is the script tag being loaded
* [ ] How to use the DOM to implement dynamic functionality
  * [ ] What is it and what do developers use the DOM for?
  * [ ] DOM manipulation
    * [ ] Get elements
    * [ ] Insert elements
    * [ ] Element manipulation (style, innerHTML, text)
    * [ ] Window object
    * [ ] Document object
* [ ] How to use Event Listeners to implement interactivity
  * [ ] Document onload
  * [ ] Click, submit, change, input - Focus on usage
* [ ] Displaying external data
  * [ ] Fetch (No promise explanation! Focus on usage)


# Week 1

## Learning goals

See [this module's learning goals](/course-content/foundation/intro-to-frontend#learning-goals).

## Relevant links

* [Preparation](/course-content/foundation/intro-to-frontend/week1/preparation)
* [Assignment](/course-content/foundation/intro-to-frontend/week1/assignment)
* [Session Plan](/course-content/foundation/intro-to-frontend/week1/session-plan)

## HTML interaction

Interacting with the HTML DOM is done through the document object in the browser. With the document object we can get html elements and change them.

For the next js part we use this html.

```html
<html>
  <body>
    <h1>Javascript week 3</h1>
    <div class="queue"></div>
    <div id="test-id"></div>
    <script src="js/review.js"></script>
  </body>
</html>
```

```js
// use the querySelector to select elements just like in css
const testIdElement = document.querySelector("#test-id");
console.log(testIdElement); // logs the html element with id "test-id"

// Change the inner html of the test-id element
testIdElement.innerHTML = "test";
// Change the background-color of the test-id element. Inline css changes is done via the style attribute on the element
testIdElement.style.backgroundColor = "blue";

// It is also possible to create html elements
// Create a div element
const div = document.createElement("div");
// Change its inner html
div.innerHTML = "We created this div!!!";

// Lest append it to the div with the class queue
const queueDiv = document.querySelector(".queue");
queueDiv.appendChild(div);
```

## Code Commenting

First the straightforward part: how do we place comments in our code?

### HTML

[W3Schools](https://www.w3schools.com/html/html_comments.asp) Comments

```html
<!-- Write
your comments here -->

<!-- Write your comments here -->
```

### CSS

[MDN on CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments)

```css
/* Comment */

/*
A comment
which stretches
over several
lines
*/
```

### JavaScript

Single line comments

```js
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
```

Single line comments at end of the line:

```js
const x = 5; // Declare x, give it the value of 5
```

Writing js documentation: [JSDoc](https://usejsdoc.org/)

### When to comment?

Now for the hard part: when to comment? When you work for different companies, you will see different styles. Embrace something you like, and then learn to let go. Google on "when to comment code?" and you'll find a big bunch of different opinions.

The general concept is, however, that it is there to help make the code more easy to understand. Note, however, that comments can also make code more difficult to understand when not applied properly.

## Events

Events in JavaScript are things like: A timer has just finished, a user clicked a button, our page has loaded, someone types into an input element or we have just gotten some data from a server. When these events happen, we usually want to add some functionality. For example, when a user clicks the "like" button (event), we want to increment the "like" counter, and color the "like" button blue. Or when someone clicks "Close cookies" (event) we want to remove the cookie div.

Let's first try to create some js that waits for 2 seconds and the console.logs out "2 seconds has elapsed!"

In JavaScript we use an *event listener* to listen:

```javascript
setTimeout(function () {
  console.log("2 seconds has elapsed!");
}, 2000);

// Cool, now let's make a function as a variable:
const fourSecondLog = function () {
  console.log("4 seconds has elapsed!");
};

setTimeout(fourSecondLog, 4000);
```

Now let's keep track of how many times a button is clicked. To do something whenever a button gets clicked, we use what is called an *event listener*.

Imagine that the button is noisy. There's someone listening out for the click sound, and every time they hear it, they add 1 to a counter.

```javascript
const buttonElement = document.querySelector("button");
let counter = 0;

buttonElement.addEventListener("click", function () {
  counter = counter + 1;
  console.log(`Button clicked ${counter} times so far`);
});
```

You might prefer to assign the event listener to a `const`, like this:

```javascript
const buttonElement = document.querySelector("button");
let counter = 0;

const buttonClicked = function () {
  counter = counter + 1;
  console.log(`Button clicked ${counter} times so far`);
};

buttonElement.addEventListener("click", buttonClicked);
```


# Preparation

* [Basic DOM manipulations (img src, innerHTML)](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/DOM_manipulation.md) (5 min)
* [Code Debugging Using the Browser](https://javascript.info/debugging-chrome) (5 min)
* [Code commenting](https://github.com/HackYourFuture/fundamentals/blob/master/fundamentals/code_commenting.md) (2 min)
* [Attaching an event](https://www.w3schools.com/jsref/met_element_addeventlistener.asp) (5 min)

*Please go through the material and come to the session prepared!*

## Flipped classroom videos

* [Executing Javascript in the browser environment](https://youtu.be/k8PEyCe3vK0)
* [Interacting with the DOM using Javascript](https://youtu.be/YvHQIaKtOl8)
* [DOM event listeners using Javascript](https://youtu.be/DwzApTvTngI)
* [Fetching data from API using fetch - Javascript](https://youtu.be/pL_zEzunBKU)


# Session Plan

* Browser environment
  * HTML vs CSS vs JS
  * Client vs server
  * Where is the script tag being loaded
  * Code debugging
* DOM
  * What is it and what do developers use the DOM for?
  * DOM manipulation
    * Get elements
    * Create elements
    * Insert elements - let trainees investigate `appendChild`, `insertBefore`
    * Element manipulation (`style`, `innerHTML`, `text`)
    * Document object
    * [Code inspiration simple](#dom)
    * [Code inspiration change logo](#change-logo)
    * Exercises: [Favourite dishes](#favourite-dishes), [podcasts](#podcast), [image inserter](#image-inserter)
* Event listeners - Focus on usage, no explanation of callback
  * Click, mouseover, etc. Explain one and let trainees investigate another, like mouseover or mousemove
  * Input Change, input
  * Event parameter
  * [Code inspiration](#event-listener)
  * [Exercise simple](#simple-event-listener)
  * [Exercise dark mode light mode](#light-mode-dark-mode)
* Fetch (No promise explanation! Focus on usage)
  * Focus on usage let the trainees copy the fetch script and use it from there. Promises are out of scope in this module.
  * [Code inspiration](#fetch)
  * [Exercise 1](#astronauts-in-space), [exercise 2](#dog-fan-website)

Really try in this session to do short teaching and lots of exercises!

## Flipped classroom videos

[Flipped classroom videos](/course-content/foundation/intro-to-frontend/week1/preparation#flipped-classroom-videos)

## Code inspiration

### DOM

```js
const eventElement = document.querySelector(".events");
eventElement.innerHTML = "Soccer training Wednesday";
eventElement.style.backgroundColor = "blue";
console.log(eventElement);

const div = document.createElement("div");
div.innerHTML = "new div";

const body = document.querySelector("body");
body.appendChild(div);
```

### Change logo

```js
function changeLogo() {
  let logo = document.getElementById("logo");
  logo.src =
    "https://assets.fontsinuse.com/static/use-media-items/15/14246/full-2048x768/56fc6e1d/Yahoo_Logo.png?resolution=0";

  let newTitle = document.createElement("h1");
  newTitle.innerHTML = "My new title"; // <h1>My new title</h1>

  document.body.appendChild(newTitle);
}

changeLogo();
```

### Event listener

```js
// change the event type
document.querySelector("button").addEventListener("click", function (event) {
  // what does the event do?
  console.log(event);
  body.style.backgroundColor = "red";
});
```

### Fetch

```js
fetch("https://yesno.wtf/api/")
  .then((response) => response.json())
  .then((yesOrNoData) => {
    console.log(yesOrNoData);
    // HERE IS WHERE YOU WRITE YOUR CODE!!!!!!!!
  });
```

## Exercises

### Favourite dishes

Create an array of strings with your favourite dishes.

With js select a `ul` in the DOM. You add the `ul` to the html file.

Now loop through each element of the favourite dishes array, you create an `li` element and set the text to the favourite dish.

Then append the `li` element to the `ul` element.

### Podcast

```js
const podcasts = [
  {
    name: "The mystery om of Johan Klausen Varbourg",
    imageUrl: "https://picsum.photos/536/354",
  },
  {
    name: "Tips about dogs with small legs",
    imageUrl: "https://picsum.photos/536/354",
  },
  {
    name: "You, me, we and us",
    imageUrl: "https://picsum.photos/536/354",
  },
  {
    name: "Breakfast news - Dinner edition",
  },
];
```

1. Create a `ul`
2. Loop through the podcasts
3. For every podcast:
   1. Create an `li`
   2. Create an `h1` element
   3. Change the innerHTML of the `h1` to equal the name of the current podcast
   4. Append the `h1` to the `li`
   5. Now add an image to the `li` with the `src` set to the `imageUrl`. But only if the `imageUrl` key exists on the object!
4. Append the `li` to the `ul`

### Image inserter

Create a function that has two parameters: `imageUrl` and `elementToAppendImageTo`. The function should create an img tag and set the `src` attribute of the img to the `imageUrl` parameter. The function should then append the `img` to the `elementToAppendImageTo` - html element.

```js
// Should append a img tag to the body with the picture from 'https://picsum.photos/536/354'
notThisFunctionName(
  "https://picsum.photos/536/354",
  document.querySelector("body"),
);
```

### Simple event listener

When clicking a button, change the text on the button to say "Button clicked"

### Light mode dark mode

Clicking a button should toggle the background color of the body and the text color in the page. If the background is white and the text is black, then clicking the button will make the background dark and the text white and vice versa

*Optional* also make the text on the button change.

### Astronauts in space

Use [this api](http://api.open-notify.org/astros.json) to fetch how many astronauts are currently in spaces.

Add the following text to the DOM, using the data about astronauts:

```
There are NUMBER_OF_ASTRONAUTS astronauts in space, they are:
ASTRONAUT_NAME1
ASTRONAUT_NAME2
ASTRONAUT_NAME3
ASTRONAUT_NAME4
ASTRONAUT_NAME5
```

An example with 2 astronauts could be:

```
There are 2 astronauts in space, they are:
Benjamin Hughes
Jørgen Pedersen
```

### Dog fan website

Let's create a site for dog lovers using this API: <https://dog.ceo/api/breeds/image/random>

1. Get a random dog image and display it in the browser
2. Get a new image every 2 sec.
3. Get the list of all breeds from <https://dog.ceo/api/breeds/list/all>
4. Display a random image of a breed from the list <https://dog.ceo/api/breed/[BREEDNAME]/images/random>
5. Display the name of the breed under the image


# Assignment

## So why this assignment?

**Interacting with the DOM is a crucial part** of building a web app. If we cannot interact with the DOM then the javascript we write cannot change what we see in the browser. **Connecting javascript to the browser opens up a new world of possibilities** where only the imagination is the limiting factor. These assignments will help you get a glimpse into what is possible.

## 1. Warm up

Complete these Katas on CodeWars:

* [8kyu Remove First and Last Character](https://www.codewars.com/kata/56bc28ad5bdaeb48760009b0)
* [8kyu Counting sheep...](https://www.codewars.com/kata/54edbc7200b811e956000556)
* [7kyu String ends with?](https://www.codewars.com/kata/51f2d1cafc9c0f745c00037d)
* [7kyu Odd or Even?](https://www.codewars.com/kata/5949481f86420f59480000e7)

Remember to submit a link to your profile as part of submitting this assignment.

## 2. Hogwarts House generator

In the Harry Potter series, every student of Hogwarts school is placed into a house (Gryffindor, Hufflepuff, Ravenclaw, or Slytherin).

Let's create a page where **a user writes their name** in an input element. The user then clicks a button. The user will now **receive a Hogwarts House**, e.g. "Benjamin belongs in Slytherin!"

### 2.1. Markup time!

Create an input element, a button and a tag to display the Hogwarts house into.

### 2.2. Setting up the events

When the user clicks the button, get the name the user wrote in the input field.

### 2.3. Choosing a house

Now we can get the users name, next step is to **add the Hogwarts house string** and display that with the users name in this format: "`Name` belongs in `House`!".

Store the houses in an array, and return a random one to be assigned to the user.

### 2.4. Trying again

If a user isn't happy with the house they ended up in, they should be able to try again. Make sure if the user wants to, they can click a button to try and get into a different house.

### 2.5. No input

What if the user clicks to get assigned a house, but they didn't supply their name? What's the best way to handle this situation?

### 2.6. New feature?

Think of a new feature or design to add to your generator, and implement it! Maybe a cool animation? Or a description of each house? Or some images to represent the houses? Or a beautifully styled UI?

## 3. hyfBay

You have been hired to build a simple app lightly inspired by eBay called hyfBay.

It should be a website where a user can search for a product. The products can also be filtered and sorted, depending on what the user is looking for.

### 3.1. Let's get started!

In your assignment repo, you will find a template to get started with:

* `main.js` - This is where you will be writing your JavaScript code.
* `hyfBayHelpers.js` - This defines a function called getAvailableProducts that you can use to get an array of products to display on your website.
* `index.html` - A basic html page that you can add some markup and styles to.

### 3.2. Requirements

You should implement the following functionality:

* The product list should be generated by calling a function called `renderProducts(products)`, that you will write.
* You should use the `getAvailableProducts` function to get a list of products to use.
* The list of products should be rendered as a html list.
* The product list items should contain `title`, `price` and `rating`

#### Tips

Feeling stuck? here's some tips on where to start:

1. Your HTML needs a `ul` element that can contain all the products. You can then select that `ul` using `document.querySelector` in JavaScript, and modify its contents.
2. To generate the content, for each `product` in the `products` array:
   1. [create an `li`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement)
   2. Set the innerHTML of that `li` to the contain the title, price and rating
   3. [Append the `li`](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild) to the `ul`


# Career Training

Welcome to your Career Sessions!

In this repository you can find all the info and material from your Career Sessions, what to prepare for each session and resources that can be used to support you and the community in finding a job in tech. The goal of this series of sessions is to optimally prepare you for the job hunt in Denmark's IT industry following your graduation from our program by helping you identify and communicate your specific competencies and skills.

## Contents

| Week | Topic                                                                                                                                                                                               | Preparation                                                                 | Session Plan                                                                                | Assignment                                                                |
| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| 1.   | [Jobhunting in Denmark](/course-content/foundation/career-training/week1). Introduction to the Danish job market, job search, and what a strong profile looks like, including your CV and LinkedIn. | [Preparation](/course-content/foundation/career-training/week1/preparation) | [Session Plan](/course-content/foundation/career-training/week1/session-plan) (for mentors) | [Assignment](/course-content/foundation/career-training/week1/assignment) |
| 2.   | [Mock Screening Interview](/course-content/foundation/career-training/week2). Practice the first part of the interview process and gain some feedback.                                              | [Preparation](/course-content/foundation/career-training/week2/preparation) | [Session Plan](/course-content/foundation/career-training/week2/session-plan) (for mentors) | (No assignment)                                                           |

## Module Learning Goals

By the end of this module, you will be able to:

* [ ] Understand where to look for suitable jobs and internships
* [ ] Understand what you should do in order to be an attractive candidate on the Danish job market
* [ ] Learn how to identify and communicate your competencies
* [ ] Understand what HYF can do to support you on your job hunt
* [ ] Know how to assemble an effective CV and LinkedIn profile
* [ ] Learn how to perform well in a screening interview


# Week 1

The session will provide an overview of the Danish job market and common expectations that guide local recruitment practices. It will outline key elements that characterize a strong candidate profile in Denmark, including clarity, reliability, and evidence of practical competence. In addition, it will address how a well developed CV and LinkedIn presence will collectively shape an applicant’s professional identity. Together these materials demonstrate both technical capability and professional maturity, offering recruiters a coherent and comprehensive view of the candidate’s qualifications and potential.

## Learning Goals

By the end of this session, you will be able to:

* [ ] Understand where to look for suitable jobs and internships.
* [ ] Understand what you should do in order to be an attractive candidate on the Danish job market.
* [ ] Learn how to identify and communicate your competencies.
* [ ] Understand what HYF can do to support you on your job hunt.
* [ ] Know how to assemble an effective CV.
* [ ] Know how to make your LinkedIn page attractive to recruiters.
* [ ] Identify how their CV and LinkedIn play together.
* [ ] Have an understanding about how recruiters review a CV and what they look for.
* [ ] Being able to critically review a CV and LinkedIn page and identify main errors and pitfalls.

## Materials

* [Preparation](/course-content/foundation/career-training/week1/preparation)
* [Session Plan](/course-content/foundation/career-training/week1/session-plan) (for mentors)
* [Assignment](/course-content/foundation/career-training/week1/assignment)


# Session Materials


# HYF CV Guide

![Header Image](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-304d7bf0b928e2e7106239c6042451377af235e9%2Fcv.png?alt=media)

Securing an interview requires a polished resume that highlights your work experience, qualifications, and technical skills. Your resume needs to effectively communicate that you have the skills and experience required for the position. As a web developer, you aren’t expected to be a graphic design expert, but a well designed resume can make a big difference. Most recruiters only spend a few seconds on their initial resume scan.

Writing the perfect resume is less about showing how great you are and more about showing the hiring person why you’re the ideal person to help them reach their goals. The key to doing this is being relevant and to the point. In this guide you will find a few important resume writing tips and resources to help you get started:

## 1. The Do’s & Don’ts of Resume Writing

You’ve likely heard conflicting statements of what you should and should not include in a resume. We’re clearing through the clutter with a list of do’s and don’ts to help you write a resume that will get you an interview, if not hired.

Keep in mind that the HYF team is always available to help you improve your CV. However, in order for us to do that, we expect you to read this guide and follow each and every step. Only then we can provide you with further support.

### DO

**- Pay attention to details:** This should go without saying, but a great resume is free of any typos and grammatical errors and looks slick. For typose, getting a friend to check can be helpful in spotting any errors you might have missed. We also love [grammarly for Chrome](https://www.grammarly.com) which is a tiny app that works as a digital writing assistant to support you create clear and effective communication! For design in general, be sure to have good contrast and clarity and make it pixel perfect as if it were a website. Your CV also tells the hiring manager or recruiter how much attention for detail you have and how you structure your content. Both crucial skills for a web developer!

**- Keep it concise:** A recruiter’s time is limited, so keep it focused and to the point. The ideal resume length should be one page for a printed resume, two pages if you have extensive relevant experience which is probably not the case when you come out fresh from our program so we strongly recommend you to stick to one page. Also, a resume is not a portfolio, and adding too many stylized details or too much information can make your resume design more distracting, taking away from the content itself. Try to stick with your biggest accomplishments, your most beautiful and challenging projects and avoid using over-the-top fonts, colors, and complicated layouts. Remember, sometimes less is more :)

**- Keep it up to date:** Your resume should include your most impressive projects and accomplishments. For that reason, we suggest updating your CV every time to create a new amazing project or take part in an internship. Keep in mind that the better the projects, the more chances you will have to be invited to take part in an interview.

**- Use a balance of interpersonal skills and technical skills:** It is important to include a mix of both technical skills (sometimes called "hard skills") and interpersonal skills (sometimes called "soft skills") on your resume, as when combined, they make you a highly desirable candidate. In many instances, interpersonal skills can help enrich your technical skills — for example, your Javascript skills will be supported by an ability to collaborate as a team, problem solve and meet deadlines.

**- Mention accomplishments and make it measurable:** In addition to your strengths and responsibilities in your resume, try backing them up with real work achievements. Focus on how that activity resulted in a positive difference for that employer, team or user. You should also try to quantify your accomplishments with numbers, providing context whenever possible

**- Write it in reverse chronological order:** Start with your most recent and relevant experiences and work your way through your previous job titles.

### DON’T

**- Exaggerate (or lie):** It could be tempting to ‘bend the truth’ a bit on your resume. Maybe you watched a video or did a short Python or Java course, so it might feel like a good idea to add it to your skillset. Do not do it. Do not (ever) use exaggerated information on your CV. Every fact you include on your resume should be supported by your past references, colleagues and most importantly, knowledge. Chances are you will be interviewed by someone with many more years of web development experience than you and interviewers usually zoom in on everything you put on your CV. Better to be interviewed with a simple CV and nailing your technical assignment, than having the interviewers create a lot of (unreal) expectations about your skills.

**- Add unnecessary details:** Employers are not interested in seeing 20 Udemy certifications, whether or not you have a driver's license, where you were born, if you are married or not or where exactly do you live (city is enough).

**- Use templates that are not flexible:** If you send the HYF team a PDF it is VERY hard and time consuming for us to provide you with feedback. Instead, please use google docs or (even better) stick to some of the great looking templates we share with you on this guide!

## 2. The Structure of a HYF Graduate’s CV

While there are no exact ways of doing a resume, there are some best practices we’ve seen have worked well for our graduates. Your CV needs to be professional looking and well-organized. It should also link to your GitHub and LinkedIn.

There are seven main sections you need to incorporate in your resume. Each one is critical and serves its own purpose when you're applying for an internship:

![CV Sections](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-abd72213f1707846edb062e80dc6af594c062905%2Fcv-sections.jpg?alt=media)

1. Your photo and contact information
2. Your BIO text
3. Your skills (technical and interpersonal)
4. Your experience (including your Final Project)
5. Your education (including HackYourFuture)
6. Your (additional) projects
7. Other information including languages and hobbies

Each of these sections should be clearly separated with easy to read headers. Let’s walk through some of these sections so you can better understand what to include.

### 1. Your Photo and contact information

Every CV should include your full name, your position (being full-stack, frontend or backend), your city and country, your email, your phone number, your GitHub (with a link) and your LinkedIn (also linked). Here you can also add your portfolio, if you have one.

While there are a lot of mixed thoughts about whether to include or not your (professional) picture, we strongly advise it.

### 2. Your Bio

Your CV Bio needs to be unique and captivate the reader. This is your opportunity to grab the attention of the recruiter and draw them into reading the rest of your resume. It should highlight what makes you stand out from the other people applying for the internship or job and call attention to who you are as a person and as a professional. Here some examples:

**Example 1:** Developer with a BSc in Electrical and Electronics Engineering and a MSc in Information Systems. After 4 years working as a Technical Specialist I had to leave Turkey seeking refugee status. Today I allocate all my energy to building a new future for me and my family by doing what I like the most: coding and solving problems. I'm a responsible and caring person that learns fast, likes to share, and takes work and personal growth seriously.

**Example 2:** Energetic Full Stack Web Developer ‘in love’ with JavaScript. For me, web development is more than just writing code. Is to communicate and work well with others in a team, to be curious and open to criticism and different approaches, to solve problems and to never stop learning. I'm currently looking for an opportunity to continue doing what I love, in a challenging but friendly environment.

**Example 3:** Avid learner, debate lover, and forever optimist. I like creating products that either have fun and nifty features or solve a genuine problem for people. I love creating products that have both of those things. Above all that, I love collaborating and working on a team! My hobbies include having several craft projects on the go at once, daydreaming about space, and eating snacks.

### 3. Your skills

This section enables recruiters to quickly scan your resume to see what programming languages, software frameworks, and databases you have experience with and to get an idea of how you are as a person. That’s why, we recommend adding a mix of both hard and soft skills.

You should only list the technical skills that you’re highly proficient in. Don’t list skills that you’re only familiar with as this may backfire once the interview rolls around. You could potentially lose credibility if an interviewer starts asking questions about a programming language you haven’t mastered.

HTML, CSS, Javascript, MySQL, Nodejs, Git and Reactjs are the most common ones after HackYourFuture. In some cases you can also add ExpressJS, Elastic Search, Firebase, KnexJS, Swagger, Storyboook, AWS or other skills that you have learned during your final project.

When it comes to interpersonal skills (soft skills), be sure to include only those 2, 3 or 4 that you are particularly good at and that you can back up with great examples during your interview. Some of these soft skills could include: Empathy, communication, teamwork, problem solving, grit, patience, open mindedness, accountability, creativity and time management. Read more about these [in this article](https://hackernoon.com/10-soft-skills-every-developer-needs-66f0cdcfd3f7).

### 4. Your experience (including your final project)

Besides adding the company name, your position and date (assuming that the experience is relevant) is good to include a short description of your function and your specific accomplishments or contributions.

Be sure to also include your final project in this section (with links to the deployed website, or [Feats page](https://www.feats.co/search?q=%22hackyourfuture%22)) as they are probably your most web development related experiences! Here some examples:

#### HackYourSocial at HackYourFuture | Jan 2022 | Link

Created a clean, and mobile-friendly web app using NodeJS, ReactJS, Redux and MongoDB to help travelers connect with each other and exchange tips. Implemented fetching of data through APIs and geolocation, authentication & authorization and client server model.

#### Kaospilot Toolbox at HackYourFuture | Jun 2023 | Link

Responsive Full-stack app developed for client Kaospilot using the MERN stack that allows users to search, filter and sort through a variety of facilitation tools developed by Kaospilot and other educational institutions, as well as user authentication and an admin console to add new tools.

### 5. Your education (including HackYourFuture)

The educational section of your resume is still an important aspect, however, you shouldn’t go into too much detail. The more experience you have, the less you need to focus on your education section. You need to list your school, college or university degree obtained, and dates you attended in your education section. As for your HackYourFuture Education, simply add a short description and links to the curriculum. Here some examples:

#### HackYourFuture, Frontend Development | Jan 2021 - Aug 2021 | [Curriculum](https://program.hackyourfuture.dk)

8-month program with modules on HTML, CSS, JavaScript and ReactJS.

#### Backend Development at HackYourFuture | Jan 2023 - Aug 2023

A 34-week course designed to cover all aspects of backend development including HTML, CSS, JavaScript, NodeJS, ExpressJS and MySQL. Check [the curriculum here](https://program.hackyourfuture.dk).

### 6. Your (additional) projects

Companies hiring interns from the HackYourFuture program know that you don’t have years of experience working as a web developer. However, they want to know you work hard, that you are eager to grow, that you have an eye for detail (especially if you want to be a frontend or full stack developer) and that you never stop learning. A way to show just that is by adding the most challenging and beautiful projects you’ve worked on during and after the program. Be sure to provide a link to the deployed version of the project and another link to the source code. Here some beautiful examples:

#### Weather app | Jan 2021 | [Demo](https://raw.githack.com/Nazeh/weather-app/master/dist/index.html) | [Source](https://github.com/Nazeh/weather-app)

Clean, and mobile-friendly web app built using plain JS, Webpack, and Babel. Implemented fetching of Open-weather, and geolocation data.

#### Todo app | Jan 2021 | [Demo](https://tv2z-app.herokuapp.com/) | [Source](https://github.com/salih18/MERN-Todo-App)

Simple (but great looking) to do app built with Reactjs, Nodejs and Expressjs allowing users to register and save their data, tag their activities and more.

#### YouTube UI Clone | Jan 2021 | [Demo](https://nazeh.github.io/youtube_video_player_page/) | [Source](https://github.com/Nazeh/youtube_video_player_page)

{% hint style="warning" %}
Be sure that the quality of the projects shared in this section are representative of your skills as a developer! Recruiters will judge your work, so be sure there projects show the best you can do! Needless to say, be also sure that each project follows the best practices on GitHub, like including a readme file, etc.
{% endhint %}

### 7. Other information including languages and hobbies

Give interviewers more information to get to know you better and have something else to talk about during the interview.

When it comes to languages, we suggest you add your native language and english of course, and if you know any other language such as dutch, highlight your level: Intermediate, basic, etc. Just like this:

> **Languages: English, Arabic, Danish (intermediate)**

In this case, we do not add native or proficiency to English or Spanish given that in this case Arabic is the applicant’s native language and English is simply expected to be at a working proficiency.

## 3. The HackYourFuture CV template pack

To make your job easier, we’ve created a set of templates with sections tailored to the needs of a HackYourFuture student. These templates can be mixed and matched together and you can also play around with style (typography and colors) to achieve a style and format that goes in line with your content and preferences.

[Check out the templates here](https://docs.google.com/presentation/d/1hcKvyIOLnXtDXqEu554_xaC7EzuRAPNTqYbIDMAvoQA/copy) and don’t forget to check the following video that explains how to repurpose the templates for your own use:

[![Templates Video](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-99bd4a5e5c31f12da482976e7b06bd0fcda9ce1b%2Fvideo.jpg?alt=media)](https://www.youtube.com/watch?v=DE28v--Zh58\&ab_channel=FedericoFusco)

## 4. Submitting your CV to the HYF team

Once your CV is ready, set the editing rights in Google Slides to "Anyone with the link":

![Sharing Permissions](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-3bf168ea41ff3de049b8d53a0e03df8765a840d3%2Fpermission.gif?alt=media)

And then submit the URL to the HYF team via Slack. We will then give you feedback (if needed) to be sure you end with a good CV that gets you interviews.

{% hint style="info" %}

### IMPORTANT

Once you submitted your CV, please be sure to ***continue to update it in the same file*** with new projects and experiences. That way we can be sure that every time you need feedback we can work from an up-to-date version.
{% endhint %}

{% hint style="info" %}

### EVEN MORE IMPORTANT

During and after HackYourFuture, it is crucial that you keep us informed with your progress and what you are up to. Also know that the HYF team is always available to connect with your case worker or contact person in the Kommune or at your Job Center, if necessary. If so, just reach out to us on Slack!
{% endhint %}


# Preparation

## Do

### Respond to survey

Fill out the "Career Status" survey posted in your teams' Slack channel.

## Read

### Hard vs Soft Skills

The differences between Soft Skills and Hard Skills - and why both are important.

Soft skills refer to interpersonal, cognitive, and behavioral attributes such as communication, teamwork, adaptability, and problem solving. Hard skills involve the technical competencies and domain specific knowledge required to perform job related tasks, for example proficiency in programming languages, data analysis techniques, or system architecture.

1. [Asana: Hard Skills vs. Soft Skills](https://asana.com/resources/hard-skills-vs-soft-skills)
2. [EdgePoint: Hard Skills vs. Soft Skills](https://www.edgepointlearning.com/blog/hard-skills-vs-soft-skills/)

### Writing your CV

1. [How to write a your profile text for your CV](https://www.prospects.ac.uk/careers-advice/cvs-and-cover-letters/writing-a-personal-statement-for-your-cv)
2. [IDA’s Guide to CV’s in the Danish Job Market](https://english.ida.dk/cv)

### Working in Denmark

1. [Read about what a Union is in Denmark](https://www.workindenmark.dk/working-in-denmark/terms-of-employment/trade-unions)
2. [Read about what an A-Kasse is](https://www.workindenmark.dk/working-in-denmark/terms-of-employment/unemployment-insurance) (Unemployment insurance in Denmark)
3. [Read about what to expect from a Employment contract in Denmark](https://lifeindenmark.borger.dk/working/work-rights/working-conditions/employment-contracts)

### Danish work culture

1. [Danish Workplace Culture – 8 Essentials to Denmark’s Balanced Worklife](https://swaplanguage.com/blog/understanding-danish-workplace-culture/)
2. Compare your own culture(s) with Danish culture by using the [Country Comparison tool](https://www.theculturefactor.com/country-comparison-tool).
   * Pay attention to and write down any surprises or observations you find in your comparison. Bring a few examples to the session.


# Session Plan

## Session Goal

Equip trainees with a realistic understanding of the job search process and what is expected beyond technical proficiency. Clarify how HYF can support them, and where its boundaries lie. Set the foundation for professional self-presentation and awareness of the Danish job market structure.

Guide trainees to understand how their CV and LinkedIn profile should work in harmony to present a complete and professional image to recruiters. Provide tools, examples, and hands-on practice in critiquing and improving their online presence.

## Your Preparation (Before Session)

### 1. Familiarize Yourself with Materials

Thoroughly read the [same preparation](/course-content/foundation/career-training/week1/preparation) as the trainees.

### 2. Review Responses to the "Career Status" Survey

Before the session, check submissions in the team Slack channel or [survey tool](https://docs.google.com/forms/d/1paMG5mM5FfpXHvRYnz4FLFHhGJF6xwKgfztY2Kw90CY/edit).

Use these responses to:

* Tailor examples to trainees situations
* Identify trainees needing more support
* Initiate relevant 1-on-1 conversations

### 3. Prepare Slide Deck

Include:

1. Summary of key soft vs. hard skills
2. Overview of Danish employment structures (Union, A-Kasse, Contracts)
3. Highlights and characteristics of Danish workplace culture and society.
4. [Slide deck example can be found here](https://docs.google.com/presentation/d/1sYaWbvFmylrLv5AnWPsL4dbuj6Ifl1ufwTGJeqWXZqY/edit?usp=drive_link).

### 4. Set Expectations Clearly

Be ready to clarify:

* What HYF can support (mentorship, feedback, referrals, skill-building)
* What HYF cannot do (guarantee job placement, write applications for trainees, legal employment advice)


# Assignment

## Update your CV and LinkedIn

1. Read the [HYF CV Guide](/course-content/foundation/career-training/week1/session-materials/cv-guide)
2. Add your current email address, LinkedIn profile and GitHub profile to your Slack profile
3. Polish and update your LinkedIn ([example 1](https://www.linkedin.com/in/alex-sudar/), [example 2](https://www.linkedin.com/in/remyamm/), [example 3](https://www.linkedin.com/in/saloumehsarabi/), [example 4](https://www.linkedin.com/in/anna-louise-jensen-559a89177/))
4. Write a short profile text about yourself - about 400-500 characters and add it to your CV.
5. Update your current CV fully - all professional experience as well as soft and hard skills.
6. Canva has [thousands of free and GOOD CV templates](https://www.canva.com/resumes/templates/) - find and use one that you like.
7. Make sure your make an ATS compatible/compliant CV - there are many free ATS CV checkers online.'


# Week 2

This session is for practicing for a screening interview and receiving feedback from peers and volunteers.

You've made a lot of progress on your CVs and LinkedIn profiles so far, and now you get the opportunity to practice a screening interview. Watch out in your teams' slack channel, where you will receive a case to prepare for.

We will also bring a camera so that you can get updated photos for your LinkedIn and CV - so wear the clothing you would like to have on your professional profile!

## Learning Goals

By the end of this session, you will be able to:

* [ ] Give a personal elevator pitch clearly and confidently
* [ ] Learn how to perform well in a screening interview
* [ ] Understand and practice asking your own questions during the interview
* [ ] Practice receiving constructive feedback
* [ ] How to handle job rejection and job anxiety
* [ ] Feel prepared and ready to take on a real interview

## Materials

* [Preparation](/course-content/foundation/career-training/week2/preparation)
* [Session Plan](/course-content/foundation/career-training/week2/session-plan) (for mentors)
* There is no assignment for this session


# Preparation

## Read

1. Understand the purpose of a screening interview.

   A screening interview serves as an initial assessment that helps employers determine whether a candidate possesses the foundational skills, professional disposition, and communication abilities required for further consideration in the hiring process. It allows interviewers to verify key qualifications, explore general behavioral tendencies, and gauge overall alignment with the role and organizational culture. This early conversation streamlines the selection process by identifying strong potential matches while ensuring that subsequent stages focus on candidates who demonstrate both capability and suitability.
2. What is the ["STAR" answer format](https://novoresume.com/career-blog/interview-star-method)?
3. [Read about the elevator pitch](https://www.indeed.com/career-advice/interviewing/how-to-give-an-elevator-pitch-examples)

## Do

1. Prepare your own elevator pitch
2. Prepare questions for the interview: At the end of the interview, asking thoughtful questions demonstrates interest, engagement and can make a great impression. Prepare your own list of questions. Use this examples for inspiration, if needed:
   * Based on our discussion, what value do you feel I could bring to the team?
   * Are there any gaps in my experience that you are concerned about?
   * What are the next steps and when should I be expecting to hear from you?
   * What is the tech stack of your company?
   * What do the internal processes at your company look like? (workflow, growth plan, onboarding plan)
   * What is the team composition? (the team you are interviewing for)
   * What is the most important trait of the position?
   * Questions that matter to you (depends on your personal circumstances, maybe you would like to work remotely, maybe you would like to have a mentor, etc.)


# Session Plan

This session is focused on realistic screening interviews, peer feedback, and volunteer involvement. Trainees present themselves with an elevator pitch, and give answers based on a case that they’ve been preparing for over the prior 2.5 days.

## Session Goal

Create a realistic but supportive interview environment where trainees can:

1. Practice giving their elevator pitch clearly and confidently
2. Gain actionable feedback on both technical and soft skills
3. Improve their readiness for real interviews

Key message to reinforce: “It’s not about having the perfect experience - it’s about clearly explaining your skills, competencies and potential in the role.”

## Session Outline

A screening interview serves as an initial assessment that helps employers determine whether a candidate possesses the foundational skills, professional disposition, and communication abilities required for further consideration in the hiring process. It allows interviewers to verify key qualifications, explore general behavioral tendencies, and gauge overall alignment with the role and organizational culture. This early conversation streamlines the selection process by identifying strong potential matches while ensuring that subsequent stages focus on candidates who demonstrate both capability and suitability.

## During the Interview

1. Observe how clearly the candidate explains past experiences and technical concepts
2. Note whether responses are structured, coherent, and appropriately detailed
3. Assess the candidate’s ability to stay focused on the question without unnecessary distractions
4. Evaluate the candidate’s listening skills and how accurately they respond to prompts
5. Consider the candidate’s level of professionalism in tone, pace, and choice of language
6. Watch for signs of confidence and composure when addressing unfamiliar or challenging questions
7. Assess how well the candidate adapts explanations for different audiences and levels of expertise

### Examples of questions to ask

1. Can you describe a situation where you adapted to a significant change in project requirements and explain how you managed the transition?
2. How do you respond when you realize you have made an error in your work, and what steps do you take to correct it?
3. Can you share an example of how you handle conflict within a team, particularly when opinions differ about a technical decision?
4. How do you maintain focus and motivation during long or complex development cycles?
5. Can you describe a time when you supported a colleague who was struggling with a task and explain what you did to assist them?
6. How do you approach constructive criticism in a code review or technical discussion, and how do you incorporate the feedback?
7. Can you discuss a moment when you took initiative to solve a problem before it became a larger issue?
8. How do you stay organized when managing multiple tasks or priorities, and can you share a recent example?
9. Can you describe a time when you had to make a difficult decision without having all the information you wanted?
10. How do you maintain effective communication with teammates who have different working styles or levels of experience?
11. Can you talk about a moment when you demonstrated resilience during a challenging project?
12. How do you approach mentorship, whether you are guiding a colleague or seeking guidance yourself?
13. Can you describe a situation where you balanced your own preferred solution with the broader needs of the team?
14. How do you ensure that your personal work habits contribute positively to team culture and project outcomes?
15. Can you reflect on a time when you identified an opportunity to improve a workflow and explain how you encouraged others to adopt the change?


# Intro to Agile

This module aims to introduce you to the basic principles of managing a project well and collaborating with others on tasks. Most of these concepts come from the software development world, but they inform good practices that you can use across many different types of jobs and teams.

## Planning

| Week | Topic                                   | Preparation                                                                 | Assignment                                                                | Session Plan                                                                  |
| ---- | --------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| 1.   | Project management & team collaboration | [Preparation](/course-content/foundation/intro-to-agile/week-1/preparation) | [Assignment](/course-content/foundation/intro-to-agile/week-1/assignment) | [Session Plan](/course-content/foundation/intro-to-agile/week-1/session-plan) |

## Learning Goals

* [ ] What is project management and why is it important
* [ ] Understand the main principles and values of Agile
* [ ] Understand the very basics of Scrum
* [ ] Understand how to use a simple tool to manage tasks, backlog, a board, and a simple project workflow
* [ ] Be able to apply basic prioritisation using MoSCoW
* [ ] Feel equipped to apply basic task and project organisation in your next project (e.g. final project)

## Prerequisites

* Basic understanding of what a web development project involves (e.g. frontend/backend tasks).
* Experience working on a group project (from HYF or elsewhere).
* Familiarity with Git/GitHub workflows.


# Week 1


# Preparation

## Introduction to Agile

### Part 1: Introduction to Agile and Waterfall

#### What is Waterfall?

Waterfall is a **sequential software development model**: Requirements, Design, Implementation, Verification, Maintenance.

**Pros:**

* Predictable
* Good for fixed requirements
* Suitable for some large-scale production such as manufacturing, rocket launching etc.

**Cons:**

* Late feedback
* High cost of change
* Misalignment risk

#### Why Agile Emerged

Agile was created in response to Waterfall's rigidity. The **Agile Manifesto (2001)** values:

1. Individuals and interactions over processes and tools
2. Working software over comprehensive documentation
3. Customer collaboration over contract negotiation
4. Responding to change over following a plan

#### Agile vs. Waterfall

| Aspect               | Waterfall  | Agile       |
| -------------------- | ---------- | ----------- |
| Structure            | Sequential | Iterative   |
| Change Handling      | Rigid      | Flexible    |
| Customer Involvement | Limited    | Continuous  |
| Testing              | At the end | Ongoing     |
| Delivery             | Big-bang   | Incremental |

**Key Takeaway:** Agile is not a methodology — it's a **mindset** focused on value, learning, and adaptability.

### Part 2: Basics of Scrum

#### What is Scrum?

Scrum is a lightweight framework used by 87% of Agile teams (2024). It is based on empirical process control and supports frequent delivery, learning, and feedback.

#### Scrum Principles

* **Empiricism** — Transparency, Inspection, Adaptation
* **Self-management** — Teams decide how to work
* **Cross-functionality** — Team has all skills needed
* **Iterative Progress** — Frequent increments to inspect and adapt

#### Scrum Roles

| Role          | Responsibilities                                    |
| ------------- | --------------------------------------------------- |
| Product Owner | Maximizes value, owns the Product Backlog           |
| Scrum Master  | Coaches, facilitates, removes impediments           |
| Developers    | Cross-functional professionals building the product |

#### Scrum Events

| Event                | Purpose                                              |
| -------------------- | ---------------------------------------------------- |
| Sprint               | Time-boxed iteration (max 1 month)                   |
| Sprint Planning      | Define Sprint Goal, select work, plan delivery       |
| Daily Scrum          | 15-min sync for progress and re-planning             |
| Sprint Review        | Present Increment, gather feedback                   |
| Sprint Retrospective | Reflect and improve team collaboration and processes |

#### Scrum Artifacts

| Artifact        | Description                                              |
| --------------- | -------------------------------------------------------- |
| Product Backlog | Ordered list of everything needed in the product         |
| Sprint Backlog  | Selected work for Sprint + delivery plan                 |
| Increment       | Working product output that meets the Definition of Done |

**Definition of Done (DoD):** Shared understanding of “complete,” enforced by Developers, ensures transparency and consistency.

**Key Takeaway:** Scrum gives structure to Agile — it’s simple, but powerful when practiced with discipline and empathy.

### Scrum Master vs. Project Manager

#### Scrum Master

The Scrum Master is a facilitator and coach for the Agile team. Their primary role is to support the team in following Scrum principles, ensure that Scrum events (like Daily Standups, Sprint Planning, and Retrospectives) run smoothly, and help remove any impediments that block progress. They don’t manage the team or assign tasks. Instead, they enable the team to self-organize, collaborate, and continuously improve. The Scrum Master also works closely with the Product Owner to maintain focus on delivering value.

#### Project Manager

A Project Manager is traditionally responsible for the overall planning, execution, and delivery of a project. This includes defining scope, creating schedules, managing budgets, assigning tasks, and ensuring that the project is completed on time and within budget. They typically operate in more structured or Waterfall environments, where they lead and direct the team’s work based on pre-defined plans.

#### Main Difference

The key distinction lies in their approach and authority. The Scrum Master supports a self-managing Agile team without directing them, while the Project Manager takes ownership of the entire project lifecycle and actively directs team tasks. Scrum Masters focus on process and team empowerment. Project Managers focus on control, coordination, and delivery.


# Session Plan

## Session Outline

1. Lost at sea
2. What is project management?
3. What is Agile (basic principles and values)?
4. Basics of Scrum
5. Simple project setup
6. Simple prioritisation

**Note:** This module is in Foundation, which means trainees are not becoming specialized developers yet. The above topics should be kept high-level, focusing on the principles rather than deeper details. For example, it's good to explain that a principle of Scrum is that decisions are made based on data, but there is no need to go into the depths of calculating velocity and burndown charts at this point. These full details should be covered more in the specialization courses.

***

## Exercise: Lost at Sea

**Purpose:** Experience working under pressure, dealing with sudden change, and making group decisions under stress.

**Time:** 45 minutes total

### The Scenario

You have won the lottery! To celebrate, you decide to take three or four teammates on a fancy holiday. For that you've chartered a yacht, sailing together across the Atlantic Ocean. Since none of you have sailing experience, you hired an experienced captain and two crew members.

Unfortunately, in the middle of the Atlantic, a violent fire breaks out in the ship's galley. The captain and crew disappear. Most of the yacht has been destroyed and the boat is slowly sinking.

Your location is unclear, after all you were busy partying, and the navigation tools and radio were damaged in the fire. Your best estimate is that you may be several hundred kilometers from the nearest beach to land.

You and your friends managed to save 15 undamaged items after the fire. You also saved a four or five-person lifeboat and a box of matches.

**Your task:** Rank the 15 items in order of importance for your survival while waiting to be rescued.

Use this link to order items: [Lost at Sea](https://lost-at-sea.netlify.app/)

> \[!TIP] If the link doesn't work, read the file [lost-at-sea.md](https://github.com/HackYourFuture-CPH/program/tree/main/courses/foundation/intro-to-agile/week1/session-materials/lost-at-sea.md).

### The 15 Items

* A sextant
* A small mirror
* A mosquito net
* A 25-liter container of drinking water
* A case of army rations
* Maps of the Atlantic Ocean
* A floating seat cushion
* A 10-liter can of oil and fuel mixture
* A small transistor radio
* 2m² of opaque plastic tarp
* A box of shark repellent
* A bottle of rum (80% alcohol)
* 500 meters of nylon rope
* 2 boxes of chocolate bars
* A fishing kit with rod

{% hint style="danger" %}
**🔒 FACILITATOR GUIDE - TRAINEES: STOP HERE**

The section below contains facilitation instructions and strategy. If you are a trainee, do not read further - complete the exercise first!

### Stage 1: Individual Ranking (10 minutes)

Have trainees work individually to rank all 15 items from 1 (most important) to 15 (least important).

**Script:** "You have 10 minutes to work individually. Read through the scenario and the list of items carefully. Then rank them from 1-15 in order of importance for survival. Write your answers down."

**Facilitation tips:**

* Circulate but don't give hints
* Ensure everyone understands they need to rank ALL 15 items
* No ties allowed - every item must have a unique ranking
* If everyone is done before the time limit move to the next stage to save time.

### Stage 2: Team Discussion (15 minutes, but announced as 30)

1. Divide trainees into groups of 3-4 people
2. Have them produce a single ranking of the items per group.
3. **Announce 30 minutes** for discussion (this is intentional - you will change it!)
4. Emphasize unanimous decision is required
5. Start timer

**Script:** "Now you'll work in teams of 3-4 people. You have **30 minutes** to discuss and agree on a single team ranking. You must reach a **unanimous decision** - everyone must agree. Write your team's ranking down."

#### ⚡ THE TIME PRESSURE TRICK

**CRITICAL - After exactly 10 minutes of team discussion:**

Interrupt loudly and urgently:

**Script:** "STOP! I need to interrupt you - It appears to be that the fire got more violent . You actually only have **5 more minutes** to finish and make your final decision. You need to agree NOW or your team has failed the exercise. Continue!"

**What to observe during these 3 minutes:**

* How are decisions made?
* Do quieter members get overruled in the rush?
* Do teams make quick, forced decisions without real consensus?
* Does anyone question or push back on the time change?
* How does communication style change under sudden pressure?

**Important:** This sudden change is intentional and is the core learning moment. Don't reveal this beforehand!

### Stage 3: Reveal Solution & Debrief (10 minutes)

At this stage check the answers from the teams and compare it with the Expert ranking.

1. Go to [Check answers per team](https://lost-at-sea.netlify.app/answer_check)
2. Fill in number of teams
3. Ask each team to provide their answers
4. Check the results and show their chance to be found by rescue team :D

#### Lead Discussion

You can use some of these questions (or statements) to debrief the exercise and connect to Agile:

**About the Time Pressure:**

* What happened when we suddenly changed the time limit?
* How did your team respond to that change?
* Did anyone feel stressed or frustrated? Why?
* Did the quality of your decision-making change under pressure?
* Did communication styles change? How?

**About Decision-Making:**

* Was it difficult to reach unanimous agreement?
* What led to disagreements in your team?
* Did everyone's voice get heard equally, especially under time pressure?
* Did some people dominate the conversation?
* How did your team resolve conflicting opinions?

**About Team Performance:**

* Did your team score better or worse than individual scores?
* Was working as a team better or worse than working alone? Why?
* What characteristics make a team succeed under pressure?
* What would you do differently if you could do this exercise again?

**Connection to Agile (MOST IMPORTANT):**

* In real projects, requirements change suddenly, just like the time limit changed without warning
* Teams need to adapt quickly and communicate clearly under pressure
* Unanimous agreement isn't always possible, sometimes you need to make a decision and move forward

**Reflection Questions:**

* How well did you "respond to change"?
* What parallels do you see between this exercise and real software development?
  {% endhint %}

***

## What is project management?

We organise projects to help provide some structure for a group of people to achieve some shared goal by working together.

Project management describes different best practices and approaches we can take to organising some work to avoid wasting time, effort, resources, money, and most importantly end up building the thing we started out to achieve.

Imagine you're about to go on a hike with a group of friends. Project management means you have a map and a plan before you set off, and to help you as you go on. You need to know:

* What path you'll take around the mountain
* What your end destination is
* How you'll get there
* What you need to pack
* Who will carry what along the way

Without project management, even a clever bunch of people can go in the wrong direction, duplicate work, miss deadlines, or build entirely the wrong thing.

Good project management keeps everyone aligned, on the same page, tackles problems early, and gives everyone the best chance of achieving the shared goal together.

## What is Agile

In project management, it's easy to go overboard. Planning every tiny detail of every project up front before actually getting started. This approach is often referred to as Waterfall, since you must complete each step of a project before moving onto the next (e.g. planning, designing, building, testing, delivery). In reality, projects rarely work that way. Lots of details change as you go, as you learn more of how something should work or look. And it's rarely a good idea to leave testing until you've finished building everything!

Agile is a way of working that was born out of a frustration with traditional project management (that followed the Waterfall mentality).

Agile aims to help teams build things in small steps, learn as they go, and adapt when things change. At its core, Agile is about people, collaboration, and delivering value early and often. It helps you avoid following strict processes or writing long plans up front.

Imagine you're steering a boat over a huge ocean. You can't know exactly how the weather will be, so you can't make an accurate plan for the whole journey. Instead, you keep moving forward, regularly checking the weather, your direction, and adjusting your course as needed. This is the Agile approach!

### The 4 Agile principles

Agile was formalised in the Agile Manifesto in 2001 by these core principles, and they are still valued today.

1. Individuals and interactions over processes and tools

Great teamwork and communication matter more than having the “perfect” tool or following every process step.

2. Working software over comprehensive documentation

The most important thing is to deliver something that actually works, and avoid spending too much time writing lots of plans.

3. Customer collaboration over contract negotiation

Working closely with customers throughout the project is more important than delivering just what they agree on at the start.

4. Responding to change over following a plan

Plans are useful, but things change. Be open minded to new ideas, feedback and issues that arise, rather than stubbornly sticking to a plan.

### Exercise: Draw a Rocket

Purpose: Demonstrate the difference between a waterfall and agile approach, showing how feedback and iteration improve results.

Time: 10 minutes

How it works:

1. Ask for a volunteer to be the "customer" and ask for a rocket to be drawn
2. In Waterfall style: The "artist" (mentor) draws a rocket without showing the customer until it's finished. The requester gives feedback of what they like/don't like at the end.
3. In Agile style: The "artist" (mentor) shows progress as they go (first the body, nose tip, wings, windows, flames etc.), asking questions and getting feedback during each step.

Compare the results. The Agile version should fit the customer's vision a lot more closely. Discuss what happened, which turned out better and why.

## Basics of Scrum

Agile is a useful mindset, but it doesn't actually give you any clear instructions on how to run a project. That's where Scrum comes in.

Think of Agile like the philosophy of healthy eating, and Scrum is a specific diet plan to achieve it.

Scrum is defined by some principles, specific roles, specific meetings and "artifacts". We will only go over the basics here, for what you'll need to understand to run your own first project.

### The Sprint

A sprint is a short, fixed period of time (usually 1–4 weeks) where a team focuses on completing a small, specific set of tasks that work towards a bigger goal. The outcome from a sprint should be a working version of the software - in other words, you should aim to finish something specific!

### The Backlog

This contains a list of tasks that you need to complete as part of the project. It is split into two parts, the "product backlog" which contains the full list of tasks, and then a "sprint backlog" which contains the list of tasks that you plan to work on in the next sprint.

## Simple project setup

Let's see what a basic Scrum project might look like in real life!

What we need:

1. A place to define tasks
2. A list of tasks to complete
3. A way to visualise them, so we can see their status

### Demonstration

Walk through the process of setting up a new board on Trello. Make sure to include:

1. A product backlog
2. A sprint backlog
3. In progress and Done columns, too
4. An example task
5. Visually demonstrate how the task moves through the board

It should look something like this: ![Trello Example Basic](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-8e54a10fbc2150384c9009037a95fb4e87d9cd21%2Ftrello-example-basic.png?alt=media)

### Exercise: Setting up Trello

Purpose: To practice setting up a project from scratch

Time: 10 minutes

Trainees should now register and set up their own Trello board. It should mirror what has already been demo'd in the session.

We'll now plan your next birthday party! Add the following tasks to the product backlog:

* Buy decorations
* Order the birthday cake
* Send out invitations
* Book the venue
* Choose and buy party snacks
* Plan the playlist / music
* Plan the date

Notice anything? They order doesn't seem to make sense!

## Prioritising tasks

If you plan of all the tasks you need to complete in a specific project, the list could be very long! And it can be hard to work out where to start.

There are many techniques you can use to help ordering the tasks into a prioritised list. We'll start simple with a method called Now/Next/Later:

* **Now**: We need to do these first.
* **Next**: These are also important, so we'll come to them shortly.
* **Later**: These could be good ideas, but they're not important right now.

How will we visualise that on the board? There is no right answer, as long as it's clear. But here is one way to do it: ![Trello Example Prioritisation](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-8dd161e2d3aff598cb6fe71711f971607d32f4b4%2Ftrello-example-prioritisation.png?alt=media)

### Exercise: Prioritising birthday tasks

Purpose: Practice prioritising a list of tasks using Now/Next/Later.

Time: 10 minutes

With the person next to you, go through the birthday party tasks, and decide which ones should fit into which category. Order your product backlogs so the Now tasks are at the top, followed by the Next, and finally at the bottom the Later tasks.

Finally, get ready to start your first sprint. Move all of the Now tasks into your sprint backlog!

Discuss the order and any differences between people's decisions in the whole group.


# Assignment

Now it's time to practice planning a project and prioritising tasks on your own!

## Instructions

1. Imagine you are building a new personal portfolio website. Think about the kinds of set up, features, content etc. that would be required to bring it to life.
2. Create a new Trello board using [the same columns as you did in the session exercise](/course-content/foundation/intro-to-agile/week-1/session-plan#prioritising-tasks) and brainstorm a list of at least 10 tasks to implement the projet.
3. Prioritise each task into the **Now**, **Next** and **Later** columns and order the tasks accordingly.

## Tips

* You're only *planning* a project here, so expect the "In Progress" and "Done" columns to be empty for now.
* There's no right answer for e.g. how many tasks you prioritise into the first sprint, but check out these guiding tips to stay on the right track:
  * **Now** - Tasks to complete in the first sprint (e.g. first week). These will likely be set up tasks and end in the first working version of your portfolio.
  * **Next** - Tasks to complete in the next sprint (e.g. next week). These will likely be adding/finishing the main features of your portfolio.
  * **Later** - Tasks to be prioritised at a later date (e.g. some time in the future). These could be optional ideas, improvements or new features to explore later.

## Submission

Submit your assignment as a PR as usual. Add your board's public link to a simple text or markdown file.


# Foundation Project

Welcome to your final project! Here you can learn more about the goals and requirements of this final module.

## Learning Goals

* [ ] Practice working in a team on the same project
* [ ] Develop self-guided learning skills (i.e. finding answers to your own problems)
* [ ] Practice building a project from a brief
* [ ] Practice interpreting requirements and making assumptions
* [ ] Developing your own additional requirements (i.e. adding your own flair to the project)
* [ ] Practice breaking big problems down into smaller tasks
* [ ] Managing your own tasks within a tight deadline
* [ ] Understanding how and when to ask for help at the right time
* [ ] Taking a project from idea to completion, including deploying it to the web

## Technical Requirements

### Frontend

* [ ] Design and implement layout using HTML and CSS
* [ ] Use DOM manipulation to introduce interactive elements
* [ ] Use JavaScript functions, types and loops and more to implement features
* [ ] Use GET requests to bring content and data into your app

### Backend

* [ ] Implement an API to return data to the frontend
* [ ] Use Postman to test your API
* [ ] Design a data schema to store data for your app
* [ ] Create a database table with usable data

## Organisational Requirements

* [ ] Work as a pair (two trainees) to complete the project together
* [ ] Use Trello to organise your project and visualise your progress
* [ ] Define your tasks with Trello cards
* [ ] Prioritise your tasks using MoSCoW so you know what to work on first
* [ ] Organise your tasks into weekly sprints
* [ ] Submit pull request(s) each week for each milestone in the project brief

## Projects

See the [Project Brief](/course-content/foundation/final-project/project-brief).


# Project Brief

You joined an online game platform startup and your task is to build a game that people can play in their browser.

It will be based on the classic Memory Game, where a player needs to flip all the cards in a grid until they find all the matching pairs. You aspire to make the game smooth and pleasant, so they have fun and keep playing it.

> \[!NOTE] Take some time to research online for similar games and how they look and work to gain inspiration. This is an important skill to practice because you won't always know (or be told) how to approach a new task.

## Requirements

Here are the features and details of the the app that need to be implemented. They have been listed in an order that might be useful to follow, but feel free to tackle the steps in the order that you see best fit.

You are strongly encouraged to add your own features, details, design and flare throughout the steps, as long as these requirements are still met.

### Week 1 Milestone

#### The Flippable Card

You are provided with a card picture and a card backside image which you can use, [which you can find here](/course-content/foundation/final-project/project-brief/card), or feel free to choose your own.

Your app needs to:

* [ ] Display a card
* [ ] Flip the card on click, showing the backside pattern to the picture and vice versa.
* [ ] Animate the flip

It can look and be animated in any way you like, but here's some inspiration: ![screenshot](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-df22983d1f582950dc5a2d731afc895554ab8ade%2Fmemory-game-card-flip.gif?alt=media)

#### The Card Grid

Next, you need to set up the cards in a grid, so they are displayed in a way suitable for the game to be played. You'll need some more pictures now!

* [ ] Display a grid of unique pairs of cards in a random order
* [ ] It should be at least 3x3, but a bigger grid is up to you

Tips:

1. You'll want to use an object to store the card details, such as an id, name, picture and more.
2. You'll need to store multiple of these objects, and then traverse through them to display them in a grid.
3. Each unique card will need to appear twice in the grid in a random order - think about *doubling* and *shuffling* your array to achieve this.
4. Make sure all the cards are still flippable and animate as you implemented in the first step!

Here's some inspiration: ![screenshot](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-236b0f3fddd5bda303704b2fbbbff886c6eef7f4%2Fmemory-game-grid.png?alt=media)

#### Counters and Timers

Now you need to add some of the core game functionality:

* [ ] Display a counter that shows how many times the player has *revealed* a card.
* [ ] Display a timer should start from when the player clicks their first card.
* [ ] Once two cards are flipped, they should stay flipped for X seconds, after of which they flip back down automatically.

Tips:

1. Revealing a card is not the same as a click! Your counter should incrememt with reveals.

#### Storing and Retrieving Your Cards

Up until now, your cards have been hardcoded in your app code. Instead, these should be stored in a database and fetched via an API which the frontend can use to retrieve and display them.

* [ ] Design a database schema that can store your cards
* [ ] Create your database and add some cards
* [ ] Implement a route in your backend that returns all of the cards from the database
* [ ] Refactor your frontend code to fetch the cards via your new API, and replace your hardcoded cards

Tips:

1. After these changes, your game should appear to the player to function just as it did before.
2. Refer to your exercises from previous modules if you need a reminder on creating databases and APIs.

### Week 2 Milestone

#### The Game Logic

The final step is to add the game logic, so it becomes a playable game!

* [ ] Only two cards should be able to be flipped at a time
* [ ] If the cards match, they should disappear
* [ ] Once all cards have disappeared, the player wins and the game is over
* [ ] After winning, the player should be able to restart the game and play again

#### Your Own Ideas!

Now your game is working, it's time to introduce your own features! Think of some improvements or changes to the game and implement it.

You should choose 3 features/improvements as a minimum to showcase as part of your project. But, you are welcome to add more and further polish your app to a high standard until you are super proud of it!

Some ideas for inspiration:

* [ ] Make use of the counter or timer in some way to make the game more challenging
* [ ] Add multiple levels so the player doesn't get bored
* [ ] Add more animations and interactivity, to make it exciting
* [ ] Implement a score mechanic
* [ ] Keep track of your personal best score/time
* [ ] Implement some options that the user can tweak, such as grid size
* [ ] Let the player choose a name, and save their score in the database
* [ ] Implement a leaderboard for the top 10 scores
* [ ] ... and many more!

### Week 3 Milestone

At the third session you'll be sharing a presentation. Read the [Session Plan](/course-content/foundation/final-project/session-plan) for more info.

Make sure you have all of the final details of your project working, as well as tidying up your deliverables such as your Trello board ready to present.

#### Deploy your app!

Part of the reward of building a web app is putting it live on the web! By completing this step you can experience the joy of showcasing your app on a public URL.

Follow the guide at [Deployment Quick Start](https://program.hackyourfuture.dk/trainee/technical-guides/deployment-quick-start) and give it a go.


# Initial Card Assets

Card Backside ![Card Backside](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-3c61a6c64e05a65283a2083cf92d884aa4f178ab%2Fcard-backside.jpg?alt=media)

Card Picture ![Card Picture](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-a5fe247d0c140b7843dffdad9fac578eb40c60c1%2Fcard-picture.jpg?alt=media)


# Session Plan

## Session Outline

This module is designed to be ran as a three week project. That means there will be three sessions, but it doesn't have the usual structure of content and learning goals for each week.

Instead, trainees will be continuously working through the [Project Brief](/course-content/foundation/final-project/project-brief), which is split up into three weekly milestones.

### The first session

Note: Trainees will work in pairs to compelete the project. These pairs will have been organised by a staff member before the session.

* Introduce the project requirements outlined in the [Readme](/course-content/foundation/final-project) and answer any questions.
* Remind trainees to use the project management skills they have recently learned. The [Readme](/course-content/foundation/final-project) describes these "organisational requirements" of the project that must be met.
* Give space for the trainees to organise into their pairs and get started.
* Actively work your way around the pairs, making sure everyone is making progress as they should.
* If multiple people are facing similar challenges, take the opportunity to "pause" the session and walk through something together out loud (e.g. creating a new github repo).

### The second session

* Progress update: Check in on what people have completed since last week, what they found hard, questions to answer, and encourage some people to demo their progress in front of the team.
* Teaching moment: If there were any significant issues or confusions that came up, spend some time diving into them in detail.
* Introduce the next milestone: Talk through the next requirements in detail, and answer any questions.
* Pairing time: Allow space for the trainees to continue working on their project, answering any questions as they come up with the whole team.

### The final session

The final session acts as a showcase for the projects. Here is an outline that can be shared with trainees:

```plaintext
🎮 Final Project Presentation Guidelines
When: 3rd week of the Foundation project
Duration: 7–10 minutes per team

Presentation structure:

1. Start with your Trello board → Explain your workflow, task organization, and process.

2. Show your project → Demonstrate the working game/application.

3. Talk about contributions → Each team member should briefly explain what they worked on.

Requirements before presentation day:
✅ Project must be fully deployed and live.
✅ Prepare a QR code linking to your live project.

During the session:

Share the QR code so other teams can test your game on their devices.
```

### The final assignment

After the presentation, trainees will have recently received lots of feedback and ideas for improving the app. Each trainee should choose 1 (or more) improvement to implement as a follow up assignment. The size of the change is not so important, since a small code change can significantly improve the app or fix a bug. The important part is that they choose a valuable change from the feedback and implement it.

This helps close the feedback loop from the last session, and provides closure for the final state of the project before completing the course.


# Frontend

This specialism course is focused on setting you up to land a Frontend Developer job. We go deeper into building frontend applications, design and popular frameworks that you'll meet in your career such as React.

## Modules

| Name                                                                                    | Weeks |
| --------------------------------------------------------------------------------------- | ----- |
| [Collaboration via GitHub](/course-content/shared-modules/collaboration-via-github)     | 1     |
| [Using AI in Development](/course-content/shared-modules/using-ai-in-development)       | 1     |
| [Advanced JavaScript](/course-content/frontend/advanced-javascript)                     | 4     |
| [React](/course-content/frontend/react)                                                 | 5     |
| [Specialist Career Training](/course-content/shared-modules/specialist-career-training) | 2     |
| [Agile Teamwork](/course-content/shared-modules/agile-teamwork)                         | 1     |
| [Final Project](/course-content/frontend/final-project)                                 | 5     |

Total: 19 weeks

## Learning Goals Overview

### [Collaboration via GitHub](/course-content/shared-modules/collaboration-via-github)

* [ ] How to write a good commit message and submit easy to understand PRs
* [ ] Understand why we use branches and the different types
* [ ] Practice using branches and handling changes between local and remote
* [ ] Understand what a merge conflict is and how to resolve them
* [ ] How to save temporary changes without committing them (ie. git stash)
* [ ] How to "remove" commits using reset (soft vs hard), revert, cherry-pick and rebase
* [ ] Be prepared to collaborate successfully using GitHub on your final project
* [ ] How to use git tags and semantic versioning
* [ ] Know the main git workflows (feature-branch, gitflow, forking) and when to use each

### [Using AI in Development](/course-content/shared-modules/using-ai-in-development)

* [ ] Use AI to support your development tasks such as refactoring and reviewing code.
* [ ] Explore prompting techniques to understand complex code, code snippets and tough technical concepts.
* [ ] Evaluate AI-generated code for correctness, expected outcomes, security and maintainability.
* [ ] Use AI to support learning new programming languages, frameworks and tools.
* [ ] Identify and integrate AI into appropriate parts of the software development workflow.
* [ ] Describe ethical, legal and risk considerations of using AI in professional software development.
* [ ] Explore the possible futures of how AI is changing the role and expectations of developers in the industry.

### [Advanced JavaScript](/course-content/frontend/advanced-javascript)

* [ ] Retrieve and work with data from remote servers
* [ ] Process and display complex data in user-friendly interfaces
* [ ] Create responsive web applications that react to user input
* [ ] Build complex websites in a scalable and maintainable way

### [React](/course-content/frontend/react)

* [ ] Understand when and why to use React to build modern web applications
* [ ] Build user interfaces using reusable, component-based architecture
* [ ] Manage data and interactivity using props, state, and hooks
* [ ] Handle user input, forms, and events in React applications
* [ ] Load and display data from external APIs
* [ ] Structure complex, multi-page applications with routing and shared state
* [ ] Understand what a Component Library is, along with the pros and cons
* [ ] Build, deploy, and share a production-ready React app using Next.js

### [Specialist Career Training](/course-content/shared-modules/specialist-career-training)

> ⚠️ "Learning goals" section is empty in `shared-modules/specialist-career-training`

### [Agile Teamwork](/course-content/shared-modules/agile-teamwork)

* [ ] Understand conceptual differences between Agile, Scrum & Kanban
* [ ] Understand what Scrum looks like in day to day life as a developer
* [ ] Understand how to interact with Scrum ceremonies (e.g. standup, planning, estimating/prioritising, retrospectives)
* [ ] Practice skills used by developers such as understanding requirements, breaking down technical tasks, and common workflows for reviewing, testing and deploying.
* [ ] Understand how these skills and practices impact and support agility
* [ ] Be able to organise a very well structured project in collaboration with other developers for the final project

### [Final Project](/course-content/frontend/final-project)

* [ ] Collaborate effectively in a team setting
  * [ ] Read and extend/improve other peoples code
  * [ ] Give and receive constructive PR feedback
  * [ ] Plan, communicate and coordinate technical tasks / solutions upfront before implementation
* [ ] Develop self-guided learning skills (e.g. learn to read documetation for a new tool or API)
* [ ] Interpret a problem statement and specs/wireframes/prototypes into buildable requirements
* [ ] Break down bigger problems into smaller, actionable written tasks
* [ ] Work in iterative sprints and achieve deadlines
* [ ] Ask for help effectively and at the right time (e.g. describing problems to mentors, asking online, and knowing the power *and* limitations of using AI)
* [ ] Deploy a completed project you are proud to showcase on your portfolio


# Advanced JavaScript

Javascript is the brain of the website and an essential technology to master when building increasingly complex websites.

In this module, you will advance your JavaScript expertise to build interactive and dynamic websites. You will explore how to retrieve data from remote servers, process and present complex information in intuitive interfaces, and develop responsive web applications that respond to user actions. Additionally, you will learn strategies for designing scalable and maintainable code to tackle advanced development scenarios.

## Contents

| Week | Topic                                                                                        | Preparation                                                                   | Session Plan                                                                                  | Assignment                                                                  |
| ---- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| 1.   | [Array functions & Arrow functions](/course-content/frontend/advanced-javascript/week1)      | [Preparation](/course-content/frontend/advanced-javascript/week1/preparation) | [Session Plan](/course-content/frontend/advanced-javascript/week1/session-plan) (for mentors) | [Assignment](/course-content/frontend/advanced-javascript/week1/assignment) |
| 2.   | [Callback functions & Asynchronous code](/course-content/frontend/advanced-javascript/week2) | [Preparation](/course-content/frontend/advanced-javascript/week2/preparation) | [Session Plan](/course-content/frontend/advanced-javascript/week2/session-plan) (for mentors) | [Assignment](/course-content/frontend/advanced-javascript/week2/assignment) |
| 3.   | [Promises & `async`/`await`](/course-content/frontend/advanced-javascript/week3)             | [Preparation](/course-content/frontend/advanced-javascript/week3/preparation) | [Session Plan](/course-content/frontend/advanced-javascript/week3/session-plan) (for mentors) | [Assignment](/course-content/frontend/advanced-javascript/week3/assignment) |
| 4.   | [Classes & Object-Oriented Programming](/course-content/frontend/advanced-javascript/week4)  | [Preparation](/course-content/frontend/advanced-javascript/week4/preparation) | [Session Plan](/course-content/frontend/advanced-javascript/week4/session-plan) (for mentors) | [Assignment](/course-content/frontend/advanced-javascript/week4/assignment) |

## Module Learning Goals

By the end of this module, you will be able to:

* [ ] Retrieve and work with data from remote servers
* [ ] Process and display complex data in user-friendly interfaces
* [ ] Create responsive web applications that react to user input
* [ ] Build complex websites in a scalable and maintainable way


# Week 1

This session is about mastering the most commonly used array functions provided by Javascript. Working with arrays is an essential part of being a javascript developer. A lot of the time js developers have an array of some objects. That could be **users**, **products**, **posts**, **jobs** etc. Developers so often need to filter the arrays, change the structure of the array, sort them or loop through them.

Understanding how to use array functions and the arrow notation can greatly improve the readability of your code.

The module strongly encourages going beyond JavaScript alone and **implementing a real frontend**—work that runs in the browser with a visible, interactive UI. All exercises (session materials and assignment) are designed so that JavaScript drives HTML and the interface.

## Contents

* [Preparation](/course-content/frontend/advanced-javascript/week1/preparation)
* [Session Plan](/course-content/frontend/advanced-javascript/week1/session-plan) (for mentors)
* [Assignment](/course-content/frontend/advanced-javascript/week1/assignment)

## Session Learning Goals

By the end of this session, you will be able to:

* [ ] Use the **arrow function syntax** with any number of arguments
* [ ] Use the **arrow function syntax** with an implicit return (no curly braces)
* [ ] Use the **array functions** `.forEach()`, `.map()`, and `.filter()`
* [ ] Know how to find and learn about other **array functions** such as `.find()`, `.some()`, `.reduce()`
* [ ] Combine multiple **array functions** (chaining) to solve complex problems in a concise way.

```js
// Example of using filter() with an arrow function
const expensiveItems = myItemArray.filter((x) => x.cost > 200);
```


# Preparation

## Reading List

Read/watch through this list of content before you come to the session.

> \[!TIP] Some topics are covered in multiple links below. Feel free to skip reading if you already feel confident that you understand the topic.

### Arrow Functions

Use one or more of the links to :

* 📖 [JavaScript Arrow Function](https://www.w3schools.com/js/js_arrow_function.asp) by w3schools.com (10 min)
* 📽️ [Javascript Arrow Functions](https://youtu.be/DFyfbJk4sZw) by HackYourFuture (10 min)

### Array Functions

* 📽️ [Javascript advanced array methods part 1](https://youtu.be/wBKv2EX2hw8) by HackYourFuture (20 min)
* 📽️ [JavaScript advanced array methods part 2](https://youtu.be/w4FNF8FLjQU) by HackYourFuture (5 min)
* 📽️ [Functional programming in JavaScript](https://www.youtube.com/playlist?list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84) by Fun fun functional - Check the first 2 videos. (20 min)
* 📽️ [Array Iteration: 8 Methods](https://www.youtube.com/watch?v=Urwzk6ILvPQ) by freeCodeCamp.org (5 min)
* 📖 [10 JavaScript array methods you should know](https://dev.to/frugencefidel/10-javascript-array-methods-you-should-know-4lk3) by Frugence Fidel (10 min)
* 📖 [Chaining Array functions](https://www.geeksforgeeks.org/javascript/chaining-of-array-methods-in-javascript/) by Madhumanti Gupta (5 min)
* 📖 Go to the [official documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) by MDN and read the *description* and *examples* of each function:
  * `forEach()` (10 min)
  * `map()` (10 min)
  * `filter()` (10 min)


# Session Plan

## Session Materials

These are some examples of previously created materials by mentors that you can use yourself, or for inspiration.

* [Notion Page Handout](https://dandy-birth-1b2.notion.site/HYF-Aarhus-JS-2-Week-2-cd0c1163d0264215824dc17580c97825?pvs=4) (by [Thomas](https://github.com/te-online))

### Mentors demo

The [Mentors demo](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/mentors-demo/README.md) is an in-session demo for forEach, map, filter, and chained filter. Use **index.js** to implement the TODOs in class (FOREACH, MAP, FILTER, CHAINING). The [README](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/mentors-demo/README.md) describes the files, how tasks are marked, and how the code works. **index-solution.js** has the full implementation for reference.

## Session Outline

### Array functions

Write this code with traditional `function`s, no arrow functions yet!

* Try to write your own `forEach`, `map` and `filter` with the trainees. Shows very precisely how it works!
* `forEach` - Executes function for each item in the array, NO RETURN!
  * [Mentors demo](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/mentors-demo/README.md) – do **FOREACH TODO**
  * [Code inspiration](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/code-inspiration.md#foreach)
  * [forEach homemade](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/code-inspiration.md#foreach-homemade)
  * [Exercises](/course-content/frontend/advanced-javascript/week1/exercises#task-1-generate-and-show-listings-foreach)
* `map` - Changes/transforms the items in the array
  * [Mentors demo](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/mentors-demo/README.md) – do **MAP TODO**
  * [Code inspiration](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/code-inspiration.md#map)
  * [map homemade](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/code-inspiration.md#map-homemade)
  * [Exercises](/course-content/frontend/advanced-javascript/week1/exercises#task-2-show-prices-map)
* `filter` - Changes the number of items in the array. Let the trainees investigate `filter`
  * [Mentors demo](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/mentors-demo/README.md) – do **FILTER TODO**
  * [Code inspiration](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/code-inspiration.md#filter)
  * [filter homemade](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/code-inspiration.md#filter-homemade) - Get help from trainees to write this
  * [Exercises](/course-content/frontend/advanced-javascript/week1/exercises#task-3-filter-buttons-filter)
* [Mentors demo](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/mentors-demo/README.md) – do **CHAINING TODO** (multiple filter conditions)
* [Other example](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/code-inspiration.md#other-example)

### Arrow Functions

* [Code inspiration](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/code-inspiration.md#arrow-function)
* [Exercises](/course-content/frontend/advanced-javascript/week1/exercises#task-arrow-functions)

## Exercises

See the separate [Exercises](/course-content/frontend/advanced-javascript/week1/exercises) document.

## Code inspiration

See the separate [Code inspiration](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/code-inspiration.md) document.


# Exercises

Work in the [Listings demo](https://github.com/HackYourFuture-CPH/hyf-assignment-template/blob/main/courses/frontend/advanced-javascript/week1/listings-demo). Open **index.html** in your browser to run the demo, and open **index.js** in your IDE to implement the tasks. In `index.js`, search for **`Task`** (e.g. Task 1.1, Task 2)—each task has a comment with explicit instructions about what code to write. This document describes the **end-result** you’re aiming for and how the exercise is set up. The generation of random listings and the render helpers (cards, price list) are already implemented; you only need to call them and add the logic that uses `.forEach()`, `.map()`, and `.filter()`.

## Task 1: Generate and show listings (`forEach`)

**What should happen:** When the user clicks **Generate listings (37) — Task 1**, 37 random listings are generated and displayed as cards on the page.

**Listing** (each object in the generated array):

| Property     | Type      | Description                                                 |
| ------------ | --------- | ----------------------------------------------------------- |
| `type`       | string    | e.g. `"House"`, `"Apartment"`, `"Shed"`, `"Dorm"`, `"Farm"` |
| `facilities` | string\[] | e.g. `["Parkering", "Have"]`                                |
| `price`      | number    | 1–10000                                                     |
| `hasGarden`  | boolean   |                                                             |
| `size`       | number    | m², 12–1000                                                 |
| `img`        | string    | image URL                                                   |

You implement the logic that (1) triggers generation and (2) renders the listings by iterating over the array and adding one card per listing. The code that builds each card and prepares the view is already there; you use `listings.forEach(...)` to show every listing.

## Task 2: Show prices (`map`)

**What should happen:** After generating listings, when the user clicks **Show prices — Task 2**, a list of all listing prices appears (e.g. comma-separated) in the prices area.

You implement getting an array of prices from the current listings and passing it to the helper that displays numbers. Use `.map()` to turn the list of listings into a list of prices.

## Task 3: Filter buttons (`filter`)

**What should happen:** When the user clicks one of the filter buttons, the page shows only the matching listings (or their prices).

* **Cheap listings — Task 3a:** Only “cheap” listings are shown as cards. You decide what “cheap” means (e.g. price below a certain number). Use `.filter()` and then the same render-as-cards logic as in Task 1.
* **Expensive prices — Task 3b:** Only the *prices* of “expensive” listings are shown (as numbers). Use `.filter()` to get expensive listings, then `.map()` to get their prices, and the helper that displays numbers.
* **With parking — Task 3c:** Only listings that have “Parkering” in their facilities are shown as cards. Use `.filter()` on the facilities.

## Task: Arrow functions

Rewrite the code you wrote for Tasks 1–3 to use arrow function syntax instead of `function`.

## Task 4: Advanced filters (Listing project)

**What should happen:** The user can set type, min price, min size, facilities, and garden in the Advanced filters form. When they click **Apply filters — Task 4**, only listings that match *all* selected criteria are shown as cards.

You implement **filterListings(listings, filter)**. Reading the form and building the `filter` object is already done; you receive an object with only the fields the user set. Return only listings that match every property present in `filter`. If a property is missing from `filter`, don’t filter by it.

**Filter** (object passed to `filterListings`; only set fields are present):

| Property     | Type      | Meaning                                                       |
| ------------ | --------- | ------------------------------------------------------------- |
| `type`       | string    | `listing.type` must equal this.                               |
| `minPrice`   | number    | `listing.price` must be ≥ this.                               |
| `minSize`    | number    | `listing.size` must be ≥ this (m²).                           |
| `hasGarden`  | boolean   | If `true`, `listing.hasGarden` must be `true`.                |
| `facilities` | string\[] | `listing.facilities` must include every string in this array. |


# Assignment

Tasks 1 and 2 are short warmups; task 3 is a larger, real-world-style task where everything is visible in one page or app.

* **Task 1 (Doubling of number):** JavaScript only. Submit your solution using `map` and `filter` (and arrow functions).
* **Task 2 (Codewars):** Complete the Katas on Codewars. No frontend or repo submission needed.
* **Task 3 (Working with movies):** Frontend required. Build an HTML page with CSS and JavaScript that runs in the browser and shows the result of each movie sub-task in the page (e.g. sections or cards with the computed data).

## 1. Doubling of number

Say you would like to write a program that **doubles the odd numbers** in an array and **throws away the even number**.

Your solution could be something like this:

```js
let numbers = [1, 2, 3, 4];
let newNumbers = [];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 !== 0) {
    newNumbers[i] = numbers[i] * 2;
  }
}
// expected result: [2, 6]
```

Rewrite the above program using `map` and `filter`; don't forget to use arrow functions.

## 2. Codewars!

Complete these Katas:

* [8 kyu To square(root) or not to square(root)](https://www.codewars.com/kata/57f6ad55cca6e045d2000627)
* [8 kyu Removing Elements](https://www.codewars.com/kata/5769b3802ae6f8e4890009d2)

## 3. Working with movies

![cinema](https://media.giphy.com/media/l6mBchxYZc7Sw/giphy.gif)

**What the user sees:** One page (e.g. sections or cards) where every sub-task’s result is visible in the browser: short titles, long titles, 1980s count, tagged movies, ratings over 6, keyword count, duplicated-word titles, and optionally average rating and Good/Average/Bad counts.

Copy the movies array from [movies](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week1/session-materials/movies.js) and use it for the tasks below.

1. Create an array of movies containing the **movies with a short title** (you define what short means)
2. Create an array of movie titles with **long movie titles**
3. Count the **number of movies** made between 1980-1989 (including both the years)
4. Create a new array that has an **extra key called tag**. The tag is based on the rating: Good (>= 7), Average (>= 4 and < 7), Bad (< 4)
5. Using chaining, first filter the movies array to only contain the movies rated higher than 6. Now map the movies array to only the rating of the movies.
6. **Count the total number of movies** containing any of following keywords: `Surfer`, `Alien` or `Benjamin`. So if there were 3 movies that contained `Surfer`, 1 with `Alien` and 2 with `Benjamin`, you would return 6. Can you make sure the search is case insensitive?
7. Create an array of movies where a **word in the title is duplicated**. e.g. "Star **Wars**: The Clone **Wars**" the word **Wars** is duplicated. Here are some made-up examples of movies with duplicated words in the title: "**The** three men and **the** pistol", "**Chase** three - The final **chase**"
8. Calculate the **average rating** of all the movies using `.reduce()` *Optional*
9. **Count the total number** of Good, Average and Bad movies using `.reduce()`. A return could be e.g. `{goodMovies: 33, averageMovies: 45, goodMovies: 123}` *Optional*


# Week 2

This session is about how you in Javascript can assign functions to variables, pass them as arguments, and return them from other functions. You'll learn how to use callback functions to handle asynchronous operations, such as fetching data from a server or responding to user events.

By understanding the difference between synchronous and asynchronous code, you'll be able to write more efficient and responsive programs which will make for a much better user experience.

## Contents

* [Preparation](/course-content/frontend/advanced-javascript/week2/preparation)
* [Session Plan](/course-content/frontend/advanced-javascript/week2/session-plan) (for mentors)
* [Assignment](/course-content/frontend/advanced-javascript/week2/assignment)

## Session Learning Goals

By the end of this session, you will be able to:

* [ ] Assign functions to variables
* [ ] Pass functions as arguments
* [ ] Return functions from other functions
* [ ] Call functions inside other functions
* [ ] Distinguish between synchronous and asynchronous code
* [ ] Explain why we need code to run asynchronously sometimes
* [ ] Write and use callback functions
* [ ] Use `setTimeout()` for asynchronous operations
* [ ] Use `addEventListener()`

```js
// Example: Using setTimeout() with a callback function
const callback = () => console.log("Do something later");
setTimeout(callback, 1000);
console.log("Do something now");
```


# Preparation

## Reading List

Read/watch through this list of content before you come to the session:

* 📽️ [JavaScript Callback Functions](https://www.youtube.com/watch?v=pTbSfCT42_M) by techsith (15 min)
* 📖 [Asynchronous vs. Synchronous Programming](http://www.hongkiat.com/blog/synchronous-asynchronous-javascript/) by Preethi Ranjit (10 min)
* 📖 [setTimeout()](https://www.w3schools.com/jsref/met_win_settimeout.asp) by w3schools (5 min)
* 📖 [addEventListener()](https://www.w3schools.com/jsref/met_element_addeventlistener.asp) by w3schools (10 min)
* 📽️ [HYF - JavaScript Callbacks](https://youtu.be/hjgunSqSPaA) by HackYourFuture (20 min)
* 📽️ [HYF - Working with Asynchronous Code in JavaScript](https://youtu.be/RTrua6CRNEM) by HackYourFuture (10 min)


# Session Plan

## Session Materials

These are some examples of previously created materials by mentors that you can use yourself, or for inspiration:

* [Notion Page Handout](https://dandy-birth-1b2.notion.site/HYF-Aarhus-JS-2-Week-3-6bce73b3a0bf47a3ad32ed12ee4d0519?pvs=4) (by [Thomas](https://github.com/te-online))
* [Demo](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week2/session-materials/demo/README.md) – In-session code: **index.js** (worksheet with Task/Next comments to implement this session plan) and **index-solution.js**.
* [Event loop demo](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week2/session-materials/event-loop-demo/README.md) – Draggable code blocks (sync, setTimeout) into Call stack, Timer, Async queue. Use it to explain how the event loop works under the hood.

## Session Outline

1. **Functions – passing a function as an argument**
   * Repeat everything about functions. Functions as a variable: pass as argument, call from inside another function.
   * This is super good at explaining function logic: [Function graphic](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week2/session-materials/function-graphic.jpg).
   * [Demo](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week2/session-materials/demo/README.md): implement `functionRunner`.
   * [Code inspiration](#calling-a-function-within-a-function).
2. **Callbacks – setTimeout and the event loop**
   * Explain how `setTimeout(callback, delay)` works, why the timer is never exact and why a 0 delay doesn't make it a sync operation.
   * [Event loop demo](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week2/session-materials/event-loop-demo/README.md) can help with explaining how async operations work under the hood.
   * Solve [console-order.md](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week2/session-materials/console-order.md) together with the trainees.
   * [Code inspiration](#callback-functions).
3. **(Optional) Infinite loop – sync vs async**
   * Implementation of an infinite loop with both sync and async operations and demonstrating whether it freezes the page or not. Helps to realise how async operations work under the hood.
4. **Callbacks – events (addEventListener)**
   * Another example of callbacks. Explain `addEventListener`.
   * [Code inspiration](#event-listeners), [Anonymous vs named](#anonymous-vs-named-function).

Also hammer in the point of the difference between:

```js
document.querySelector("button").addEventListener("click", logOuttext);
document.querySelector("button").addEventListener("click", logOuttext());
```

Here's a good [practical example of callbacks](https://github.com/HackYourFuture-CPH/JavaScript/blob/class08/JavaScript2/Week5/classwork/extra_examples.md) (TODO: move this to this repo).

## Code inspiration

### Calling a function within a function

```js
// Here we create a function that as a parameter takes a function!! Super weird right!?
// Functions works just like any other type in js.
function functionRunner(functionToRun) {
  console.log(typeof functionToRun);
  // Here we are calling the function that is provided as an argument when calling functionRunner
  functionToRun();
}

functionRunner(function () {
  console.log("hello");
});

// We don't see anything, why??
functionRunner(Math.random);

// Let's rewrite functionRunner to log out the return of a function
function functionRunnerImproved(functionToRun) {
  console.log(typeof functionToRun);
  // Here we are calling the function that is provided as an argument when calling functionRunner
  const capturedReturnValue = functionToRun();
  console.log(capturedReturnValue);
}

functionRunnerImproved(Math.random);
```

### Callback functions

```js
/*
Events
Events in javascript are thing like:
A timer has just finished, a user clicked a button, our page has loaded,
someone types into an input element or we have just gotten some data from a server.
When these events happen, we usually want to add some functionality.
e.g. when a user clicks the like button (event), we want to increment the like counter and color the like button blue.
Or when someone clicks "Close cookies" (event) we want to remove the cookie div.
Let's first try to create some js that waits 2 seconds and the console.logs out "2 seconds has elapsed!"
In javascript we use the word eventlistener to listen
*/

// Tried to find actual webkit implementation, but failed. To show that the setTimeout implementation is just calling the provided function after a given time
setTimeout(function () {
  console.log("2 seconds has elapsed!");
}, 2000);

// Cool, now let's make a function as a variable:
const fourSecondLog = function () {
  console.log("4 seconds has elapsed!");
};

setTimeout(fourSecondLog, 4000);
```

### Event Listeners

```javascript
// Now let's keep track of how many times a button is clicked.
// To do something whenever a button gets clicked, we use what is called an event listener.
// Imagine that the button is noisy. There's someone listening out for the click sound,
// and every time they hear it, they add 1 to a counter.

const buttonElement = document.querySelector("button");
let counter = 0;

buttonElement.addEventListener("click", function () {
  counter = counter + 1;
  console.log(`Button clicked ${counter} times so far`);
});

// or the same thing but assigning the event listener to a const:

const buttonElement = document.querySelector("button");
let counter = 0;

const buttonClicked = function () {
  counter = counter + 1;
  console.log(`Button clicked ${counter} times so far`);
};

buttonElement.addEventListener("click", buttonClicked);

//Callbacks
// Now let's learn about callbacks!
// Well actually you have already made callbacks!
// When you give a function to an event listener or a timer or when fetching data you are using a callback function

// Let's create a callback function when someone writes in a input element
const callback = function () {
  console.log("Someone is writing!!");
};

document.querySelector("input").addEventListener("input", callback);
```

### Anonymous vs named function

```js
// Named function
function myFunction() {
  console.log("myFunction");
}

// Anonymous function, assigned to a variable
const myFunctionAsVar = function () {
  console.log("myFunctionAsVar");
};

document.body.addEventListener("click", myFunctionAsVar);
document.body.addEventListener("click", myFunction);
```

## Exercises

See [Exercises](/course-content/frontend/advanced-javascript/week2/exercises). Trainees show results on the page (update the DOM), not in the console.


# Exercises

Work through these in order.

## 1. Click counter

Create an `index.html` file with two buttons and a place to show the count.

* When the first button is clicked, show 0. The next time show 1, then 2, etc.
* Clicking the second button should use the same counter and update the same display.

## 2. Delay clicker

Create a button with the text "Log in 3 seconds" and an area where you can show a message.

* When the button is clicked, wait 3 seconds and then show the text: "This text was delayed by 3 seconds".

## 3. Page onload

Create a callback function (as a variable) that shows "DOM fully loaded and parsed".

This callback should run when the DOM is fully loaded. Search for how to run code when the DOM is ready (e.g. "DOM ready" or "page load event").

## 4. Mouse position

Create a handler that shows the x,y coordinates of the mouse (e.g. update a paragraph or a fixed div as the user moves the mouse).

## 5. Mouse position online tool

Imagine an online tool where businesses see where their users' mouse is most of the time, to check if their design works well.

Write JS that, after 30 seconds, computes the average x and y position of the user's mouse and displays it.

> \[!TIP] Before starting, make a plan for how you will implement this (e.g. with your mentor).


# Assignment

## 1. Codewars!

* [7 kyu Product Array (Array Series #5)](https://www.codewars.com/kata/5a905c2157c562994900009d/javascript)

## 2. Functions!

The warmup is a **little abstract**, it will get more concrete later on!

1. Display the text `Called after 2.5 seconds` on the page 2.5 seconds after the script is loaded.
2. Create a function that takes 2 parameters: `delay` and `stringToLog`. Calling this function should display the `stringToLog` on the page after `delay` seconds. Call the function you have created with some different arguments. ![second task](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-6baafce96180e7f7b510946c79992f891b8d7d7a%2Fcarbon.png?alt=media)
3. Create a button in html. When clicking this button, use the function you created in the previous task to display the text `Called after 5 seconds` on the page 5 seconds after the button is clicked.

![second task](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-073f2f4d6d7c3007360d9f6173ebfe12536fc517%2Fbutton-delay.gif?alt=media)

4. Create two functions and assign them to two different variables. One function displays `Earth` on the page, the other displays `Saturn`. Now create a new third function that has one parameter: `planetLogFunction`. The only thing the third function should do is call the provided parameter function. Try calling the third function once with the `Earth` function and once with the `Saturn` function.

![second task](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-df5cf3f3426802e417e7156be19ea8288c84f033%2Fplanet-log.png?alt=media)

5. Create a button with the text "Log location". When this button is clicked, display the user's location (latitude, longitude) on the page using this [browser API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API).

![second task](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-9fd98bc65988d1ff3eee92dc892946f174e685c8%2Flog-location.gif?alt=media)

6. *Optional* Now show that location on a map using e.g. the [Google maps api](https://developers.google.com/maps/documentation/javascript/tutorial)
7. Create a function called `runAfterDelay`. It has two parameters: `delay` and `callback`. When called the function should wait `delay` seconds and then call the provided callback function. Add an input in the HTML for the delay (in seconds) and a button; when the button is clicked, read the delay from the input and call `runAfterDelay` with that delay and a callback that displays something on the page.

![second task](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-3e107e2c37fce896718b14ea12c1b2324025dfed%2Frun-after-delay.png?alt=media)

8. Check if the user has double-clicked on the page. A double click is two clicks within 0.5 seconds. If a double click is detected, display the text "double click!" on the page.
9. Create a function called `jokeCreator` that has three parameters: `shouldTellFunnyJoke` (boolean), `logFunnyJoke` (function), and `logBadJoke` (function). If `shouldTellFunnyJoke` is `true` it should call `logFunnyJoke`, which displays a funny joke on the page. Otherwise it should call `logBadJoke`, which displays a bad joke on the page.

## 3. Function as a variable

Create functions that are used in these different ways:

* Create an array with 3 items. All items should be functions. Iterate through the array and call all the functions.
* Create a function as a const and try creating a function normally. Call both functions. You can read more about this in [What is the difference between a function expression vs declaration in JavaScript?](https://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip)
* Create an object that has a key whose value is a function. Try calling this function.

Yes I know that was a little tough, now on to the fun part 🎉

![phew](https://media.giphy.com/media/EDt1m8p5hqXG8/giphy.gif)

## 4. The fastest presser in this realm

Let's create a fun simple game :)

Here is the setup of the game: **Two users compete** about who can **press a key the most times** within a set time!

A user specifies how long time the game should be, and presses **"start game!"**. When the button is pressed it is about pressing either `l` or `s` on the keyboard. The user that has the highest number of keypresses after the time is up, wins 🎉

Here is a gif of how the site should work:

![Fastest presser game demo](https://1850235804-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fv5mADMeH7axh0TSGyUQy%2Fuploads%2Fgit-blob-72226655b1be6af41aaae02d96dcced9a78e1e4c%2Ffastest-clicker.gif?alt=media)

You can implement it exactly like you want to, but here is my recommended order:

1. **Create an input and a button in html**. When the button is clicked, get the value of the input. This value will be the amount of time the game should run.
2. **Set a timeout for the time specified by the user.** After that time has run out, display a message on the page (e.g. "Time's up!").
3. **Create an event listener** so you can call a function **when any key is pressed**. Now grab the actual key that was pressed. e.g. was it a `j` or an `i`. We are interested in `s` and `l`. Here Google is your friend!
4. **Keep a counter** for how many times `l` and `s` was pressed.
5. **Now put it all together!** After the timeout is done figure out which of the counters is largest. Give some kind of feedback to the users indicating who won.

## Optional Assignments

### 5. Extra features

1. **Start a new game** functionality. Create some functionality so that the users can restart a game.
2. Try and give the site some **styling so it looks nice** :)
3. **Custom feature**. Add something unique to the game! If you don't know how to implement it, just describe what it should do!
4. **Countdown to end of game** - *optional*. Have a countdown that simply counts down until the game is done.

Here are some general things to consider:

* What if a user starts pressing a key before the game is started, what should happen?
* What if the game is a draw? Are both winners? None winners? Maybe indicate to the user that is was a draw.
* What if no time was specified for the game?
* What if there were no key presses before the game ends?

### 6. Confetti

If you wanna give the game some confetti like in the gif, check out [this library](https://www.npmjs.com/package/confetti-js)

Use the library in your page by adding this line before you load your main.js:

```js
<script src="https://cdn.jsdelivr.net/npm/confetti-js@0.0.13/dist/index.min.js"></script>
```


# Week 3

In this session, you'll learn how to write asynchronous code that is both efficient and easy to understand. We'll explore Promises and the `async`/`await` syntax, which allow you to handle long-running operations—such as network requests—without blocking the user interface. Mastering these techniques is key to building responsive applications that deliver a smooth user experience.

## Contents

* [Preparation](/course-content/frontend/advanced-javascript/week3/preparation)
* [Session Plan](/course-content/frontend/advanced-javascript/week3/session-plan) (for mentors)
* [Exercises](/course-content/frontend/advanced-javascript/week3/exercises)
* [Assignment](/course-content/frontend/advanced-javascript/week3/assignment)

## Session Learning Goals

By the end of this session, you will be able to:

* [ ] Use **Promises** to run asynchronous code.
  * [ ] Understand the anatomy of a Promise and how to use it
  * [ ] Using `.then()` to add callback behaviour
  * [ ] Using `.catch()` to handle errors
  * [ ] Chaining multiple `.then()`
* [ ] Use `async` and `await` to make your code more readable
  * [ ] Defining `async` functions
  * [ ] Using `await` when calling `async` functions
  * [ ] Error handling using `await`

```js
// Example: Using promise with .then()
let user1;
fetch("https://jsonplaceholder.typicode.com/users/1")
  .then((response) => (user1 = response.json()))
  .then(() => console.log("User 1:", user1))
  .catch(() => (user1 = null));

// Example: Using promise with async/await
async function getUser() {
  try {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/users/2",
    );
    const user = await response.json();
    return user;
  } catch (error) {
    return null;
  }
}
```


# Preparation

## Reading List

### Promises

* 📖 [A cartoon explaining promises](https://fullstackjournal.wordpress.com/2018/07/06/the-promise-js-explained-i-burger-party/) by Kosamari (10 min)
* 📖 [Guide to Promises](https://javascript.info/async) by javascript.info (Step 2-4) (60 min)
* 📽️ [Async JavaScript tutorial](https://www.youtube.com/playlist?list=PL4cUxeGkcC9jx2TTZk3IGWKSbtugYdrlu) by Net Ninja - focus on the following:
  * [Callback Hell](https://www.youtube.com/watch?v=EQem2gugonA\&list=PL4cUxeGkcC9jx2TTZk3IGWKSbtugYdrlu\&index=6\&ab_channel=NetNinja) (5 min)
  * [Promises](https://www.youtube.com/watch?v=a_8nrslImo4\&list=PL4cUxeGkcC9jx2TTZk3IGWKSbtugYdrlu\&index=7\&ab_channel=NetNinja) (10 min)
  * [Chaining Promises](https://www.youtube.com/watch?v=GfVMKkUk2Uo\&list=PL4cUxeGkcC9jx2TTZk3IGWKSbtugYdrlu\&index=8\&ab_channel=NetNinja) (5 min)
  * [The Fetch API](https://www.youtube.com/watch?v=drK6mdA9d_M\&list=PL4cUxeGkcC9jx2TTZk3IGWKSbtugYdrlu\&index=9\&ab_channel=NetNinja) (10 min)

Optionally:

* 📽️ [Promises practical examples using Javascript](https://youtu.be/o_m4clbtzeI) by HackYourFuture (15 min)
* 📽️ [Creating a promise using Javascript](https://youtu.be/qapwmq5UA6Y) by HackYourFuture (20 min)
* 📽️ [Consuming/using promises using Javascript](https://youtu.be/G4YSi6VA2gw) by HackYourFuture (20 min)

### `async` / `await`

* 📽️ [Async JavaScript tutorial](https://www.youtube.com/playlist?list=PL4cUxeGkcC9jx2TTZk3IGWKSbtugYdrlu) by Net Ninja - focus on the following:
  * [Async & Await](https://www.youtube.com/watch?v=CWjNefiE47Y\&list=PL4cUxeGkcC9jx2TTZk3IGWKSbtugYdrlu\&index=10\&ab_channel=NetNinja) (10 min)
  * [Throwing Errors](https://www.youtube.com/watch?v=AoBSB00vW5A\&list=PL4cUxeGkcC9jx2TTZk3IGWKSbtugYdrlu\&index=11\&ab_channel=NetNinja) (5 min)
* 📽️ [Async crash course](https://www.youtube.com/watch?v=PoRJizFvM7s) by Traversy Media (25 mins)
* 📖 [async/await](https://javascript.info/async-await) by javascript.info (15 min)

Optionally:

* 📽️ [Working with async/await using Javascript](https://youtu.be/6Hq6AywZ7FY) by HackYourFuture (15 min)

![You can do it!](https://media.giphy.com/media/yoJC2K6rCzwNY2EngA/giphy.gif)


# Session Plan

## Session Materials

These are some examples of previously created materials by mentors that you can use yourself, or for inspiration.

* [Notion Page Handout](https://dandy-birth-1b2.notion.site/HYF-Aarhus-JS-3-Week-2-0287dd1293df4a0a92171e62ce12f5c8?pvs=4) (by [Thomas](https://github.com/te-online))
* [Demo](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week3/session-materials/demo/README.md) – In-session live coding from **Code inspiration** below (not the trainee exercises). **index.js** = worksheet stubs; **index-solution.js** = reference. [README](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week3/session-materials/demo/README.md).
* [Promises chaining diagram (PDF)](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week3/session-materials/Promises.pdf) – Hand-drawn sketch you can project or redraw on the board when explaining how `.then()` chains.

## Session Outline

Promises is notoriously difficult to teach! I teach **consumption and creation of promises totally separate!** And show them that it's just like with functions. There is a creation part and a consumption part.

First when they fully understand one part of promises, I move on! Don't over-complicate things. Only mention the resolve function to begin with. When they get that, say that there also is a reject function. **Take as many baby steps as is possible!** Don't mention that resolve and reject can take an argument to begin with, first later explain that.

* Async/await - simple introduction focused on usage
  * Quickly recap asynchronicity
    * Ask the trainees what it means that some code is asynchronous
  * Practical example of async/await
  * [Exercises 1](/course-content/frontend/advanced-javascript/week3/exercises#exercise-1)
* Promise
  * Why do we use promises?
    * So important to explain this, the trainees always ask this! [Is there specific functionality that can only be done with promises in JS?](https://stackoverflow.com/questions/39004567/why-do-we-need-promise-in-js)
  * Consumption
    * [Code inspiration](#promise-consumption)
    * Example, call some function that returns a promise (like fetch)
    * [Exercises 2](/course-content/frontend/advanced-javascript/week3/exercises#exercise-2)
  * Creation
    * [Code inspiration](#promise-creation)
    * [Exercises 3](/course-content/frontend/advanced-javascript/week3/exercises#exercise-3) and then [Exercises 4](/course-content/frontend/advanced-javascript/week3/exercises#exercise-4)
  * Async await
    * [Exercises 5](/course-content/frontend/advanced-javascript/week3/exercises#exercise-5)
  * `Promise.all` - Let trainees investigate
  * Optional - Chaining. Calling `.then` returns a promise. Only get to here when they understand async/await and promise consumption and creation.
    * I found that drawing/demoing how it works under the hood useful when explaining how promises feed into the next `.then()`. You can find example in Session matherials.
    * [Reason for promise](https://mobile.twitter.com/addyosmani/status/1097035418657144832?s=19)
  * [Exercises 5](/course-content/frontend/advanced-javascript/week3/exercises#exercise-5) and [Exercises 6](/course-content/frontend/advanced-javascript/week3/exercises#exercise-6)

## Exercises

See [Exercises](/course-content/frontend/advanced-javascript/week3/exercises). Trainees show results on the page (update the DOM), not in the console.

[Console order](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week3/session-materials/console-order.md) – Optional “what is logged?” promise chaining.

## Code inspiration

### Async/await - simple usage

```js
// Warm up exercise. The trainees has to say everything they can about a variable, ONLY from the variable name. e.g. the type, what it returns, what object we could expect etc.
// cars, car, title, getTitle, addTitle, isTitle, hasTitle, hasItem, users, year, yearIndex, user, review.
```

```js
// DON'T EXPLAIN WHAT ASYNC OR AWAIT DOES YET! Explain on a higher level:
// You have to write async before a function for await to work. No details for now
// await waits until we have fetched the data from the api. Or said in another way await waits until fetch has resolved with the data from the api

// write async before a function for await to work. What does it mean that something is asynchronous?
// JSONPlaceholder works reliably in the browser (same idea as Open Notify / astronauts, different URL).
async function getJsonPlaceholderUser() {
  // await waits until we have data from fetch before it runs the next line. No need for callbacks 🤯
  console.log("Before we fetch data");
  const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
  console.log(
    "This is logged out after some time, even though the code looks synchronous! 🤯",
  );
  const user = await response.json();
  console.log("This is logged out after some time! 🤯");
  console.log(user);
  return user;
}

getJsonPlaceholderUser();
```

### Promise consumption

So how did the async/await example above actually work? Let's get into promises!

If you have a promise, you can call two functions on that promise. '.then' and '.catch'. When are these functions called? What does it mean that a promise is resolved or rejected?

The trainees should be able to answer these questions: // Question 1: What does it mean that a promise is resolved? Which method on a promise get called? // Question 2: What does it mean that a promise is rejected? Which method on a promise get called? // How would you explain your mom what resolved and rejected means?

```js
fetch("https://jsonplaceholder.typicode.com/users/1")
  .then((response) => response.json())
  .then((user) => {
    console.log(user);
  })
  .catch((error) => console.log(error));

// https://codesandbox.io/s/scrollto-promise-example-0gjp6
// If not working try chrome
scrollTo("section.features")
  .then(() => console.log("scrolling done"))
  .catch((error) => console.log(error));

// HAMMER in this point:
// When you have a promise you can call two functions on that promise (.then and .catch). '.then' is called when the promise is resolved. '.catch' is called when the promise is rejected.
```

### Promise creation

When you create a new promise you give it a function that has two functions as parameters (resolve and reject). Resolve is called when everything in a promise goes well. Reject is called when something goes wrong.

```js
// Start as simple as possible, no reject, just resolve!
const oneSecondTimeoutPromise = new Promise((resolve) => {
  setTimeout(() => {
    resolve();
  }, 1000);
});

// You can pass data in the resolve
const oneSecondTimeoutPromise = new Promise((resolve) => {
  setTimeout(() => {
    resolve("1 second has passed");
  }, 1000);
});

oneSecondTimeoutPromise.then((timeoutData) => {
  console.log(timeoutData); // '1 second has passed'
});

const orderPizzaPromise = new Promise((resolve, reject) => {
  const pizzaMakingTime = 10000;
  const didPizzaBakingSucceed = true;
  const pizza = "Macaroni pizza";
  setTimeout(() => {
    if (didPizzaBakingSucceed) {
      resolve(pizza);
    } else {
      reject("The pizza was a mess");
    }
  }, pizzaMakingTime);
});

orderPizzaPromise
  .then((pizza) => {
    console.log(`Let's eat the ${pizza}`);
  })
  .catch((error) => {
    console.log(`Let's eat the nothing`);
  });

// HAMMER in this point:
// When you create a new promise you give it a function that has two functions as parameters (resolve and reject). Resolve is called when everything in a promise goes well. Reject is called when something goes wrong.

// Compare function creation and consumption to promise creation and consumption
// function creation
function test() {}

// function usage
console.log(test());
```

### Back to `async`/`await`

So writing `async` in front of a function makes it return a promise! The keyword `await` makes JavaScript wait until that promise resolved and returns its result.

```js
async function getJsonPlaceholderUserSafe() {
  try {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/users/1",
    );
    const user = await response.json();
    return user;
  } catch (err) {
    throw "Fetching the user went wrong";
  }
}

const userPromise = getJsonPlaceholderUserSafe();
```

### Function that returns a promise

```js
// This example could definitely be more real world! Any ideas, make a pull request!
const promise = new Promise((resolve) => {
  setTimeout(() => {
    const tea = {
      color: "green",
      taste: "Bitter",
    };

    resolve(tea);
  }, 3000);
});

const isThereMoreTea = false;

// This example could definitely be more real world! Any ideas, make a pull request!
function makeTea() {
  console.log("Start making tea");

  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const tea = {
        color: "green",
        taste: "Bitter",
      };

      if (isThereMoreTea) {
        resolve(tea);
      } else {
        reject("We don't have more TEA!!");
      }
    }, 3000);
  });
}

console.log(makeTea());

makeTea()
  .then((returnedTeaObject) => {
    console.log(returnedTeaObject);
  })
  .catch((error) => {
    console.log(error);
  });
```


# Exercises

Work through these in order.

## Exercise 1

Using async await

1. `fetch` yes or no from this api: `https://yesno.wtf/api`. Show the answer on the page.

## Exercise 2

Using promises

1. `fetch` yes or no from this api: `https://yesno.wtf/api`. Show the answer on the page.
2. Try fetching a url that rejects e.g. `https://knajskdskj.jasdk`. Show the error message on the page.

## Exercise 3

1. Create a promise that resolves after 4 seconds. Use this promise to show the text `hello` on the page after 4 seconds.
2. Now make the promise fail by rejecting it with an error message instead of resolving it, and show the error message on the page.

## Exercise 4

Create a function that returns a promise, that you can use like this:

```js
// YesNoFail4Seconds should wait 4 seconds before it does one of the following 3 things:
// resolves with a yes
// resolves with a no
// or rejects
// Look into Math.random()
YesNoFail4Seconds()
  .then((data) => {
    // Show on the page: The answer is ${data}
  })
  .catch((error) => {
    // Show on the page: the error
  });
```

The above example show how to consume the promise using promises. Now try consume the `YesNoFail4Seconds` using async/await

## Exercise 5

Using async await

1. Fetch a user from JSONPlaceholder (for example `https://jsonplaceholder.typicode.com/users/1`)
2. After that succeeds, fetch movies using [this api](https://gist.githubusercontent.com/pankaj28843/08f397fcea7c760a99206bcb0ae8d0a4/raw/02d8bc9ec9a73e463b13c44df77a87255def5ab9/movies.json)
3. Show the movies on the page

## Exercise 6

Get the JSONPlaceholder user and the movies at the same time. Show the movies and the battery status on the page when the related promises have resolved.


# Assignment

The assignment for this week is to build a currency calculator using [this API](https://open.er-api.com/v6/latest/USD).

Deliverable: a small browser application, so the user can interact with it and see the converted amount on the page.

## Technical specifications

1. Make a request to the API and use the response to obtain exchange rates and to populate the currency dropdowns.
2. The user can enter an amount.
3. The user can choose a currency to convert from (default: EUR).
4. The user can choose a currency to convert to (default: DKK).
5. When the amount, the "from" currency, or the "to" currency changes, show the equivalent amount in the "to" currency.


# Week 4

In this session, you'll learn how to use JavaScript classes to create reusable templates for objects that share common properties and behaviors. By mastering classes and inheritance, you'll be able to organize your code more efficiently and implement object-oriented programming principles. These skills will help you write cleaner, more maintainable code and understand the differences between classes and objects in JavaScript.

## Contents

* [Preparation](/course-content/frontend/advanced-javascript/week4/preparation)
* [Session Plan](/course-content/frontend/advanced-javascript/week4/session-plan) (for mentors)
* [Exercises](/course-content/frontend/advanced-javascript/week4/exercises)
* [Assignment](/course-content/frontend/advanced-javascript/week4/assignment)

## Session Learning Goals

By the end of this session, you will be able to:

* [ ] Use **classes** to create objects with consistent structure and built-in behavior
  * [ ] Declare a class using `class`, `constructor`, and `this`
  * [ ] Instantiate objects from classes using `new`
  * [ ] Use Methods and constructors
  * [ ] Use Static methods
  * [ ] Use inheritance with `extends` and `super()`
  * [ ] Understand the difference between classes vs objects

```js
class Comment {
  constructor(username, text) {
    this.username = username;
    this.text = text;
    this.likes = 0;
  }

  like() {
    this.likes++;
    this.render();
  }

  render() {
    // data, behavior, and rendering live together
    const div = document.createElement("div");
    div.innerHTML = `
      <strong>@${this.username}</strong>
      <p>${this.text}</p>
      <button>❤️ ${this.likes}</button>
    `;
    return div;
  }
}

const comment = new Comment("alice", "Great post!");
document.body.appendChild(comment.render());
```


# Preparation

## Reading List

Read/watch through this list of content before you come to the session:

* 📖 [Classes](https://javascript.info/classes) by javascript.info (60 min)
* 📽️ [Intro to Classes](https://youtu.be/tciZZi2ZxrM) by HackYourFuture (5 min)
* 📽️ [Constructor & Methods](https://youtu.be/ZRCfNLtyO6Q) by HackYourFuture (10 min)
* 📽️ ["this"](https://youtu.be/LrQYgjIfxAU) by HackYourFuture (15 min)

Optionally, you can also strengthen some topics from previous weeks:

* 📽️ [Fetch API introduction](https://www.youtube.com/watch?v=Oive66jrwBs\&ab_channel=TraversyMedia) by Traverse Media (30 min)
* 📽️ [Callbacks, Promises, Async Await](https://www.youtube.com/watch?v=VmQ6dHvnKIM\&ab_channel=DaveGray) by Dave Gray (60 min)
* 📖 [Fetch](https://javascript.info/fetch) by javascript.info (40 min)


# Session Plan

## Session Materials

* [Demo](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week4/session-materials/demo/README.md) – In-session live coding: plain-object motivation, `Comment` class, methods, flagged comments, then Errors / Web Components as “real world” context. **index.js** = worksheet; **index-solution.js** = reference. [README](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week4/session-materials/demo/README.md).

## Session Outline

Start VERY simple. Just a class that has few fields, no methods. Explain the diff from object to class. Explain instance etc. When they get that move on to class methods. **Only teach extends if they really are on top of things** otherwise just get them comfortable with classes :) if you can repeat a bit of promise, maybe when working with class that would be great.

* Constructor
  * [Code inspiration](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week4/session-materials/code-inspiration.md#constructor)
  * [Exercise](/course-content/frontend/advanced-javascript/week4/exercises#1-create-a-user-class)
* Instance
  * [Code inspiration](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week4/session-materials/code-inspiration.md#instance)
  * [Exercise](/course-content/frontend/advanced-javascript/week4/exercises#2-create-an-instance-of-the-class)
* Methods (instance + static)
  * [Code inspiration](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week4/session-materials/code-inspiration.md#methods)
  * [Code inspiration — static methods](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week4/session-materials/code-inspiration.md#static-methods) (Promise as "you already use this")
  * [Exercise](/course-content/frontend/advanced-javascript/week4/exercises#3-create-a-class-method)
* `this`
  * Refers to the instance of the class. Do go into too much detail and edge cases. Avoid mentioning `bind`, `apply`, etc unless you find it super important, the trainees will just forget it anyway!
* [Exercise](/course-content/frontend/advanced-javascript/week4/exercises#4-creating-a-cv-class)
* Extend (Only if time!)
  * [Code inspiration](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week4/session-materials/code-inspiration.md#extending-built-ins-error-and-web-components) (`Error`, `ValidationError`, Web Components sketch — matches demo Part 4)

## Exercises

See the separate [Exercises](/course-content/frontend/advanced-javascript/week4/exercises) document.

## Code inspiration

See the separate [Code inspiration](https://github.com/HackYourFuture-CPH/program/tree/main/courses/frontend/advanced-javascript/week4/session-materials/code-inspiration.md) document.


# Exercises

Work through these in order.

## 1. Create a user class

The class should have 2 properties: `firstName` and `lastName`. Hint: Use `this` and `constructor`.

## 2. Create an instance of the class

Use the `new` keyword and assign the instance in a variable.

Add a **`renderUserCard(user)`** function that accepts a **`User`** instance and renders a user card on the page (e.g. a `div` with `firstName` and `lastName`).

## 3. Create a class method

1. Add **`getFullName`**: it should return the combined first and last name of the user. Use string concatenation or template literals and **`this`** to read the properties.
2. Add **`render()`** on **`User`**: it should render the user card on the page (same job as **`renderUserCard(user)`** in exercise 2, but as an instance method). Use **`this.getFullName()`** for the name you show on the card.
3. Call **`myUser.render()`** so the card appears on the page (you can stop using **`renderUserCard`** once this works).

## 4. Creating a CV class

The CV that we will be making uses three classes: `Job`, `Education` and `CV`. The `CV` class we have made for you (with some missing functionality). The `Job` and `Education` classes you need to create.

### Part 1

Create the classes `Job` and `Education`.

* `Job` has five properties: `id`, `title`, `description`, `startDate` and `endDate` (the dates can be strings or actual `Date` objects).
* `Education` has six properties: `id`, `title`, `school`, `address`, `startDate` and `endDate`.

```js
class Job {
  ///...
}

class Education {
  ///...
}
```

### Part 2

Now add the functionality for the methods in the `CV` class.

*Remember*: jobs and educations are just arrays of class instances. So use your array manipulation knowledge for the add and remove methods.

```js
class CV {
  constructor(email) {
    this.jobs = [];
    this.educations = [];
    //this.email = ?
  }

  addJob(job) {
    // add functionality here
  }

  removeJob(job) {
    // add functionality here
  }

  addEducation(education) {
    // add functionality here
  }

  removeEducation(education) {
    // add functionality here
  }
}
```

### Part 3

1. Create a new `CV` instance using the `new` keyword, and save it in a variable called `myCV`.
2. Apply the methods you have created on the `myCV` object. Create a few `Job` and `Education` objects and add them to your CV.
3. Remove a job and an education from `myCV`.
4. Log `myCV` to the console, again, and check that the objects were removed correctly.

### Part 4

Add a method to the `CV` class called `renderCV()`. This method should render out the CV using HTML. Make sure, that view updates, when data is changed.


# Assignment

For this week's assignment we will create a web application that generates a screenshot of a website based on a URL. We will combine two APIs: one to generate the screenshot and one to allow the user to save the screenshot.

We use [Rapid API](https://rapidapi.com/apishub/api/website-screenshot6/?utm_source=RapidAPI.com%2Fguides\&utm_medium=DevRel\&utm_campaign=DevRel) to generate a screenshot and the [crudcrud API](https://crudcrud.com/) to save the screenshot.

## Technical specifications

1. User can enter a URL for a website and it will send back a screenshot of the website using the website-screenshot API
2. User can hit a button to save the screenshot. It will then save the screenshot and the URL as a resource on crudcrud
3. User can get a list of all screenshots that they have saved
4. User can delete a screenshot that they have saved

### Class requirements

1. **Model your UI as classes** with a `render()` method that puts content on the page.
2. **Build an error system** with custom error classes that `extend Error`, each with a way to show a user-friendly message (e.g. `toUserMessage()`).
3. **Handle errors** with `try/catch` and use `instanceof` to treat different error types differently.

Look at your interface and think about what parts can be modeled as classes — if something has data and behavior that go together, or if it can be reused, make it a class. For example, you could create a `Screenshot` class that holds the URL and image data, knows how to render itself as a card on the page, and has a method for deleting itself from crudcrud.

For the error system, think about what kinds of errors can happen in your app — what if the user submits an empty URL? What if the API returns a bad response? What if the network is down? You might end up with classes like `ValidationError`, `ApiError`, or something else entirely — it's up to you.

## Optional Tasks/Assignments

> **Note:** Users do not need to be stored in a database or API — just keep them in memory (e.g. an array of instances in your JavaScript). No need to persist them anywhere.

1. Create a user object with an email and password. Keep it in a variable or array.
2. Show a login form first.
3. If the email and password match the user you created, show the application. Otherwise show an error message.
4. Create another user. When saving a screenshot, also save the user email (or another unique identifier).
5. Make sure you only show screenshots that the logged-in user has uploaded.

Keep in mind the API key for the website-screenshot and the uuid for crudcrud should be in a secret.js file which is not committed to git.




---

[Next Page](/llms-full.txt/1)

