# Course Overview

## Welcome to Fundamentals!

Coding Fundamentals is Rocket Academy's intro course in software programming, also known as coding. You will learn basic coding syntax and concepts through building simple programs. Students interested in software engineering careers can continue with Rocket's [Coding Bootcamp](https://www.rocketacademy.co/courses/bootcamp-course) after Fundamentals to build more complex applications and start on a career as a software engineering.

If you are interested in understanding what is required to attend our Bootcamp, please refer to the [Bootcamp Admission Criteria page](/course-logistics/post-course/bootcamp-admission-criteria).

{% embed url="<https://youtu.be/7Bx4LTD9guo>" %}

### What is Fundamentals About?

Coding Fundamentals aims to introduce the elements of constructing a program and thinking about how it should work in a short amount of time. This happens in a "sandbox" JavaScript environment meant to focus on the universal, fundamental concepts of programming, rather than being specific to the JavaScript language. Using project and mastery based learning it aims to incrementally level-up students' coding knowledge through fun game-based mini projects.

Ultimately, this is a tool to allow students to understand if they truly enjoy software engineering, and to serve as a tool that would allow one to make a better decision towards whether or not to further pursue a software engineering career.

### What is Fundamentals Not?

Fundamentals is focused on project-based learning, so does not cover theoretical computer science concepts. It is focused on universal programming fundamentals, so does not cover software systems or code frameworks as they are deployed in a commercial setting.


# Course Methodology

## Class Organization

Each cohort will be split into sections of no more than 20 students. Each section will be led by a section leader from Rocket, who will be the primary point of contact for that section during SWE Fundamentals. Sections are assigned randomly and fixed for the duration of the course. Students will meet with their respective sections for classes to maximise interaction and learning. Students will be able to interact with students from other sections via your community channel.

{% content-ref url="/pages/uvnUDGOnyRVSO3HSIZYK" %}
[Course Components](/course-logistics/course-methodology/course-components)
{% endcontent-ref %}

{% content-ref url="/pages/kcUyHbO0bdH1EHklvIex" %}
[Community Channels](/course-logistics/course-methodology/slack)
{% endcontent-ref %}

{% content-ref url="/pages/VKpnJhVmumN26Hf9kViE" %}
[Course Projects](/course-logistics/course-methodology/projects)
{% endcontent-ref %}

##


# Course Components

SWE Fundamentals applies a flipped classroom model that consists of 2 components: **self-learning** and **live classes**.

### Self-Learning

The goal of self-learning is for students to learn concepts **before** class, such that class time can be spent discussing those concepts. **Self-learning is mandatory**, and will consist of videos and exercises listed under the Pre-Class header.

### **Live Classes**

The objective of live classes is to enable students to gain a better understanding of the concepts learnt during self-learning through instructor facilitated discussion and pair-programming exercises.

**Live classes are mandatory.** They will be held over Zoom.

There will be 1 pre-course briefing and 12 classes in total. Each section will have their own Zoom room to meet for live classes.

Live classes will generally follow this outline:

1. 30 minutes for students to explain and review concepts with the section
2. 85 minutes of pair programming on in-class exercises with a designated peer
3. 5 minutes for students to ask any questions that they might have about the day's class, and for the instructor to preview the next class

### Pair Programming

Pair programming is a common software engineering activity that involves 2 engineers working on the same computer, on the same problem together. Typically, 1 engineer acts as the "driver", controlling the keyboard and writing the code. The other engineer acts as the "navigator", helping to guide the overall strategy and look up documentation (on a separate computer).

Pair programming is commonly used for the following purposes:

1. To share knowledge across teams or between juniors and seniors, where the navigator is typically more knowledgeable about that part of the system than the driver.
2. To ensure an important piece of software gets done correctly. Sometimes, for difficult software engineering problems with large future repercussions, it is more worth it to spend 2 engineers' time to get it right, than to spend 1 engineer's time and risk getting it wrong.

During SWE Fundamentals, we will use pair programming to solidify our understanding of concepts by coding and explaining in front of each other. The majority of class time will be spent pair programming in designated pairs that will change every live class.

## Exercise, Project Strategy

Please read through all sections of exercises and projects before starting. Later parts of exercises and projects may require different code architecture than earlier parts. **Failure to take into consideration all aspects of the project might result in a lengthy refactor.**

### Base, More Comfortable

To accommodate different learning speeds and prior experience, exercises and projects may have different sections to differentiate what must be completed to minimally understand concepts, and what are extra exercises or features to help solidify one's understanding.

#### Base

Everything in the Base section must be completed to minimally understand relevant concepts. When short on time, we can complete the Base section then move onto the next exercise or project.

#### More Comfortable

The More Comfortable section is for students that wish to push their boundaries. Students can complete SWE Fundamentals without touching More Comfortable, but students that complete More Comfortable exercises will gain more experience and may be more valuable in the job market.


# Community Channels

## Introduction

The Rocket LMS platform (rocket.disco.co) provides community channels for real-time but asynchronous messaging that should feel casual and fun. We have provided with a selection of channels, e.g. `#general` for you to keep in touch with your classmates and instructors.

### Discussion Channels House Rules

The following are a set of guidelines to follow when using discussion channels at Rocket. By setting strong culture of messaging on this platform for questions and discussion we hope to further enhance the Rocket Fundamentals experience.

### Ask Questions in the Channel

During Rocket's courses you will have questions about the material. To ensure your questions get answered soonest and so others can help and learn, please ask questions in the batch-wide or section-wide channel (including about installing required software). ***Therefore, please refrain from DMing (direct messaging) instructors with questions about course material.***

### Provide Context for Questions

To get help effectively, we need to provide context. One of the biggest differences between junior and senior engineers is the amount of relevant context they provide with their questions.

Questions **without context** usually sound like: "*It doesn't work. Could you help?*" A question with **relevant** context might be more like: "*Program A is giving me Error X. I didn't expect X to happen because of Logic B. When I googled X, it told me that this might be related to Y, but I don't see Y anywhere in the system.*"

Contextual questions help the answerer by filling in the details needed to fully understand the question. In the field of programming (not just for students) it is well known that simply formulating the question often leads directly to the answer. [This is called rubber-duck programming.](https://en.wikipedia.org/wiki/Rubber_duck_debugging)

#### How to ask contextual questions

Try to answer the following when asking questions. What is the problem? Include any relevant error messages in text or screenshots. What is your hypothesis? Include relevant code snippets. What have you tried? Include any relevant output or Google results. This will not only assist the person helping you, it will actually make you a better coder.


# Course Projects

## Project Presentations and Review

Students present projects in class on the last day of each project. Presentations should cover the following.

1. Demo
2. Biggest challenges faced
3. What they might do differently next time

In order to keep each presentation relatively brief, the presentation should be focused around the *features* of the game. The presentation is not a code review, as that would take up too much time.

## Code Review

On days when projects are due, we will review each others' code in groups of 2 or 3 during class. If there is a group of 3, the triplet will do individual code review together so that everyone gets to review someone else's code, then split into 2 groups for pairing.

### Individual Review

#### 1) Clone Partner's Code

You'll be paired up so that you can exchange the links for your repos via your community channel. Remember that the forked repo is the one that is under your GitHub account, not Rocket Academy's. If you have forked the repo but haven't pushed your latest code to GitHub, take a moment now to `git push`. Let your partner know you're updating the repo. Run a `git clone <REPO_URL> <NEW_FOLDER_NAME>` to get a copy of your partner's code.

{% hint style="info" %}
Note: You need to rename the folder when you clone if you already have a folder named after the repo where you're making the clone.
{% endhint %}

#### 2) Run Partner's Code

Open the code in the browser and test it. What does it do? If you're not sure what it does look inside `script.js` to see.

#### 3) Read Partner's Code

Read the code and answer the following questions.

1. How does it work?
2. Does it have any obvious errors?
3. Does it implement something that you were trying to do?
4. Does it implement a feature that you haven't started yet? How does the code work?

#### 4) Play with Partner's Code

It may be helpful to make changes to the code to help you understand it better. Write some `console.log` that would help you figure out what the code does. Break the code in a certain way to prove how it works or doesn't work.

#### 5) Discuss

Once both partners are done with #1-4, discuss what you saw.

### Peer Review

You'll be pair programming on one person's project at a time. The goal is to get working versions for each person. **The driver will be the person who is \*not\* working on their own code.**

Once done with one person's code, send the code to your pair (it's their project) via a code snippet. Switch to work on the other person's code.

{% hint style="info" %}
Note: If you are working on your partner's code you can't push to their repo because GitHub repos are read-only to non-owners by default.
{% endhint %}

If you both have working versions, implement a new feature in one of the projects together.


# Required Hardware and Software

To partake in Rocket's courses, we will need the following hardware and software.

## Required Hardware

1. Desktop or laptop computer running the latest version of Windows or MacOS.
2. Webcam and microphone capable of enabling video conferencing on your computer. These are built-in for most laptops.
3. Internet connection that is able to run Zoom calls with no interruptions in audio or video. If you're not sure, let us know and we can schedule a chat!

{% content-ref url="/pages/e5KsHJ1U6kitFk1EDa9z" %}
[Required Software 1](/course-logistics/required-hardware-and-software/required-software-1)
{% endcontent-ref %}

{% content-ref url="/pages/ryEJuJYTHuseggtBfqa7" %}
[Required Software 2](/course-logistics/required-hardware-and-software/required-software-2)
{% endcontent-ref %}

{% content-ref url="/pages/ZBcy8pRfBDYaSkfydpHf" %}
[Recommended Setup](/course-logistics/required-hardware-and-software/recommended-set-up)
{% endcontent-ref %}

If you have any difficulty in preparing the required software, do ask for help in the discussion channels! Your coursemates, peers and Section Leaders will be happy to help.


# Required Software 1

## Required GUI-Application Software

GUI-application software is software we run with a graphical user interface (GUI) on our operating system.

### Messaging Platform

The Rocket LMS platform (rocket.disco.co) provides community channels for real-time but asynchronous messaging that should feel casual and fun. We have provided with a selection of channels, e.g. `#general` for you to keep in touch with your classmates and instructors.

#### Onboarding

There are 2 stages to onboard a new student:

1. Join the Rocket Academy community at <https://rocket.disco.co> as a member
2. Join the Coding Fundamentals (PF1) Learning Experience product assigned to them

Once a student joins the community as a member, they can register to join the various learning products that they will be assigned to.

### Zoom

Zoom is Rocket's chosen video conferencing software for class. Each section will have its own Zoom room. The link to this room can be found at the top of each section's community channel.

#### **Installation**

1. Download the Zoom Client for Meetings [here](https://zoom.us/download).
2. Start a new meeting to test that your webcam and microphone are working.

### Chrome

Chrome is the most popular web browser for software engineers because of its mature developer tools, which we will soon see in course videos. Chrome also has the largest library of browser extensions, which further help developers build and maintain software.

#### **Installation**

1. Download Chrome for your OS [here](https://www.google.com/intl/en_sg/chrome/).

### VSCode

VSCode is the most popular code editor in the world. We will write all code for SWE Fundamentals inside of VSCode. Download VSCode for your OS [here](https://code.visualstudio.com/download).


# Required Software 2

## Required Command-Line Software: Git

### Intro to Git

Command-line software is software primarily operated from the command line (we will explain this in a video) that may not have a graphical user interface we can interact with. This software is typically used by software developers to write programs. Command-line software is not stored in a computer's Applications folder. We'll cover [more about the command line in 1.3.](/1-introduction/1.3-command-line)

Git is the most popular software version control system. All tech companies use version control to manage contributions to and releases of their software. We will be using basic Git during CodiSWE Fundamentals to download and upload copies of projects. We'll cover more about Git in [Module 7](https://github.com/rocketacademy/basics-docs/blob/main/course-logistics/required-hardware-and-software/broken-reference/README.md).

On Windows, Git installation also enables us to run our terminal in the Bash programming language. The terminal is the program that allows us to run commands (and command line software) on our computers. Bash is a terminal language used across OSes, allowing us to run commands on our computers in the same way on both Windows and Mac. A version of Bash called Zsh (pronounced "zoosh") is installed by default on MacOS.

{% hint style="warning" %}
***When copying any commands from the Git website, do not copy the dollar sign ($) in front of the command.*** The dollar signs in their commands denote the start of command lines, and are not part of the commands.
{% endhint %}

### **Git - Installation**

#### Installing Git for Mac OS

1. Download and install Git for Mac OS by downloading it here: <https://sourceforge.net/projects/git-osx-installer/>
2. Verify Git is installed by running `git --version` in the [VSCode terminal](https://code.visualstudio.com/docs/editor/integrated-terminal). This should print out a version number on the next line, e.g., `git version 2.28.0`.
3. Download and install the [Git Credential Manager.](https://github.com/git-ecosystem/git-credential-manager/blob/release/docs/install.md)

{% hint style="warning" %}
To install the Git Credential Manager you may need to allow "unidentified developer apps". (*But don't worry, Git Credential Manager is created by Microsoft*) from instructions [here:](https://support.apple.com/en-sg/guide/mac-help/mh40616/mac)

**To override your security settings and open the app, follow these steps:**

1. *In the Finder* ![](https://help.apple.com/assets/605932B4A1B7A93F492858E8/605932C0A1B7A93F492858FF/en_US/058e4af8e726290f491044219d2eee73.png) *on your Mac, locate the download file.*
2. *Control-click the app icon, then choose Open from the shortcut menu.*
3. *Click Open.*\
   \_\_

   *The app is saved as an exception to your security settings, and you use it in the future just as you can any registered app.*\
   \_\_

Note: If you are using a company computer for this course you may not be able to override the security settings- you may need to [create a personal token as described here.](https://docs.github.com/en/github/authenticating-to-github/keeping-your-account-and-data-secure/creating-a-personal-access-token)
{% endhint %}

#### Installing Git for Windows

1. Navigate to the Git website download page and click the download link: <https://git-scm.com/download/win>
2. Open the downloaded file.
3. The Git install dialog will open. We'll need to set a few options here. The rest will be the default options.
4. Follow [command line setup instructions below](#vscode-settings) to set Bash as the terminal language.
5. Verify Git is installed by running `git --version` in the [VSCode terminal](https://code.visualstudio.com/docs/editor/integrated-terminal). This should print out a version number on the next line, e.g., `git version 2.28.0`.

{% embed url="<https://www.youtube.com/watch?v=7Dq_e90LqTU>" %}
Dialog Options: (just click ***next*** for default options)
{% endembed %}

## VSCode Formatters

### Prettier

Prettier is a code formatter that will auto-format our code and make it more readable when we save our files.

1. Install the Prettier extension for VSCode [here](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode).
2. Restart VSCode to activate Prettier.

### VSCode Formatting Settings

1. Open VSCode and open the command prompt with `Ctrl+Shift+P` on Windows and `Cmd+Shift+P` on Mac.
2. Start typing `Preferences: Open User Settings (JSON)` and select this option when you see it in the search dropdown. A JSON settings file should open in VSCode.
3. Replace everything on the screen (in the file) with the code below.
4. Save the settings file.
5. Restart VSCode to apply our settings.
6. Open and save the settings file again and verify that Prettier auto-formats it as our default formatter.

###

### VSCode Settings

{% tabs %}
{% tab title="Mac OS" %}
**VSCode Settings - Mac OS**

```
{
	"editor.formatOnSave": true,
	"editor.formatOnPaste": true,
	"editor.minimap.enabled": true,
	"editor.tabSize": 2,
	"editor.wordWrap": "on",
	"editor.defaultFormatter": "esbenp.prettier-vscode"
}
```

{% endtab %}

{% tab title="Windows" %}
**VSCode Settings - Windows**

{% hint style="warning" %}
Windows users: The following code assumes we installed our Git folder at the root of our C drive. Some students' installers install the Git folder elsewhere, for example in `C:\\Program Files (x86)`. You should have noted the installation location of Git when you installed it, as per the instructions above.

If your installed Git folder is not in the location as listed below, please edit line 8 and 12 to the appropriate values when you copy these configurations.
{% endhint %}

```
{
	"editor.formatOnSave": true,
	"editor.formatOnPaste": true,
	"editor.minimap.enabled": true,
	"editor.tabSize": 2,
	"editor.wordWrap": "on",
	"editor.defaultFormatter": "esbenp.prettier-vscode",
	"terminal.integrated.defaultProfile.windows": "Git Bash",
	"terminal.integrated.profiles.windows": {
		"Git Bash": {
			"path": "C:\\Program Files\\Git\\bin\\bash.exe",
			"icon": "terminal-bash"
		}
	}
}
```

{% endtab %}
{% endtabs %}

## Required Software Accounts

### GitHub

GitHub is the most popular code-hosting platform. Developers around the world use GitHub to share code and collaborate on projects. Rocket Academy's starter code and project templates are hosted on GitHub, and we will use GitHub in SWE Fundamentals to download, host, and submit assignments. Each student will need a GitHub account to host and submit assignment code.

#### **Sign Up**

Go to [https://github.com/](https://github.com), click the Sign Up button and follow on-screen instructions.

#### **Git and GitHub Credential Configuration**

Add your GitHub account credentials to your computer through the command line. Please replace `<YOUR_GITHUB_USERNAME>` AND `<YOUR_GITHUB_EMAIL>` with your own GitHub user name and the email you used to sign up to GitHub with. *Note to replace the* `<>` *characters and keep the* `"` *characters in the commands.*

```
git config --global user.name "<YOUR_GITHUB_USERNAME>"
```

```
git config --global user.email "<YOUR_GITHUB_EMAIL>"
```

#### Configuration Check

You will not get any feedback from the terminal after entering these commands.

Type the following command into the terminal to check your work. If you see a `:` at the bottom of the output, you may need to press `Enter` until you see the lines starting with `user.name` and `user.email`.

```
git config -l
```

You should see your username and email in the output, and possibly some other settings.

#### Git default branch configuration

Following the convention of all the other Rocket Academy Git repositories and GitHub, we'll change the default Git branch name by typing in the command shown in the code box.

```
git config --global init.defaultBranch main
```

## Exercise: **Send Your First Community Channel Message!**

### **Introduction**

*Once you have been added to a section in the Community Channel*, send your first message to your new section mates. Please include the following in your message:

1. Where are you based?
2. What do you do for work?
3. Why do you want to learn coding?
4. 4 emojis that describe you
5. Your specific OS version. This will be the result of running the command below for your specific OS (Windows or Mac)
6. Anything else you would like to share 😁

<img src="/files/-Mh35F9BTDHAK1QH_bg_" alt="Slack Message from Kai" data-size="original">

### Retrieve Your OS Version

These commands are for the intro above. Don't worry about exactly what's happening in these commands yet. This exercise is just to get you started with typing in the Command Line interface and sending community channel messages. We'll learn more about the command line in [1.3 Command Line.](/1-introduction/1.3-command-line)

#### Windows

```
cmd /c ver
```

#### Mac

```
sw_vers
```


# Recommended Setup

## Folder Structure for SWE Fundamentals

In SWE Fundamentals we will be creating many folders and cloning the starter code multiple times. To keep our code organised, we recommend the following folder structure.

{% hint style="info" %}
All code-related files and folders are in kebab case (hyphenated and lowercase), e.g., `file-name.txt` , for ease of use on the command line. It is generally a bad idea to name any files or folders with a space in them, e.g., `file name.txt` , because spaces need to be escaped with backslash (`\`) on the command line.
{% endhint %}

1. Host all SWE Fundamentals code in a folder called `fundamentals`. Keep this in your `Documents` folder.
2. Within the `fundamentals` folder, for each class session (there are 12 total) in SWE Fundamentals, create a new folder for that day. This means you will have 12 day-specific folders, such as `day1`, `day2`, ..., `day12`.
3. Within each `dayX` folder, create 1 folder for pre-class exercises and another folder for in-class exercises. These can be named `pre-class` and `in-class`, or any other naming scheme that works for you.
4. Within `pre-class` and `in-class` folders, keep a separate folder for every exercise you do that requires you to create a new Git repository or clone a new copy of the SWE Fundamentals starter code.

{% hint style="info" %}
As a shortcut, we can run the following command in the terminal to create all the folders.

1. Open the `Documents` folder in VSCode with File > Open Folder and choose `Documents`.
2. Run the following command in the terminal of VS Code.

{% code overflow="wrap" %}

```bash
 mkdir -p fundamentals/day{1..12}/{in-class,pre-class}
```

{% endcode %}
{% endhint %}

{% hint style="warning" %}
When cloning the starter code, choose to [name the target folder](/8-github/8.1-intro-to-github#git-clone) to the relevant exercise name. This is so that we do not end up with Git repositories within Git repositories, which can confuse Git and cause issues.
{% endhint %}

![Sample Fundamentals folder in Finder on MacOS](/files/-MUlurtBBcGdkwrUluwO)

### OneDrive

On Windows computers it may not be clear where a given folder is. Some Windows computers are setup to default to the OneDrive cloud folder. This can be double checked by clicking on the window path location arrow at the top of the window to see the full file location path.

{% hint style="warning" %}
**Don't put your Fundamentals folders in OneDrive.** This makes it harder to access them from the command line.
{% endhint %}

![How to see the full file path of a folder in Windows.](/files/-Mdfm-BTIBjSHCJYupxG)

### Open fundamentals Folder in VSCode

When working with code, it's often necessary to switch between different files in the same repository, or even across repositories. Instead of using File > Open to open a specific *file* each time, we can save time by opening the *folder* that contains all the files we may want to access. We can do this on Windows by going to File > Open Folder, or on Mac with File > Open, and selecting the relevant folder. This will open the folder and its file structure in the VSCode sidebar, allowing us to switch quickly between files in that folder without having to File > Open every time.

{% hint style="info" %}
For SWE Fundamentals, we recommend storing all of your code in a folder called `fundamentals` as per the recommended folder structure above, and keeping that folder open in VSCode for the duration of the course.
{% endhint %}

![Sample Fundamentals folder in VSCode](/files/-MUlv8-zZBZZLStoYsPD)

## Window-Snapping Software

On both Windows and Mac there are features to snap windows to standard sizes and places on our screen using keyboard shortcuts. This is especially helpful when coding and we want to view code on one side and documentation on another. The alternative is to manually drag windows and resize them.

![Windows built-in snapping tool](https://i.gifer.com/Ffgu.gif)

**Mac Installation**

Window snapping is not built-in to MacOS, and we will need to download an external program to snap windows. We recommend any of the following.

1. [Rectangle](https://rectangleapp.com) (free) is an actively-maintained open-source window snapping app. We recommend this to start.
2. [Magnet](https://magnet.crowdcafe.com) (S$10.98) is an actively-maintained window snapping app on the Mac App Store. It mostly has the same features as Rectangle, and might be more user-friendly because it's managed through the App Store. From what we can tell, it serves the same function as Rectangle.


# Schedule

Click on the following [link](https://rocket.disco.co/p/coding-fundamentals-pf1/events/upcoming) for the latest schedule for your cohort.


# Tips and Tricks

{% content-ref url="/pages/-MFuu46qRY76qxOrDmE9" %}
[Coding Strategies](/course-logistics/tips-and-tricks/coding-strategies)
{% endcontent-ref %}

{% content-ref url="/pages/-MElRTdiWrIt6Byv0anf" %}
[Tooling Pro Tips](/course-logistics/tips-and-tricks/tooling-pro-tips)
{% endcontent-ref %}


# Coding Strategies

## Getting Started / How to Break a Problem Down

{% embed url="<https://www.youtube.com/watch?v=wO2CSWgf1Xw>" %}

One of the biggest challenges when beginning a project is to know where to start.

There are two main aspects to this process:

### 1) Understand your problem using language.

* Do you understand the problem from a programatic perspective?
* Do you understand what its purpose is?
* Do you understand the logic of the application itself?

### 2) Strategize which part to concentrate on

* Start with the beginning of the program first.
* Start with the "Minimum Viable Product"
* Leave aside the features of the overall program that are not core to its purpose.
* Strategize about how you can fake other parts of the program. (Can you fake a random dice roll by starting with a value that is always 4?)

### 3) Translate the problem into the appropriate JavaScript syntax.

**Processes and logic require control flow.**

* Does your program repeat itself? Maybe you need a loop.
* Does your program have logic? *If this then ....* You might need a conditional.

**Data requires variables and data types.**

* Does your program do math? You need number types.
* Does your program have a set or list? Is that list ordered? You might need an array.

## Building Mental Models

{% embed url="<https://www.youtube.com/watch?v=C7zIy38my94>" %}

A program is a sum of its parts.

A modern computer system is incredibly complex and it's impossible to understand what goes on at every level.

*(See this description of* [*what happens when you search on google)*](https://github.com/alex/what-happens-when).

***However*** the task of writing a program is to build a contextually complete mental model of what is happening when the program runs.

This means understanding things about the code and how it behaves in the system.

You need to understand what a loop does, but also that it won't run unless you click 'refresh' on the browser.

Strategies around how to methodically build and test your mental models are an important meta-skill when building a program and when learning a new system.

### Mental Model Building Strategies

**Run your code often.**

Before you write any code strategize about what the next smallest bit you can write, *in order to run it as soon as possible.*

**Write code with the purpose of testing your hypotheses.**

Your mental model is one of the most important things you are building as you build the program. (Just as important if not more important than the program itself). You are the one using your personal knowledge to encode the behavior of the code. If you don't understand how it works, no one else will either.

Don't write code in order to fix your errors, write code to prove or disprove your hypotheses, then write correct code.

**Use `console.log` to understand your code's behaviour.**

* Use it to check control flow.
* Use it to check values.

## Learning Strategies

{% embed url="<https://www.youtube.com/watch?v=ax7Yf1RcEns>" %}

**Mental models are the key to building your computational thinking skills.**

Use each error as an opportunity to understand the system better. (But also know when to strategically move on - you won't achieve perfect knowledge - see "what happens when" link above).

**Expect lots of errors.**

Errors are the practice and process of programming. Use them to learn more. Be playful with the system and don't be afraid to break things.

**Formulate questions**

Practice asking questions when you are working on a problem.

* What have you tried?
* What is the context of the error? When do you see it, what is the incoming data and how does it affect the output?
* What do you think is happening based on the facts?

*(Note that this doesn't mean that during this course a question like- "I dunno what's happening." is not acceptable. Any question is acceptable).*

**Talk to yourself. -This is called**[ **rubber duck programming**](https://rubberduckdebugging.com)**.**

## Pro Tips

{% embed url="<https://www.youtube.com/watch?v=IYDRNvVP0w0>" %}

Optimize your programming and learning process by implementing some best practices.

### Know your tools.

Fluency at moving between the different dev tool applications means that you have a better chance of following a thought about the code all the way through.

Your goal should be to build a fluid, distraction free coding environment. Learn keyboard shortcuts. Be able to turn off notifications. Don't attempt to watch a movie while coding.

If you need to look at a different variable in the console, be able to switch back to the editor, save the change and be looking at it in the browser in only a few keystrokes. It gives the best chance that you move ahead through the process.

This also means that when you break something that you are not afraid you'll be able to put it back. Know how to use undo. Know how to use Git and GitHub to retrieve old versions in case you need to restore something.

### Practice googling.

The skill of finding contextually appropriate knowledge about something is a key skill in moving forward with programming. Some of these things are obvious but the subtleties of finding the correct information is a skill that takes some practice if you're no used to it.

#### When searching you must learn:

**The appropriate combination of keywords in the spectrum of general to specific.**

Too few keywords and you won't find an exact match. Too many and there may not be enough results.

**When to google an exact error message and when it's not helpful.**

Similar to above, googling some types of error message will yield an exact solution. Some won't.

**Which sites to look for in the results and which to discard.**

Some sites deal in specific documentation. Others are how-to-guides for beginners.

**Know exactly what level of detail you are looking for.**

Google searches can quickly take you to the most verbose, complete technical documentation on a given subject. A lot of the times you need information that is more prescriptive than that.

**Know when a solution that is not an exact match is adaptable or not.**

Don't spend a lot of time on a result that is not relevant enough to your problem, but don't disregard a solution because it is not a perfect match to your problem.

## Deliberate Practice

Learning to code is less like learning things like English and history, and more like learning the piano. There is some theory involved but it also heavily involves practice.

[Deliberate practice](https://en.wikipedia.org/wiki/Practice_\(learning_method\)#Deliberate_practice) means quality of hours over quantity. (Although mastery also involves quantity of hours).

Many of the principles stated above have to do with your meta-awareness of your own process. We believe that the more awareness you have of your own process the more effective your learning will be.


# Tooling Pro Tips

Tips for using programming tools

## Using VSCode Effectively

### Comment Out Multiple Lines at Once

Sometimes we wish to enable or disable certain segments of our code for quick testing. The easiest way to do this is to "comment out" the code we want to disable by turning it into comments, making our JavaScript runtime ignore those lines of code.

Rather than adding `//` to the start of each line manually, VSCode has a shortcut that allows us to comment out multiple lines simultaneously. To do this, select all lines we wish to comment out, then use the keyboard shortcut `Ctrl+/` on Windows, or `Cmd+/` on Mac.

### Editing a Variable Name in Multiple Places Concurrently

Sometimes we want to change the name of a variable in our code, a common practice in [refactoring](https://en.wikipedia.org/wiki/Code_refactoring). If that variable is used in multiple places, we may be tempted to edit each instance individually. Luckily VSCode has a convenient feature that allows us to edit all instances of the same variable simultaneously, saving time and our fingers.

#### Within a Single File

1. Move your cursor to the first instance of the variable
2. Press/hold `Ctrl+D` on Windows or `Cmd+D` on Mac until all instances of that variable are selected
3. Use left or right arrow keys to enable cursors on each instance of that variable and edit them simultaneously

#### Across Multiple Files

VSCode has a [search and replace feature](https://code.visualstudio.com/docs/editor/codebasics#_search-across-files) that allows us to edit all instances of a given string in multiple files at once.

### Hide Minimap

The [VSCode minimap](https://code.visualstudio.com/docs/getstarted/userinterface#_minimap) is displayed by default in VSCode to show one's vertical position within a file. This may not be necessary in SWE Fundamentals and we can hide the minimap for more space in VSCode. Hide the minimap by toggling View > Show Minimap in the menu bar.

## Troubleshooting the Terminal Editor

> Hi everyone, in the event you accidentally type `git commit` without the ‘-m’ option, you’ll notice that your terminal changes slightly and you realise you can’t type anymore. That is because a commit message is compulsory. So, by default, your terminal will open something called VIM - its a type of text editor that is not exactly user friendly, and expects you to type your commit message.

1. How to get out of VIM:
2. You have to enter something called a command mode simply by pressing the escape key
3. type the following: `:q!`
4. the above characters should appear at the bottom of your terminal as you are typing
5. Then hit enter

2\. How to change the default editor to VSCode instead

1. run the following command on your terminal (you can run this command regardless of what folder you may be in): `git config --global core.editor "code --wait"`
2. This basically configures git to make VSCode your default editor should you ever forgot to use the ‘-m’ flag when committing.
3. If you ever do forget to use the ‘-m’ flag, a normal text file will open automatically on VSCode and you can simply type your message in that file and then close it.

> Don’t worry if this doesn’t make sense now(: But feel free to use this as a reference if you ever face that issue!

## Watching YouTube Videos at Different Speeds

If the course videos are too fast or too slow for you, you can watch them at slower or faster speeds by [toggling a speed setting in YouTube](https://support.google.com/youtube/answer/7509567?co=GENIE.Platform%3DDesktop\&hl=en) or you can use the [Video Speed Controller Extension](https://chrome.google.com/webstore/detail/video-speed-controller/nffaoalbilbmmfgbnbgppjihopabppdk?hl=en)

##


# Post-Course

{% content-ref url="/pages/-MHBsuc\_gqFedi4axWPS" %}
[LinkedIn Certificates](/course-logistics/post-course/linkedin-certificates)
{% endcontent-ref %}

{% content-ref url="/pages/A3HO0waecIyRVistLizk" %}
[Bootcamp Admission Criteria](/course-logistics/post-course/bootcamp-admission-criteria)
{% endcontent-ref %}


# LinkedIn Certificates

👩‍🎓👨‍🎓

At the end of SWE Fundamentals, you will be eligible to add the course as a certification in LinkedIn. Here are instructions on how to add that certificate to your LinkedIn profile.

## 1. Go to your LinkedIn profile page and click "**Add profile section"**

![](/files/-MXAp-gsp2Ul-cYLjs4V)

## 2. Click "Licenses & Certifications" to add a new certificate

![](/files/-MU8EK1JFHyLKB1XfO1z)

## 3. Fill in the course name, organisation, \*\*\*\* issue date, and URL

1. Name
   1. Coding Fundamentals
2. Issuing Organization
   1. Rocket Academy
3. Check "This credential does not expire"
4. Issue Date
   1. Your Coding Fundamentals graduation month, e.g. July 2023
5. Credential URL
   1. Your section leader will generate a unique URL for your certificate. Please let us know if you don't have one!

![](/files/-Mdf8-eVp7AAoTJTV4oe)

## 4. Admire your hard-earned certification 🚀

![](/files/-Mdf87C1gya_PaGcE6w5)

![](/files/-Mdf8plPghDnuyOn5Jhk)


# Bootcamp Admission Criteria

**TLDR:** Application form for bootcamp is here:(<https://rocketacademy.typeform.com/bootcampapply>)

The knowledge taught in Coding Fundamentals are pre-requisite for entrance into Rocket Academy's Bootcamp.

Section leaders can share feedback with students each class on their progress if you ask. By the end of Fundamentals, students should be aware of their ability to enrol in the Bootcamp.

The criteria to pass coding Fundamentals and join Bootcamp are the following.

1. **Completion and submission** of the 3 projects in SWE Fundamentals
2. Demonstrated improvement between each of the 3 projects based on section leader feedback
3. Understanding of all core concepts acquired in Coding Fundamentals

The application process will be as follows:

1. An application found [here](https://rocketacademy.typeform.com/bootcampapply), which would link you to our official application form
2. A small multiple choice quiz to ensure you have picked up and understood the core concepts from Coding Fundamentals
3. When passed, an interview will be scheduled with our admissions team. It is best to take part in this interview on a laptop as there will be a small coding component to it.

Through the above criteria, Rocket is essentially asking the question: Would I hire this person as a software engineer if I had their attention for 4 months full time or 8 months part time to teach them coding. If the answer is yes, welcome to Bootcamp! If the answer is currently no, let's have a conversation and see how we can help you get where you want to be!

We look forward to seeing your application soon!


# 1.1: What is Coding?

## Learning Objectives

By the end of this lesson, you should be able to:

* Explain what coding is in your own words.

## Introduction

{% embed url="<https://youtu.be/8xy4TP3quSo>" %}

Coding is the act of writing computer code to form a computer program.

The process of coding includes:

1. Translating a set of input data into a set of abstractions inside a computer
2. Defining what operations the computer performs on that data
3. Determining what output the computer gives and the representation of that output

At their core, all programs, small and large, boil down to this: ***instructions*****&#x20;to a computer to process an input and give an output**.

## History

![The ENIAC being programmed. The first-ever programmers were a team of 8 women.](https://cdn.mos.cms.futurecdn.net/2Hjzmh4vVRAHaGCEoBaAE-970-80.jpeg) ![Instructions to a computer.](https://upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Blue-punch-card-front-horiz.png/440px-Blue-punch-card-front-horiz.png)

The first programmable computer was the [ENIAC](https://www.britannica.com/technology/ENIAC). It was built to ***compute*** ballistic trajectories for artillery firing tables in WWII. It did not have a screen, keyboard or mouse; It took in input in the form of [punch-cards](https://en.wikipedia.org/wiki/Punched_card_input/output).

Computers have come [a long way](https://www.livescience.com/20718-computer-history.html) since then, and we now have keyboards, screens, touchpads and voice control, but computers fundamentally have not changed. They take in input, manipulate data, and return some output. Computers, unlike humans, do exactly as they are told. And unlike humans, computers [cannot make sense of context](https://youtu.be/Ct-lOOUqmyY?t=17), or infer what to do. Writing instructions to a computer requires you to be logical and precise.

![](https://preview.redd.it/qszkl08hx9261.jpg?width=640\&crop=smart\&auto=webp\&s=d8badec3e85d21c8650271d63bc310936e3e15f8)

## Exercise Questions

1. What are 3 examples of software you use frequently that you do not access through your phone, tablet, or laptop?
   1. Examples: An ATM, your microwave, the lift.
2. How do you give input to this software, how does it give you output?
3. Define what that input is, what the output is, and what each software is responsible for.


# 1.2: Web Browsers

## Learning Objectives

By the end of this lessons, you should be able to:

* Explain what a web browser is in your own words.
* Explain what role browsers play in this course, and why we use them.
* Make simple edits to a HTML file and see those changes reflected in your browser.

## Introduction

{% embed url="<https://youtu.be/K7zGrnQ2XOk>" %}

## Web Browser History

The World Wide Web and web browsers were born in 1990 when Tim Berners-Lee invented a way to view HTML documents through the Internet.

![https://webfoundation.org/about/vision/history-of-the-web/](/files/-METEYvIdy8XMUhZCwAN)

## What is a Web browser?

A web browser is a program used to view and interact with web pages. A web browser is a purpose-built application; just like Windows Media Player or iTunes are built to handle audio or video files, web browsers are built to handle HTML and related files.

A web browser is used to *browse* for files on the *web.* If we abstract "the web" as just computers connected together, a browser fundamentally browses files on computers. You can browse files on your own computer by typing `C://` or `file://` in the browser navigation bar for Windows and MacOS, respectively.

When you visit YouTube to watch a video, you are *browsing* to a connected computer which has the video you want saved into memory.

### Why learn about web browsers?

In Coding Fundamentals we will use browsers as a learning tool to visualize inputs and outputs of our code through web pages. **In general, web browsers are not necessary for writing and executing code.**

## HTML

We will very briefly touch on HTML and what how web browsers process them, and dive deeper into HTML later on.

HTML stands for HyperText *Markup* Language. An HTML file is simply a text file, you can open HTML files with notepad or other simple text-processing applications. Markup means that the text is presented to the user as more than just plain text: it involves structure and formatting. Almost all websites are rendered using HTML. Browsers were invented to download and render HTML on computers. HTML is **not** a programming language, but it can easily work with JavaScript, which is a programming language.

The programs we will build in Coding Fundamentals will rely on HTML to accept inputs and visualize outputs. The programs we will build will be written in JavaScript.

![](https://internetingishard.netlify.app/html-markup-0761f7.562e8e23.png)

## Exercises

### Run Starter Code in Browser

1. Download a compressed ZIP file from [this link](https://github.com/rocketacademy/swe101-starter-code/archive/main.zip).
2. If you haven't already, create a `fundamentals`folder in a local folder, e.g. `Documents`.
3. Move the downloaded .zip file to the `fundamentals` folder.
4. Unzip the file - it should create a new `fundamentals-starter-code` folder. The starter code files are in this folder.
5. Open the `index.html` file in Chrome. Double click it if Chrome is your default browser. Or, you can right click to open in Chrome.

### Change HTML Text on Page

1. Change the text of the button on line `72`. Again save and refresh the page in Chrome, and notice how the button text changes.
2. Change the word `Fundamentals!` on line `62` to something else. Save the file and refresh the opened `index.html` file in Chrome. Notice how the text changes.
3. Open the `fundamentals` folder in VS Code. We can open the whole folder instead of a specific file, which will allow us to open multiple files within that folder easily. In the left sidebar of VS Code, select the file `fundamentals-starter-code/index.html` to open it. See video above for an example.


# 1.3: Command Line

## Learning Objectives

By the end of this lesson, you should be able to:

* Face the command line without fear
* Describe what the command line is.
* Open the command line on your computer.
* Use the command line to navigate directories and display directory contents.
* Use the command line to create a new directory and a new file.
* Use the command line to rename or destroy a directory and a file.
* Use the command line to open a file or folder in a program.

## Introduction

{% embed url="<https://youtu.be/iRnFyFMvH1o>" %}

## What is the Command Line?

The command line is the interface to the computer that consists of only text characters. We will use the command line to navigate our filesystem and run the Git version control system on our code.

{% hint style="warning" %}
If you are a Windows user, please use the VSCode terminal with **Bash** installed by default. The Windows Command Prompt runs PowerShell by default which is not compatible with Unix-based commands that we need for SWE Fundamental and coding in general. See the [Windows Command Line Setup for details](https://fundamentals.rocketacademy.co/course-logistics/required-hardware-and-software/required-software-2#windows-command-line-setup).
{% endhint %}

## What will we be using the command line for?

In SWE Fundamentals, we will primarily use the command line to work with our version control program, Git. In this course we will practice using the command line as an everyday tool to replace simple file actions like name, copying and deleting, before moving to exploring the fundamentals of Git and GitHub.

Don't worry if the command line seems hard to use and mysterious right now, it will become more familiar through practice. It is also a topic that is tangential to our core computational thinking material. Don't worry about mastering this section before moving on.

## Terminology

The terms "**command line**" and "**terminal**" are synonymous. We will be using them interchangeably. The "terminal" used to refer to hardware when computers were the size of rooms, but has since lost it's original meaning.

We normally work with "**folders**" inside of our graphical windows. The Unix term is "**directories***".* For our work in the command line, both are correct.

## Common Commands

We will cover the commands that mimic the kinds of file and folder manipulation tasks you would accomplish through clicking and dragging in a graphical user interface.

At any time you can press the `tab` key and the command line will try to auto complete for you. This works for the names of commands and also longer file or folder names.

### pwd (Present Working Directory)

Your command line window already has a "location". See the "**absolute**" path of that location with `pwd`.

```
pwd
```

### ls (List)

See the files in your current directory. `ls` accepts a Unix path argument (denoted below as `<path>`). If we leave it blank it means `.`, or the current Unix directory.

```
ls
```

### cd (Change Directory)

Move your current directory. Running `cd` without an argument is equivalent to `cd ~`, or "`cd` to the home directory".

```
cd boating/sails
```

### touch

Create a plain text file. A plain text file is one that only contains characters. You can't `touch` an image file or a Word Document file.

Working with files is easier in the command line if their names don't have spaces in them. If you want two words in your file name, separate them with a dash.

```
touch my-filename.txt
```

### mkdir (Make Directory)

Create a directory

```
mkdir skateboards
```

### cp (Copy)

Copy a file

```
cp sails.txt new-sails.txt
```

Copy a folder

```
cp -R boat-folder yatch-folder
```

### mv (Move)

Move a file or folder

```
mv old-folder/cats.txt new-folder
```

Rename a file or folder

```
mv cats.txt my-cats.txt
```

{% hint style="info" %}
Windows users may encounter a "Permission denied" error when moving or renaming files or folders with `mv` that are currently open in VSCode. If this happens, please try to move or rename your files and/or folders using other means.
{% endhint %}

### rm (Remove)

{% hint style="danger" %}
Your removed files **DO NOT** go to a trash bin. **Removing is irreversible.**

**Never, ever, ever** try to run a command that removes the `root` directory (`/`).

A rule of thumb is to be careful and double check what you're doing when removing folders.
{% endhint %}

Remove a file

```
rm my-friends.txt
```

Remove a folder

```
rm -r my-boat-folder
```

## Special Paths

There are a few special characters that stand in for locations in "**relative**" paths.

The folder that contains all your other folders on your computer. On Windows, this is the `C:\` drive.

```
/
```

An absolute path always begins with the root directory.

```
cd /Users/susan/Documents/boating
```

### Home

The home folder of your login user

```
~
```

Go to your current login user's home folder.

```
cd ~
```

### Current Directory

The directory you're currently in

```
.
```

Copy something into the directory you're currently in.

```
cp ~/my-report.txt .
```

### Parent Directory

The directory one level above your current directory

```
..
```

Move from the current location to the current location's parent directory

```
cd ..
```

## Command Line Options

Almost every command has options you can add, like `-R` with `cp` . If you want to see all the options available, try `man` or adding `--help` at the end of a command. For `man` and `cp` it would be `man cp` . Press `q` to get out.

If you want to accomplish something specific on the command line, googling for a specific combination of options usually works. Googling unix commands usually requires putting "unix command" in front, as in: "unix command ls" instead of just "ls" .

## Troubleshooting the Command Line

The command line has many different sub functionalities. If you get lost here are a few tips.

#### q (Quit)

There are certain interfaces that bring us into a page navigator, like the command for help with commands, `man`. `man` tells us how to use Unix commands. You use it by typing something like `man ls` - tell me about the `ls` command. It will change the interface to a page interface that you can navigate with the up and down arrow keys ↑↓. To get out of this interface, press `q` to quit. Some Git commands also bring you into this interface, such as `diff` and `log` which we'll see in the next section.

#### Ctrl+C

Many command-line interfaces run programs that can be exited with `Ctrl+C`, which sends an [interruption signal](https://en.wikipedia.org/wiki/Control-C) to the program in the foreground. On a Mac, this is still `Ctrl` and not `Cmd`.

## Cheat Sheet

Current directory

```
pwd
```

Contents of current directory

```
ls
```

Change directory

```
cd
```

Make an empty text file

```
touch script.js
```

Copy a file

```
cp cakes.txt cupcakes.txt
```

Copy a folder

```
cp -R pastries new-pastries
```

Move or rename a file or folder

```
mv dogs.txt pets.txt
```

Remove a file

```
rm donut-list.txt
```

Remove a folder

```
rm -r my-boats
```

## Pro Tip: Tab Complete

Use the `tab` key on your keyboard to auto-complete partially-typed file or folder names. This can save us a lot of typing!

## Windows OneDrive

There have been some issues with Windows OneDrive making it harder to locate files and folders. If a folder or file cannot be found, it may be in OneDrive. Don't create files and folders in OneDrive. See [the screenshot here.](/course-logistics/required-hardware-and-software#onedrive-windows-only)

{% hint style="warning" %}
The Command Line interface is a deep topic. We are only covering a tiny portion of the subject in Fundamentals to give a small look into the world of developer workflow, and so that we can start using the Git version control system. Don't worry if you don't understand everything! For now we're focused on specific actions within the total Command Line interface.
{% endhint %}

## Exercises

Follow along with the video or attempt the commands above. See your results in a GUI window in MacOS's Finder or Windows Explorer.

{% hint style="success" %}
The command line interface can do everything a GUI window can do, but don't necessarily reflect each other. Remember that `pwd` and `ls` are the commands that will tell you the current state of the command line at any time.
{% endhint %}


# Additional Resources 1

For the curious and the hungry

## Introduction

If you'd like to learn more, this page contains a non-exhaustive, unordered list of useful resources. These resources are primarily related to Module 1, but also expand the scope of what has been covered, and touch on concepts and fundamentals that we will cover in future modules. You will see some of these resources repeated in other pages.

## Learning

1. [Things I Wish Someone Had Told Me When I Was Learning How to Code](https://www.freecodecamp.org/news/things-i-wish-someone-had-told-me-when-i-was-learning-how-to-code-565fc9dcb329/)
2. [Learning to Code: When It Gets Dark](https://www.freecodecamp.org/news/learning-to-code-when-it-gets-dark-e485edfb58fd/)
3. [Sal Khan: "The Learning Myth: Why I'll Never Tell My Son He Is Smart"](https://www.khanacademy.org/college-careers-more/talks-and-interviews/talks-and-interviews-unit/conversations-with-sal/a/the-learning-myth-why-ill-never-tell-my-son-hes-smart)
4. [How to Be Great at Asking Coding Questions](https://medium.com/@gordon_zhu/how-to-be-great-at-asking-questions-e37be04d0603)
5. [Coursera: Learning How to Learn](https://www.coursera.org/learn/learning-how-to-learn)

## Typing

1. [Keybr](https://www.keybr.com)
2. [Monkey Type](https://monkeytype.com)
3. [TypeRacer](https://play.typeracer.com) - Race your section mates, maybe?

## Web Browsers

1. [BBC: How Does the Internet Work?](https://www.youtube.com/watch?v=eHp1l73ztB8) *\[5 minutes]*
2. [Google Short: What is a Web Browser?](https://www.youtube.com/watch?v=BrXPcaRlBqo) *\[1 minute]*
3. [MDN: What is the difference between webpage, website, web server, and search engine?](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Pages_sites_servers_and_search_engines)

## Command Line

1. [Command Line Flashcards](https://flashcards.github.io/command_line/introduction.html)
2. [Command Line Cheatsheet](https://files.fosswire.com/2007/08/fwunixref.pdf)
3. [Learn Enough Command Line to Be Dangerous](https://www.learnenough.com/command-line-tutorial)
4. [The Art of Command Line](https://github.com/jlevy/the-art-of-command-line#readme)
5. [Conquering the Command Line](https://www.softcover.io/read/fc6c09de/unix_commands/basics) *\[book]*


# 2: Operators and Expressions

## Learning Objectives

* Define a "code expression".
* Understand the operator's function within a code expression
* Use the Chrome DevTools Console to begin writing code expressions

## Video

{% embed url="<https://youtu.be/p24syWwKoO8>" %}

## Introduction

This module is the beginning of our programming journey!

Programming is the act of writing code (instructions) for the computer to execute sequentially. It is the same as written instructions for a cooking recipe!

<figure><img src="/files/jJcqjByXQOE9um8itCtO" alt=""><figcaption><p>pancakes ftw!</p></figcaption></figure>

We will first start with learning how to write single lines of code before stringing them together into a bigger whole. Before long, you will be creating multi-line programs of your own!

#### **Code Expression**

An expression is a **"valid unit of code that resolves to a value"**.

This does mean that there are invalid code that are "unresolvable" and will give errors - something that will be discussed at a later time.

There are two kinds of code expressions - (1) those that purely evaluate; (2) those that have a "side effect".

We are familiar with the expressions that purely evaluate. These are the arithmetic expressions we learnt in school: `5 + 6` . This, we understand, evaluates itself to `11`.

An example of the second type expression type is this: `a = 3` . This expression enters into a new, yet understandable realm. This expression uses the `=` *operator* to assign the value `3`to the variable `x`. This expression will evaluate to `3`.

We will look into these expressions in greater detail within the sub-modules. At this point we want to first have a space to experiment with code...

## Using Chrome DevTools Console

The reason we ask every student to use Google Chrome for this course is to both standardise the tools everyone uses and, in our current context, this functionality we are exploring to begin our foray into programming.

Feel free to read up more on [Google's own documentation](https://developer.chrome.com/docs/devtools/console/)!

#### **Setup**

1. Open a new tab in the Chrome browser by clicking File > New Tab; or pressing `Cmd+T` for Mac, and `Ctrl+T` for Windows.
2. Open Chrome Developer Tools by clicking View > Developer > JavaScript Console; or pressing `Cmd+Option+I` for Mac or `Ctrl+Shift+I` for Windows; or `F12`; or right-clicking anywhere in Chrome and clicking Inspect.
3. Select the `Console` tab in Chrome Dev Tools.

![Accessing the Developer tools in the Chrome browser setting](/files/Btu2k849atz74a0sbIt7)

<figure><img src="/files/eOmwz1Tbf2y63o7fHzrI" alt=""><figcaption><p>Console tab in Chrome DevTools</p></figcaption></figure>

## Try

The JavaScript language is capable of performing math operations. Enter the following calculations into the Chrome DevTools Console, followed by the `Enter` key.

![Chrome console allows for in-browser calculations](/files/cw0wohK3bfy6MzCitfqQ)

```javascript
2 + 2;
```

```javascript
4 * 2;
```

```javascript
4 / 2;
```

```javascript
4 - 2;
```

The input here is a mathematical equation typed in by the user, you. You have *instructed* the computer to perform a mathematical operation. The computer \_**returned** \_ an output, the evaluation of the equation.

{% hint style="info" %}
These exercises may seem trivial, but mathematical operations are at the core of all computing instructions. Computers fundamentally ***compute.*** That being said, they can get things predictably wrong. Try: `0.1 + 0.2` in your console. Did you get what you expect?

Coding Fundamentals will not cover why computers sometimes behave in odd ways, but you can read up more about this particular behaviour [here](https://0.30000000000000004.com) and [here](https://betterprogramming.pub/why-is-0-1-0-2-not-equal-to-0-3-in-most-programming-languages-99432310d476).
{% endhint %}

### Operators

In the above code, `+` `*` `-` and `/` are known as *operators.* Specifically, they are arithmetical operators: performing a mathematical operations between 2 numbers.

We will address all the arithmetic operators in the next section, and other operators in the following sections!.

{% hint style="info" %}
Do not worry if you are afraid of math. This course only involves basic math. You are here to learn how to write code and not solve math problems! Hang in there 💪
{% endhint %}

## Further Readings

{% embed url="<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators>" %}
MDN Documentation of JavaScript expressions and operators
{% endembed %}


# 2.1: Arithmetic Operators | Mathematical Expressions

## Learning Objectives

* Be familiarized with the list of arithmetic operators available
* Try writing your own mathematical expressions!
* Use the addition operator on strings

## Introduction

Arithmetic operators takes numerical values as their operands (the values on both sides of the operator) and returns a single numerical value.&#x20;

`6 + 13 // '+' is the operator; both values, '6' and '13', are the operands`

In the case above, 13, being on the right side, is added to 6, on the left.

The standard arithmetic operators are addition (`+`), subtraction (`-`), multiplication (`*`), and division (`/`). These operators work as they do in most other programming languages when used with floating point numbers (decimals).

Here is a list of arithmetic operators:

| Operator                  | Description                                                                                                       | Example                                 |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------- | --------------------------------------- |
| Addition ( + )            | <p><code>a + b</code><br>Result: adds <code>b</code> into <code>a</code>.</p>                                     | <p><code>3 + 9</code><br>Result: 12</p> |
| Subtraction ( - )         | <p><code>a - b</code><br>Result: subtracts <code>b</code> from <code>a</code></p>                                 | <p><code>6 - 8</code><br>Result: -2</p> |
| Multiplication ( \* )     | <p><code>a \* b</code><br>Result: <code>a</code> is multiplied by <code>b</code></p>                              | <p><code>4 \* 2</code><br>Result: 8</p> |
| Division ( / )            | <p><code>a / b</code><br>Result: <code>a</code> is divided by <code>b</code></p>                                  | <p><code>9 / 3</code><br>Result: 3</p>  |
| Remainder or Modulo ( % ) | <p><code>a % b</code><br>Result: remainder of <code>a</code> divided by <code>b</code></p>                        | <p><code>10 % 6</code><br>Result: 4</p> |
| Increment ( ++ )          | <p><code>a++</code><br>Result: adds 1 to <code>a</code></p>                                                       |                                         |
| Decrement ( -- )          | <p><code>a--</code><br>Result: subtracts 1 from <code>a</code></p>                                                |                                         |
| Exponential ( \*\* )      | <p><code>a \*\* b</code><br>Result: <code>a</code> is multiplied by itself by <code>b</code> number of times.</p> |                                         |

## String Concatenation (addition operator)

You are able to use the arithmetic addition operator to combine two strings together, this can also be known as concatenation of two strings. The same addition operator `+`  that is used on numbers are applied to strings in this case.&#x20;

Though it should be noted that if you add two different data types together this can cause type coercion. Which is a fancy way of saying, JavaScript will alter the datatypes to accommodate the logic used. If you want to know more about type coercion please read about it [here.](https://www.geeksforgeeks.org/what-is-type-coercion-in-javascript/)  &#x20;

Using the logical addition operator we can assign a combined string to a variable.

{% code overflow="wrap" lineNumbers="true" %}

```javascript
// String Concatenation using logical operators

const string = 'Good morning' + ' ' + 'class';

console.log(string)
// 'Good morning class'

```

{% endcode %}

In the example above we are taking the operands strings/ values  `Good morning` ,  `' '`   and  `class` to create a single string reading  `Good morning class` . They are being combined through the  `+` sign which is the operator.&#x20;


# 2.2: Assignment Operators | Variables

## Learning Objectives

By the end of this lesson, you should be able to:

* Describe what a variable is and how to assign it a value or expression.
* Use the `var` **keyword** to declare a new JavaScript variable.
* Explain how to achieve *accurate representation* of your program with suitable variable names.
* Use the camelCase naming convention for your JavaScript variable names.

## Introduction

To do more than just basic math, we need to store, access and manipulate data in a computer's *memory*. We do this by utilizing **variables** in programming.

{% embed url="<https://youtu.be/mBZrHgAja78>" %}

## What are Variables?

Variables store and contain data. We name a variable and we associate a specific data value with it. We use variables to represent data that our program will process. First, we name a variable by using the **keyword** `var`. This tells the browser that the next word is the intended name for the variable.

{% hint style="info" %}
Keywords are words that have a pre-defined meaning within a programming language, and are reserved for that use only. While all programming languages will have some way to declare a variable, different languages will do so using different keywords or *syntax*.
{% endhint %}

In order to assign a value to a variable, we use the assignment operator `=`. In programming, the equals sign has a slightly different meaning than in a mathematical equation, we are using `=` **declaratively**:

```javascript
var pi = 3.14;
var radius = 4;
```

In the above statements we have declared the variables `pi` and `radius`, and assigned them the value `3.14` and `4` respectively. Using these 2 data values we can calculate the area of a circle.

```javascript
pi * radius * radius;
```

We can also use variables to *capture* the result of that calculated value, and store it in *memory*.

```javascript
var area = pi * radius * radius;
```

{% hint style="info" %}
Note: You may have seen `let` and `const` syntax being used to declare variables in JavaScript. `let` and `const` are both *relatively* new ways to declare variables in JavaScript, and while `let` has a similar use case to `var,` they are different in ways which we will not delve into right now. For the purposes of Coding Fundamentals, it will suffice to use `var`, but you are free to explore and experiment.
{% endhint %}

## **The Importance of Abstraction** <a href="#the-importance-of-abstraction" id="the-importance-of-abstraction"></a>

If we wanted the same result we could also write the following.1var x = 3.14 \* 4 \* 4;Copied!But this would not be as *meaningful* as our previous example.Our programs must not only *calculate* values correctly, they must also accurately *represent* the operations we are performing, in this case calculating the area of a circle. **The names of our variables give meaning to the data our code contains.**

![Drake is not known for his programming skills. Don't be like Drake.](https://miro.medium.com/max/717/1*7LO7JEAZbo6YmN8feAVCwg.png)

## **Variable Naming Convention**

In JavaScript convention, ordinary variables are named with [lower camel case](https://en.wikipedia.org/wiki/Naming_convention_\(programming\)#Examples_of_multiple-word_identifier_formats). The name starts with a lowercase letter and every subsequent word starts with uppercase. For example, `bananaCount` or `firstDiceRoll`. This is *convention*, and will not affect code *functionality*. Different languages and communities have different conventions. Similar to driving conventions: in some countries, cars are driven on the left side, and on the right side in other countries.

![](https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/CamelCase_new.svg/1200px-CamelCase_new.svg.png)

## Exercises

Using the Chrome Dev Tools Console, write code to represent each of the following. Use descriptive variable names that explain what you are calculating. You will need to search the web for some formulas. When you are done, paste the code into a message to yourself in the community channel.

1. Calculate the circumference of a circle given its radius
2. Convert Celsius to Fahrenheit
3. Calculate the volume of a cube given a side length
4. Calculate the gradient percentage of a road given rise and run
5. Convert millilitres to pints


# 2.3: Our First Program

## Learning Objectives

At the end of this lesson, you should be able to:

* Briefly explain what *String Values* are.
* **Concatenate** *String Variables* together using the `+` **operator.**
* Perform simple manipulation on user input of the Fundamentals Starter Code template.

## Introduction

{% embed url="<https://youtu.be/pMMYj-Hbkxc>" %}

Let's run code outside the browser console. We'll create a basic program with a SWE Fundamentals starter template.

## Setup

1. [Download the zipped folder](https://github.com/rocketacademy/fundamentals-starter-code/archive/refs/heads/main.zip) of the SWE Fundamentals Starter template and extract it to an appropriate location in your computer - see the [suggested folder structure](/course-logistics/required-hardware-and-software/recommended-set-up).
2. [Open your 'fundamentals' folder in VSCode](/course-logistics/required-hardware-and-software/recommended-set-up#open-basics-folder-in-vscode).

## **Static Program Output**

### **Default Template Behaviour**

The default starter code has one basic behaviour. When you click the button you should see `hello world`.

Try it yourself. Open the `index.html` file in your browser and click the Submit button.

### **Output Own Values**

Next, we'll change the output in the output box from the default to our own text.

Open the `script.js` file in your editor. You should see the following.

```javascript
console.log('hello');

var main = function (input) {
  var myOutputValue = 'hello world';
  return myOutputValue;
};
```

On line 3 we define the `main` function. The `{}` curly brace characters surround the contents of this function. Without a further formal definition we'll begin using this code to make text appear on the screen. We'll come back to formal definitions later.

On line 4, `myOutputValue` is a variable that holds the value we see in the output box after we click the Submit button. Change the value of the variable to something else. We'll start with numbers only.

```javascript
var myOutputValue = 2;
```

To see our changes, **remember to save the file and refresh the browser screen**. What happens when we click the Submit button? Try assigning different values and see them output in the output box.

```javascript
var myOutputValue = 12;
```

```javascript
var myOutputValue = 9999999999;
```

```javascript
var myOutputValue = 1.234234;
```

### **Operations as Output**

We can also assign variables or even mathematical operations to `myOutputValue`. Our previous code from [3.2: Variables](/2-basic-data-manipulation/2-operators-and-expressions/2.2-variables) looked like this.

```javascript
var pi = 3.14;
var radius = 4;
var area = pi * radius * radius;
```

Let's add the above code and assign the value of `area` to `myOutputValue`.

```javascript
var myOutputValue = area;
```

When we click the Submit button our program now calculates the area of a circle! Try other calculations. Remember to assign the final value to `myOutputValue` to see it in the output box.

```javascript
var myOutputValue = 34534 * 2334;
```

```javascript
var myOutputValue = 12 * 12;
```

```javascript
var myOutputValue = 100 / 10;
```

## Dynamic Program Output

A program needs to take input and produce output. So far our programs only take input from `script.js`, not from the user of `index.html`. Fortunately, the starter code is set up to take user input by default.

What happens when we type in the input box before clicking Submit? We'll begin to add inputs to our program using the input box.

### Function Parameters

We'll continue working with functions without formally defining them. Our goal is to create a program that takes user-defined inputs and gives input-specific outputs. In our starter code, the `input` variable is a *"function parameter"*, and its value is what we typed in the input box.

Assign the value of `input` to `myOutputValue` like the following.

```javascript
var myOutputValue = input;
```

Now whatever we type in the input box gets output to the output box.

{% hint style="info" %}
**String Data**

`input` is always of a data type called "string". \[Wikipedia]\(<https://en.wikipedia.org/wiki/String\\_(computer\\_science)> defines a string as a "sequence of characters", where characters are typically the characters on our keyboards. Strings can also contain spaces, punctuation, numeric digits, emojis, Chinese characters, or writing in other languages. Strings are different from numbers in that numbers represent numeric values and not text. Here is an example of a string stored in a variable.

```javascript
var name = 'Susan';
```

{% endhint %}

### Interactive Messages

Change the value of `myOutputValue` to a string (any set of words you want) and see it appear in the output box. Let's use strings to make our program more interactive. Change the code back again to assign the value of `input` to `myOutputValue`:

```javascript
var myOutputValue = input;
```

## Sample Programs

### Greeting Program

We will now create a program with purpose. The user will type their name, and we will use the name to greet them. To do this we'll take `input` and combine it with other strings to generate output.

```javascript
var myOutputValue = 'Hello ' + input + ', you look great today!';
```

Change your program output to a different message. Make it longer. You can even use `input` more than once, for example, "Hello, Susan! Wow, Susan is a great name. Reminds me of this movie star..."

### Metric Conversion Program

Let's incorporate math operations. The user will now enter a distance in kilometres and the program will output the distance in miles. 1 km equals 0.62 miles. We can write this in JavaScript like the following.

```javascript
var distanceInKm = 1;
var distanceInMiles = distanceInKm * 0.62;
```

Change `myOutputValue` to see the calculation on screen.

```javascript
var myOutputValue = distanceInMiles;
```

Try changing `distanceInKm` to see new conversions. To let the user input distances, assign the value of `input` to `distanceInKm`.

## Output Formatting

Our programs should be user-friendly and output more than just a number. For example, if the user inputs `5`, the program might output the following.

```
Hi! 5 kilometers is equal to 3.1 miles.
```

To achieve this, combine calculated values with string values like the following, similar to the Greeting Program.

```javascript
var myOutputValue =
  'Hi! ' + input + ' is equal to ' + distanceInMiles + ' miles.';
```

{% hint style="info" %}
A common alternative to the above string formatting is to use [JavaScript template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals). The following syntax is equivalent to the syntax above.

```javascript
var myOutputValue = `Hi! ${input} is equal to ${distanceInMiles} miles.`;
```

{% endhint %}

## Exercise

Share your work with your section: save the code you write into another file. Name it `share.js` (A file only for sharing in the discussion channel.) Send the code file as a snippet in your section discussion channel.


# Additional Resources 2

For the curious and the hungry

## Introduction <a href="#introduction" id="introduction"></a>

If you'd like to learn more, this page contains a non-exhaustive, unordered list of useful resources. These resources are primarily related to Module 2, but also expand the scope of what has been covered, and touch on concepts and fundamentals that we will cover in future modules. You will see some of these resources repeated in other pages

## JavaScript

1. [FreeCodeCamp: Basic JavaScript Exercises](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#basic-javascript)

## Operations and Variables

1. [MDN: Basic math in JavaScript — numbers and operators](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Math)
2. \*\*\*\*[JavaSript.info: Operators](https://javascript.info/operators)
3. [JavaScript.info: Variables](https://javascript.info/variables)

## Data Types

1. [MDN: Handling text — strings in JavaScript](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Strings)
2. [JavaScript.info: Data Types](https://javascript.info/types)
3. [W3S: JavaScript Numbers](https://www.w3schools.com/js/js_numbers.asp)
4. [W3S: JavaScript Strings](https://www.w3schools.com/js/js_strings.asp)


# 3.1: Functions

## Learning Objectives

By the end of this lesson, you should be able to do the following:

* Define "control flow".
* Understand what a function is and why we use functions.
* Declare and define a function as a block of code.
* Understand how to pass input to a function.
* Understand how to store the output of a function.
* Understand the purpose of the return keyword.
* Execute a function.

## Introduction

{% embed url="<https://www.youtube.com/watch?v=VUcdDK1hSoE>" %}

We can now start to group the code we're working with into "functions" and use functions to write more realistic, complex programs. Let's explore how functions work.

## What Functions Are

A function is a collection of lines of code, also known as a **"block"** of code. We run that code when we write the appropriate statement to "execute" the function. A function is a type of **"control flow"**, meaning function definitions in our code may not execute *sequentially* through the code file. For example, we may define a function at the top of our file, but only execute that function at the bottom of our file.

We can think of functions as "recipes" of code; a fixed set of instructions or steps, that can take in a variable input (*e.g. number of dinner guests)* and give a certain output (*enough food for dinner*), even though the instructions are statically defined. Functions have 3 key parts:

1. Input(s)
2. Pre-defined operations on the input
3. Output

Functions sometimes do not take in input, and sometimes do not return an output, but for now we will work with this basic structure.

![](https://cloudreports.net/wp-content/uploads/2019/06/Function_machine2.png)

## Why We Use Functions

Functions are necessary to abstract complexity away from the main logic of our applications. This allows us to break problems down into ever-smaller sub-problems, simplifying the process of coding complex applications. In this module we will see 2 use-cases of functions.

1. Purpose-built data manipulators that take inputs and give outputs. These are sometimes called *"helper"* functions. We will define our functions' inputs and outputs, and all the instructions for that function will be contained in a block of code as part of the function *definition*.
2. Logic sequences that we wish to encapsulate in a *"sub-routine"*. We do this with our `main` function. `main` contains everything we want to happen when the user clicks Submit. It is common for sub-routine functions to rely on several other helper functions.

## Define a Function

Define a function that "abstracts" the km-to-miles conversion we did in [2.3: Our First Program](/2-basic-data-manipulation/2.3-our-first-program#metric-conversion-program).

1. Start at the top of `script.js`
2. Create a variable for our function: `var convertKmToMiles`. **Note that function variable names start with a verb by convention, to distinguish them from variables storing other data types. With few exceptions such as the `main` function, function names should almost always start with a verb.**
3. Assign a function definition to that variable: `var convertKmToMiles = function () {}`

{% hint style="info" %}
Note the beginning and end of the function "block" with curly braces (`{}`). We will add function logic within these curly braces. Semicolons marked the end of a line of code, curly braces are used to mark the start and end of a ***code block.***
{% endhint %}

```javascript
var convertKmToMiles = function () {};
```

Define what logic happens when the function is executed. In our case, we want to convert KM to miles.

```javascript
var distanceInMiles = distanceInKm * 0.62;
```

Use the `return` keyword to define the function's output value. For our `convertKmToMiles` function, our return value is the distance in miles.

{% hint style="info" %}
Note that the output of a function may not be the output of the overall program, because functions can call other functions. The output of the overall Coding Fundamentals starter code program is the return value of the `main` function.
{% endhint %}

```javascript
return distanceInMiles;
```

We define and name a function "input parameter" as `distanceInKm`. Functions can have 0 or more input parameters.

```javascript
var convertKmToMiles = function (distanceInKm) {
```

All together our function looks like the following.

```javascript
var convertKmToMiles = function (distanceInKm) {
  var distanceInMiles = distanceInKm * 0.62;
  return distanceInMiles;
};
```

### Functions Can Have Multiple Input Parameters

Functions can accept more than 1 input parameter, and input parameters are assigned based on position in the input parameter list, *not* by variable name.

For example, if we define a function with syntax like the following,

```javascript
var myFunc = function (myVar1, myVar2) { ... };
```

and we execute it with the following,

```javascript
// a and b are local variables
myFunc(a, b);
```

then inside of `myFunc`, `myVar1` will be assigned to `a` and `myVar2` will be assigned to `b`. The parameter assignment has nothing to do with the name of the input variables, and everything to do with the order of the variables passed into `myFunc`.

## Execute a Function

![](https://i.pinimg.com/236x/ef/9a/0f/ef9a0f91fb24fd8202fa7fe79253762e.jpg)

The syntax to run a function is to code the function name followed by parentheses (`()`). Without parentheses, the function is just a variable whose value is a function, and the function's logic will not run.

```javascript
convertKmToMiles();
```

Input parameters go within the function execution parentheses. Our `convertKmToMiles` function expects 1 input parameter, a distance in KM. For our function to work, we must pass this parameter to our function by specifying the parameter in the parentheses.

```javascript
var myKmDistance = 4;
convertKmToMiles(myKmDistance);
```

Let's test this function on its own outside of the Coding Fundamentals starter code.

1. Open Chrome Developer Tools by selecting View > Developer > JavaScript Console from the Chrome menu bar
2. Copy the function definition of `convertKmToMiles` into the console and hit `Enter`
3. The console should respond with an 'undefined', that is to be expected.
   * If the expression doesn’t return a value, the Chrome console will report undefined — this doesn’t mean anything is wrong, it’s just letting you know that the previous expression didn’t return a result.
4. Type the function name into the console and hit `Enter`. You should see the code block you defined.
5. Run the function from the console again with a different input value

```javascript
// Step 2 - copying the FUNCTION DEFINITION into the Chrome Dev Tools
var convertKmToMiles = function (distanceInKm) {
  var distanceInMiles = distanceInKm * 0.62;
  return distanceInMiles;
};

// Step 4 - checking the definition in Chrome Dev Tools
convertKmToMiles;

// Step 5 - executing the function using the FUNCTION CALL in the Chrome Dev Tools
convertKmToMiles(7676);

/*
 * REMEMBER that function call using the curved braces ()
 * is what 'activates' the function.
 *
 * Using the function without the curved braces is referencing
 * the variable name that stores the function (cf. step 4)
 */
```

### **Use Other Input Variables**

Create several variables and use them as input to your function.

```javascript
var kmsToHome = 4;
var kmsToSchool = 6;
var kmsToWork = 7;
```

Use these variables as input to our function. Paste each function call into the console and hit `Enter` one by one.

```javascript
convertKmToMiles(kmsToHome);
convertKmToMiles(kmsToSchool);
convertKmToMiles(kmsToWork);
```

## Capture the Result

We can see the result of our calculation in the console and capture that value for later. Paste this code into the console:

```javascript
var result = convertKmToMiles(7676);
```

Type in the name of the variable, `result`, and press `Enter` to see the given value.

## Add Function to Code File

Back in `script.js`, Call `convertKmToMiles` from our `main` function, providing `input` as a parameter to `convertKmToMiles`.

```javascript
var convertKmToMiles = function (distanceInKm) {
  var distanceInMiles = distanceInKm * 0.62;
  return distanceInMiles;
};

var main = function (input) {
  var myOutputValue = convertKmToMiles(input);
  return myOutputValue;
};
```

## Other Sample Functions

### Double a Number

```javascript
var doubleNumber = function (number) {
  return number * 2;
};
```

### Convert Kilograms to Pounds

```javascript
var convertKilosToPounds = function (kilos) {
  return kilos * 2.2;
};
```

### Calculate Area of a Circle

```javascript
var calcCircleArea = function (radius) {
  var pi = 3.1415;
  return pi * radius * radius;
};
```

## Main Function

We can now better understand the `main` function in our starter code. You may have noticed we currently do not execute `main` from `script.js`. Our starter code runs `main` for us whenever we click the Submit button. The code for this mechanism is inside `index.html`.

* The `input` parameter of `main` is what the user types in the input box
* The `return` value of `main` is what gets displayed in the output box

With this in mind, assign the value of `input` to `myOutputValue` to see this connection. Then change the code again to assign the string value "wow hello" to `myOutputValue`.

## Exercises (Base)

For each app, create a new copy of the Fundamentals Starter Code folder.

For each exercise try to encapsulate each distinct operation inside a function that returns a value. For example, `daysToMinutes(3)` is a function that converts days to minutes, takes a number of days as input, and returns a number of minutes.

{% hint style="info" %}
Share your work with your section: save the code you write into another file. Name it `share.js` (A file only for sharing in the community channel.) Send the code file as a snippet in your section community channel.
{% endhint %}

### Run Example Code

1. Duplicate and run the code from this module
2. Paste the other function examples in instead of `convertKmToMiles`
3. Remove the `return` statements from the examples. What happens and why? What does the `return` statement do and how does it work?
4. Remove the `distanceInKm` parameter from the function definition. What happens and why? Replace the parameter afterward.
5. Change the variable name `distanceInKm` to another name everywhere. What happens and why? Change the name back to `distanceInKm` afterward.

### **Juice Wedding**

It takes 4 oranges to make a 90ml glass of orange juice. When planning your wedding, you need to know how many oranges to buy so all your guests have 1 glass of juice. The user will enter a number of guests and the app will say how many oranges are needed and how many litres of orange juice you would get. ([Ref Solution](https://github.com/rocketacademy/fundamentals-starter-code/tree/5.1-refSolns-juiceWedding))

### **SG Hugs**

Everyone has a different gauge for how long they like to hug. The user can enter a number of seconds they like to hug on average, and the app will calculate how many years it will take to hug everyone in Singapore. You are allowed 9 hours a day to sleep and eat. ([Ref Solution](https://github.com/rocketacademy/fundamentals-starter-code/tree/5.1-refSolns-sgHugs))

### **House Paint**

Estimate the price of painting the interior of your home. The user will enter a dollar amount of paint per litre and the app will calculate how much it will cost.

\
Each room in your 6-room house has the same area to be painted: 3m x 3m. There are 6 windows and 8 doors in your designer home. Coincidentally, windows and doors all of the same size: 90cm x 150cm. Paint will cover 300 square meters per litre. You want to apply 2 coats of paint. ([Ref Solution](https://github.com/rocketacademy/fundamentals-starter-code/tree/5.1-refSolns-housePaint))

### **Train Speed**

Two trains are leaving to Tokyo. Train 1 is traveling 200kph, and will reach Tokyo in 2 hours. Train 2 is newer and can travel faster, but is delayed due to a signalling fault. Build an app for Train 2's conductor calculate how fast Train 2 needs to travel to arrive at Tokyo at the same time as Train 1, based on how long it was delayed. Output the speed in kph. ([Ref Solution](https://github.com/rocketacademy/fundamentals-starter-code/tree/5.1-refSolns-trainSpeed))

## **Exercises (More Comfortable)**

### **Clock**

A user can enter the number of minutes past 1pm and the app will calculate the angle between the hour and minute hand. You are free to decide how else your clock will work: if the minute hand moves in 5 minute increments or moves every second, etc.


# 3.2: Errors

## Learning Objectives

By the end of this lesson, you should be able to do the following:

* Define and differentiate between "syntax errors" and "logical errors".
* Know the difference between run-time and compile-time syntax errors.
* Understand strategies to debug errors.
* Utilise `console.log()` for effective debugging.

## Introduction

It has been told that on September 9th, 1947, [Grace Hopper](https://en.wikipedia.org/wiki/Grace_Hopper), an American computer scientist, found a moth in the Harvard Mark II computer’s logbook and reported the world’s first literal computer bug. However, the term “bug,” in the sense of technical error, dates back at least to 1878 and with Thomas Edison.

![](/files/Zscr1OJHY0vDr5kyLZ0T)

When programs throw errors that we didn’t expect to encounter, we call those errors *bugs*. Programmers call the process of updating the program so that it no longer produces bugs: *debugging*.

{% embed url="<https://preview.redd.it/2o2iq7pxia981.gif?format=mp4&s=0e7e3d534e257152b1929d3cd146b55d8232b02c>" %}
Debugging a program
{% endembed %}

Our programs will have errors. Errors are an intrinsic part of software development for everyone, not just beginners. What differentiates beginners from more-experienced engineers is the speed with which more-experienced engineers can triage and resolve errors.

Errors in our programs for Coding Fundamentals will appear in the [Chrome Dev Tools console](https://developer.chrome.com/docs/devtools/open/). Access the console by going to the Chrome menu bar and selecting View > Developer > JavaScript Console. Open the console before loading our webpages, and keep the console open when running code in the browser to catch errors as early as possible.

Unlike humans, computers follow strictly defined rules, cannot make sense of context, and do exactly as they are told. If we make grammatical mistakes when writing down instructions for them, or hope they read between the lines and understand what we hope to achieve, we are bound to run into errors.

There are 2 broad categories of errors: **syntax** and **logical** errors. Syntax errors are similar to grammatical errors in human languages, and logical errors are similar to giving poor directions to a lost tourist.

We can use the console to fix both kinds.

{% embed url="<https://www.youtube.com/watch?v=iWmlkW6uQ-0>" %}

## Syntax errors

These are errors where we will see red text in the console. Syntax errors can be divided into 2 kinds: *compile-time* and *run-time* errors.

### Compile-Time Syntax Errors

Compile-time syntax errors are errors that can be detected before our code runs. These are similar to grammatical errors caught by *auto-correct*. VSCode will point out these errors in VSCode before we run our programs by highlighting the error code with red squiggly lines. If we try to run programs with compile-time errors, the programs will not run and we will see the errors in the Chrome console.

In some other programming languages, such as Java or C++, there is a compilation step before our code runs to translate human-readable code to machine code known as [binary](https://www.youtube.com/watch?v=wgbV6DLVezo).\
\
Languages such as JavaScript and Python are [interpreted ](/3-structuring-and-debugging-code/additional-resources-3#errors)programs where there isn't a dedicated compilation step, but the terminology compile-time can still be used to refer to time after the program is written but before it is executed.

Let's introduce a syntax error into our program. Replace our `kilometersToMiles` function with the one below.

```javascript
var kilometersToMiles = function distanceInKilometers) {
  var distanceInMiles = distanceInKilometers * 0.62;
  return distanceInMiles;
};
```

You'll get the error: `Uncaught SyntaxError: Unexpected token ')'`. This may look cryptic, but once you see this error a few times (and you likely will) you'll understand what it is trying to tell you.

First of all, the console is helpfully telling us which line of our code the error is occurring on.

Specifically in this case the error was a missing parenthesis. JavaScript knew because of the `function` keyword that a function was about to be defined. It was waiting for an opening left parenthesis. When it found a right parenthesis it knew that something was wrong.

There are specific rules why JavaScript might not detect that a left parenthesis (`(`) is missing instead of detecting that a right parenthesis (`)`) is incorrect. These rules are outside the scope of this course, but in practice, unfortunately, we as programmers will have to know that "I didn't expect a right parenthesis" implies we are missing a left parenthesis.

A significant amount of the feedback we will get from the computer will be semi-cryptic and we will try to understand this to debug errors.

![Humor error: Python doesn't use semicolons](https://preview.redd.it/5yhx7zsi7ug81.jpg?width=640\&crop=smart\&auto=webp\&s=af94ec8e098d27f9b2ee3160c0e889674a3291e5)

### Run-Time Syntax Errors

Imagine sending a text message with no spelling or grammar errors, but a nonsensical one:

```
Singapore, lunch! you plane
```

Auto-correct won't catch any errors as each word is spelt correctly, grammatically valid and makes sense individually, but it's impossible to make sense of what is trying to be communicated.

Run-time syntax errors are syntax errors that are only detected *during* when our programs are running. These types of errors are not possible in compiled languages because the entire program runs through a compiler before it can be executed.

JavaScript, being an *interpreted* language, code may only be read by the computer when it is executed. This produces 'run-time syntax errors' that are common in JavaScript. Fortunately, we have VSCode to help us detect these errors before we run our programs.

Let's create a run-time syntax error.

```javascript
var myOutputValue = 'hello world'();
```

1. Replace the relevant line in the starter code with the line above.
2. Refresh the starter code page in the browser. Observe that there is no red text in the console.
3. Click the Submit button. We should see the error `Uncaught TypeError: "hello world" is not a function` in the browser console.

This error happens because there is a set of parentheses (`()`) instead of a semi-colon (`;`) after our `'hello world'` string. JavaScript interprets parentheses to mean we want to run a function. While this error is uncommon, notice for this type of error that JavaScript did not alert us until it tried to run the code .

## Logical errors

Have you every received bad directions? Or instructions that are valid and sensical, but incomplete?

Logical errors are errors that arise from syntactically-valid code that does not *behave* the way we want. These errors may not produce red console output because the program code does not have syntax errors.

### Debugging

Debugging is the process of diagnosing and fixing errors in our programs. The debugging process can be relatively straightforward. For syntax errors, our browser consoles output red error text. We can view the referenced line of code, interpret the error text, and fix our syntax. Debugging can become more complicated when diagnosing logical errors. Our code may run without errors, but its behaviour may be incorrect.

Here are 2 strategies to diagnose and correct errors.

1. Control-flow checking: Is our code running? Are the right blocks of code executing at the intended times?
2. Value checking: Do the values in our variables match what we expect?

### console.log

`console.log` is a a crucial debugging tool in JavaScript that we will use for both control-flow checking and value checking. It is a function we can run to make text appear in the browser console. We pass the text we want to appear as a parameter to `console.log` like this: `console.log('bananas!')`.

Try adding `console.log` statements to different parts of your code. Each `console.log` should indicate where in the code it is.

![This should be you.](https://i2.wp.com/programmingwithmosh.com/wp-content/uploads/2019/07/consolelogmeme.jpg?resize=442%2C442\&ssl=1)

### Control-Flow Checking: Is Our Code Running?

Control-flow checking means checking if relevant parts of our code are being executed. Function syntax allows us to execute code in a specific order, or not at all. If our programs seem incomplete or wrong even though we have coded relevant logic into the program, it's possible we forgot to execute the relevant function, or our conditional logic (which we will learn in Module 6) failed to trigger the relevant code.

We can use `console.log` statements verify whether our browser is executing the relevant code. If our `console.log` statements appear in the browser console, we know our browser is executing that code.

Replace our starter code with the following and verify that we are running the `kmToMiles` function.

```javascript
var kilometersToMiles = function (distanceInKilometers) {
  console.log('running km to miles function');
  var distanceInMiles = distanceInKilometers * 0.62;
};

var main = function (input) {
  var myOutputValue = kilometersToMiles(input);
  return myOutputValue;
};
```

### Value Checking: Are the Values Correct?

Value checking means verifying that the intermediate variable values in our program match our expectations. Another way we can use `console.log` is to pass it the variable values we wish to verify.

Replace our starter code with the following. Are the values in our program the ones we expect?

```javascript
var kilometersToMiles = function (distanceInKilometers) {
  var distanceInMiles = distanceInKilometers * 0.62;
  return distanceInMiles;
};

var main = function (input) {
  var myOutputValue = kilometersToMiles(input);
  console.log('myOutputValue');
  console.log(myOutputValue);
  return myOutputValue;
};
```

### **`console.log` Formatting**

Formatting our console output can help make it more visible and decipherable to ourselves.

A few tips:

1. Be specific when describing each `console.log` statements, especially when we are logging variable values. Avoid generic labels like `number` or `output` and avoid repeating labels, which can obfuscate which variables are being logged.
2. Format output with special characters like `===`, `***`, or `###` to help output stand out.\
   `=== DISTANCE IN KM ===` stands out more than `distance in km`.

## Tips

1. **Mental models are the key to building your computational thinking skills.**
   1. Use each error as an opportunity to understand the system better. (But also know when to strategically move on - you won't achieve perfect knowledge).
2. **Expect lots of errors.**
   1. **You will run into bugs and errors.** This does not make you a poor or lousy programmer.
   2. Errors are the practice and process of programming. Use them to learn more. Be playful with the system and don't be afraid to break things.
3. **Formulate questions.** Practice asking questions when you are working on a problem:
   1. What have you tried?
   2. What is the context of the error? When do you see it, what is the incoming data and how does it affect the output?
   3. What do you think is happening based on the facts?
4. **Talk to yourself. This is called**[ **rubber duck programming**](https://rubberduckdebugging.com)**.**

<img src="https://cdn.shopify.com/s/files/1/0243/9469/4761/articles/rubber-duck-debugging_670x.jpg?v=1558873639" alt="quack quack" data-size="original">

## Exercise

1. You'll have plenty.


# Additional Resources 3

For the curious and the hungry

## Introduction <a href="#introduction" id="introduction"></a>

If you'd like to learn more, this page contains a non-exhaustive, unordered list of useful resources. These resources are primarily related to Module 3, but also expand the scope of what has been covered, and touch on concepts and fundamentals that we will cover in future modules. You will see some of these resources repeated in other pages

## JavaScript

1. [FreeCodeCamp: Basic JavaScript Exercises](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#basic-javascript)

## Functions

1. [MDN: Functions - Reusable Blocks of Code](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Functions)
2. [MDN: Function Return Values](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Return_values)
3. [JavaScript.info: Functions Basics](https://javascript.info/function-basics)
4. [JavaScript.info: Function Expressions](https://javascript.info/function-expressions)

## Errors

1. [G4G: Difference between Compiled and Interpreted Languages](https://www.geeksforgeeks.org/difference-between-compiled-and-interpreted-language/)
2. [FCC Blog: Interpreted vs Compiled, What's the Difference?](https://www.freecodecamp.org/news/compiled-versus-interpreted-languages/)
3. [FCC Exercise: Debugging](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#debugging)
4. [MDN: SyntaxError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError)
5. [MDN: ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError)
6. [MDN: TypeError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError)


# 4.1: Intro to Logic

## Learning Objectives

By the end of this lesson, you should be able to do the following:

* Know how logic is used to make programs more complex
* Understand and use the `if` statement.
* Understand and use the equality operator: `==`

## Introduction

{% embed url="<https://www.youtube.com/watch?v=ywFgZIZXGoI>" %}

So far our apps have always performed the *same operations*, no matter the input. The next level of complexity is to create programs that perform *different* operations, depending on the input.

### What is Logic?

From a programming perspective, logic is the ability of the computer to **make decisions** based on input data.

To begin with logic we'll be using the most basic JavaScript logic syntax, the `if` condition. That means that some code will run or not depending on values we test. To start off with, those values will be what the user is typing in- so depending on what the user types, some different things will be displayed in the grey box.

## If Statement

An "**if statement**" is a control-flow "**code block**" that runs if a condition is `true`. A code block is a section of code surrounded by curly braces. We'll talk more about what `true` means when we introduce the boolean data type in [Module 4.3: Boolean And, Not](/4-conditional-logic/4.3-boolean-and-not).

### Simple Conditional Example: Secret Phrase

Let's write a program that changes the output value of `"hello world"` if we type in a particular phrase.

```javascript
var main = function (input) {
  // Set a default value for myOutputValue
  var myOutputValue = 'hello world';
  // If input is our secret phrase, change the value of myOutputValue
  if (input == 'palatable papaya') {
    myOutputValue = 'you wrote the secret phrase!';
  }
  // return myOutputValue as output
  return myOutputValue;
};
```

Our if statement is on line 5. The conditional inside it tests if `input` is equal to `'palatable papaya'`, our secret phrase. If `input` is equal to `'palatable papaya'`, the code runs between the curly braces on lines 5 and 7, i.e. the "if block". If `input` is not equal to our phrase, the if block does not run.

Code blocks may or may not run depending on "[**control flow**](https://en.wikipedia.org/wiki/Control_flow)", i.e. the logic of our app. The 1st way we learned to use code blocks was with functions. If statements are a 2nd way. We'll learn a 3rd code block syntax later in [6.2: Loops](/6-arrays-and-iteration/6.2-loops).

Try inputting secret and non-secret phrases into the program. Enter the secret phrase and click the button to see the different output. Enter anything else and click the button to see the default output.

{% hint style="info" %}
Note the distinction in our code example between variable ***declaration*** and ***assignment***. On line 2 we "declare" the variable `myOutputValue`. This creates the named container that we can store values inside. On line 5 we "assign" a new value to the `myOutputValue` container. The old value is overwritten and non-retrievable. Notice that declaration with the `var` keyword is only done *once* per variable. Please do not use `var` when assigning new values to existing variables in conditionals like if statements.
{% endhint %}

### Equality

We're using the "[**comparison operator**](https://www.w3schools.com/js/js_comparisons.asp)" `==` to test if `input` is equal to `'palatable papaya'`.

{% hint style="info" %}
There are two comparison operators in JavaScript to check for equality, `==`, known as the abstract equality operator, and `===`, the strict equality operator. For the purpose of this course, `==` will suffice, but you are free to explore and experiment. You can read more about the in-depth differences between them in [this ](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons)discussion.
{% endhint %}

## Comments

As our apps get more complicated, we can and should leave notes to ourselves and others to clarify what our code does. "**Comments**" let us write notes in our code files that are ignored on program execution. In JavaScript, comments are denoted by 2 slashes (`//`) at the start of the comment. Every programming language has commenting functionality, though commenting syntax varies by language.

```javascript
// This is an example comment. It won't actually "run".
```

## Knowledge Application: Dice Game

Let's recap and build onto [3.1: Functions ](/3-structuring-and-debugging-code/3.1-functions)by building a **function** that generates random dice numbers.&#x20;

We will be using this 'Dice Rolling function' as a base to explore Logic and Control Flow for the rest of this Module.

### Random Number Generation

To simulate dice, we first need random number generation. JavaScript can produce random numbers using a built-in "**library**" called [`Math`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) (*case-sensitive*). `Math` contains functions that perform common and helpful math operations.&#x20;

The function we need is `Math.random()`. **N*****ote the function call using ()***

```javascript
var myRandomValue = Math.random();
```

Calling `Math.random()` returns a random decimal number between 0 and 1, inclusive of 0 and exclusive of 1.&#x20;

Note that the `Math.random()` function does not take in an input.

Since we wish to simulate dice with numbers between 1 to 6 inclusive, we have to manipulate the randomly-generated number to get what we want.

To convert our random number to a valid dice roll value, we'll use another `Math` function: `Math.floor()`. We will follow the random integer generation example [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) to use `Math.floor()` to convert decimals to integers.

With `Math.random()` and `Math.floor()`, we can make a function that produces any random integer from 0 to a provided `max` number:

```javascript
var getRandomInteger = function (max) {
  // Generate a decimal from 0 through max + 1.
  // This decimal will be inclusive of 0 and exclusive of max + 1.
  var randomDecimal = Math.random() * (max + 1);

  // Remove the decimal with the floor operation.
  // The resulting integer will be from 0 through max, inclusive of 0 and max.
  var resultInteger = Math.floor(randomDecimal);

  return resultInteger;
};
```

### Dice Roll Program Logic

Since we wish to build a program that generates random dice numbers. We use the logic from the above `getRandomInteger` to always return an integer from 1 to 6. We call the new function `rollDice`.

```javascript
var rollDice = function () {
  // Generate a decimal from 0 through 6, inclusive of 0 and exclusive of 6.
  var randomDecimal = Math.random() * 6;

  // Remove the decimal with the floor operation.
  // This will be an integer from 0 to 5 inclusive.
  var randomInteger = Math.floor(randomDecimal);

  // Add 1 to get valid dice rolls of 1 through 6 inclusive.
  var diceNumber = randomInteger + 1;

  return diceNumber;
};
```

### Dice Game Logic

Using our new knowledge of '**logic**' in this chapter, let's implement a simple rule to create a "dice game": <mark style="background-color:blue;">if the user enters the same number as the dice roll, they win.</mark>

```javascript
var main = function (input) {
  // Generate a random dice number
  var randomDiceNumber = rollDice();

  // Default output value is 'you lose'.
  var myOutputValue = 'you lose';

  // If input matches randomDiceNumber, update output.
  if (input == randomDiceNumber) {
    myOutputValue = 'you win';
  }

  // Return output.
  return myOutputValue;
};
```

## Exercises

### **Follow Along**

Duplicate and run the code above.

### **Twice the Guess**

Update our dice game logic such that the user wins if the dice roll is 2 times the guess, e.g. a guess of 1 and roll of 2, a guess of 2 and roll of 4, etc. To win this updated game for a 6-sided dice, the user should only guess numbers between 1 and 3, but the game does not restrict what the user can guess.


# 4.2: Pseudo-Code, Boolean Or

## Learning Objectives

By the end of this lesson, you should be able to:

* Explain why writing pseudo-code can be helpful, and know how to write simple psuedo-code.
* Understand what logical operators are.
* Understand and use the logical OR operator.

## Introduction

{% embed url="<https://youtu.be/3QgxbnIOYnw>" %}

Let's update our dice game from [4.1: Intro to Logic](/4-conditional-logic/4.1-intro-to-logic) so that the user also wins if they guess within 1 of the dice roll. To encode this we will need a new kind of conditional syntax: "**logical operators**". We will also learn about "**pseudo-code**", a common method to plan logic before writing code.

## Pseudo-Code: Logical Expression Translation

As our code gets more complex, we will often want to plan our logic before writing code. This helps clarify our thoughts such that our code is more organised and we spend less time debugging.

### Example: Dice Game Pseudo-Code

Let's plan our logic for the updated dice game. A sample plan might look like this.

```
If the guess is correct, the user wins.
If the guess is off by 1, the user wins.
```

To start translating this to code, we can clarify the "off by 1" statement by breaking it down into the following 2 statements. We can also revise the "correct" statement using similar language.

```
If the guess plus one equals the dice roll, the user wins.
If the guess minus one equals the dice roll, the user wins.
```

Altogether we would have the following.

```
If the guess equals the dice roll, the user wins.
If the guess plus one equals the dice roll, the user wins.
If the guess minus one equals the dice roll, the user wins.
```

Notice how we reformulated sentences describing game logic at a "higher level" into a "lower-level" format that more closely resembles code. This step can be helpful when we are unsure how to translate higher-level logic descriptions to code.

#### Pseudo-Code Sentence

```
If the guess equals the dice roll, the user wins.
```

#### Corresponding Code Snippet

```javascript
if (input == randomDiceNumber) {
  myOutputValue = 'you win';
}
```

### The Importance of Pseudo-Code

Pseudo-coding is an important intermediate step to translate program requirements to code, helping us minimise logical errors. Before coding any program, try to translate program requirements into plain-English logical statements in code-comment format, then fill in your code beneath each line of pseudo-code.

Almost all developers pseudo-code, regardless of seniority. Even when we may not need pseudo-code to develop a program correctly, others reading our code will find it helpful to read the pseudo-code.

## Logical Operators

### Code Without Logical Operators

From our pseudo-code above we obtained the following specification.

```
If the guess equals the dice roll, the user wins.
If the guess plus one equals the dice roll, the user wins.
If the guess minus one equals the dice roll, the user wins.
```

We could translate this to a series of **if-statements**.

```javascript
if (randomDiceNumber == input) {
  myOutputValue = 'you win';
}

if (randomDiceNumber + 1 == input) {
  myOutputValue = 'you win';
}

if (randomDiceNumber - 1 == input) {
  myOutputValue = 'you win';
}
```

To write more concise code, we'll introduce another conditional syntax: logical operators. Logical operators allow us to construct more complex logical statements.

### Logical OR: Any of These Statements

The logical OR operator allows us to combine 2 [boolean expressions](https://en.wikipedia.org/wiki/Boolean_expression) into a single boolean expression. A boolean expression is an expression that evaluates to either `true` or `false`. To combine more than 2 boolean expressions in a single statement, we can use multiple OR operators.

Here is pseudo-code that more closely reflects OR logic.

```
If any of the following are true, the user wins.

- The guess equals the dice roll
- The guess plus one equals the dice roll
- The guess minus one equals the dice roll
```

We could also break our pseudo-code down more explicitly. This latter pseudo-code most closely resembles how we will construct our code.

```
If:

The guess equals the dice roll,

OR

The guess plus one equals the dice roll,

OR

The guess minus one equals the dice roll,

the user wins.
```

### Logical OR Syntax

The JavaScript syntax for logical OR is `||`. The final syntax for our updated dice game logic might look like the following.

```javascript
if (
  randomDiceNumber == input ||
  randomDiceNumber + 1 == input ||
  randomDiceNumber - 1 == input
) {
  myOutputValue = 'you win';
}
```

In [4.3: Boolean And, Not](/4-conditional-logic/4.3-boolean-and-not) we will learn about 2 more logical operators AND (`&&`) and NOT (`!`).

## Exercises (Base)

### Follow Along

Duplicate and run the code above.

### **Secret Words**

Change the original [secret word program in section 4.1](https://fundamentals.rocketacademy.co/4-conditional-logic/4.1-intro-to-logic#simple-conditional-example-secret-phrase) so that the user could enter more than one secret word- they can enter "neat noodles", "awesome ayam", "delicious dumplings" or the original word to see the secret message.

### **Easier Dice Game**

Change the dice game so that it's even easier. If the user guess is within 2 of the dice roll, they still win.

### **Even Easier Dice Game**

The user can guess by putting in one of two values: "odd" or "even". They win if the dice roll is odd or even.

## Exercises (More Comfortable)

### **Combo Game**

Change your dice game so that if the user types in "palatable papaya" instead of a dice guess, they also win.

### **Even Easier Dice Game Refactor**

There is a way to mathematically verify that a number is even using the `%` operator - the modulus operator. Google the solution to tell if a number is even in JavaScript, and what the modulus operator does and refactor the logic in the game to use it.


# 4.3: Boolean AND, NOT

## Introduction

In [4.2: Pseudo-Code, Boolean OR ](/4-conditional-logic/4.2-pseudo-code-boolean-or)we learned how to pseudo-code and use logical OR operators. In this module we will learn about the following.

1. Code control: how to control program inputs to quickly verify program logic.
2. Boolean values: what are boolean values and how are they stored in JavaScript?
3. Boolean AND operator
4. Boolean NOT operator
5. Conditional debugging: how to efficiently debug conditional logic.

## Code Control

{% embed url="<https://youtu.be/AYmtC4nWKsU>" %}

Sometimes we will want to control program inputs to verify program logic for specific inputs. This is especially relevant when we would otherwise not be able to control these inputs, for example when using a random number generator. Even though the user did not input the randomly-generated number, the number can be considered an input because it determines logic within the program.

No matter how small or large the range of randomness in our input, we want to be able to control this randomness during development to test our logic for potential inputs. In other words, we don't want to continuously enter numbers and click submit in our browsers until we reach a win state. If our dice rolls involved 100-sided dice, our hands would get tired.

We will control random number input to test winning conditions by removing randomness. We will "fix" the random number by changing `rollDice` to always return a specific value. In the following code snippet, `rollDice` always returns 6. Note that the `return` keyword also ends the execution of the function: `rollDice` never runs beyond line 2. We will remove `return 6;` once we're done testing.

```javascript
var rollDice = function () {
  return 6;
  // produces a float between 0 and 7
  var randomFloat = Math.random() * 7;
  // take off the decimal
  var resultInteger = Math.floor(randomFloat);
  return resultInteger;
};
```

## Boolean Values

Boolean operators are operators that return boolean values. Boolean operators consist of both logical operators (e.g. `||`, `&&`, `!`) and comparison operators (e.g. `==`, `<`, `>`). Boolean values are either `true`, or `false`. Boolean operators, similar to math operators (e.g. `+`, `-`, `*`, `/`), always return a new value that can be stored in a variable.

What is the value of `myVal` in each of the following examples?

**Math Operator Example**

```javascript
// the value of myVal is the result of the number 1 PLUS the number 2.
var myVal = 1 + 2;
```

**Boolean Operator Example**

```javascript
// the value of myVal is the result of the number 1 BOOLEAN EQUALS the number 2
var myVal = 1 == 2;
```

In previous modules we've seen number and string data types. Boolean data types are a 3rd data type. They represent a value that is `true` or `false`. Just like how variables can store the result of a math operation, variables can also hold the result of a logical, boolean operation.

**Boolean Variable Example**

Note the naming convention for variables that store booleans is to begin with a question word to signal that the variable's value is either `true` or `false`.

```javascript
// Assign true to the didUserWin variable
var didPlayerWin = true;
```

**Boolean Operation and Assignment Example**

Assign the result of `input == randomDiceNumber` to `didPlayerWin`. The result will be `true` or `false`. Notice this matches our dice game logic, which says that the player wins if their input matches the random dice number.

```javascript
var didPlayerWin = input == randomDiceNumber;
```

## Dice Game Example

We will add another dice to our dice game, and update our logic such that the player only wins if both dice rolls are the same value as the player's guess. We will utilize the AND and NOT boolean operators for this task.

### AND Operator

Use the boolean AND operator (`&&`) to validate if 2 boolean statements are both true.

**Pseudo Code**

```
if
the guess is equal to the first random number
AND
the guess is equal to the second random number
then the user wins.
```

**JavaScript**

```javascript
var main = function (input) {
  var randomDiceNumber1 = rollDice();
  var randomDiceNumber2 = rollDice();
  // The default output value is "you lose".
  var myOutputValue = 'you lose';
  // If the input matches both random dice numbers, output value is "you win".
  if (randomDiceNumber1 == input && randomDiceNumber2 == input) {
    myOutputValue = 'you win';
  }
  return myOutputValue;
};
```

### Dice Game with 2 Dice and Snake Eyes

{% embed url="<https://youtu.be/Aelo-Ay71oA>" %}

Let's add another rule to our 2-dice dice game: the player loses if the 2 dice roll "snake eyes": 2 1s.

### NOT Operator

**Non-equivalence Example**

Paired with `=`, `!=` is a "not equals" comparison operator, contrasting `==`. The following example runs line 2 if the value of `diceRoll` is not 2.

```javascript
if (diceRoll != 2) {
  console.log('dice roll is not 2!');
}
```

**Reverse-Boolean Example**

Use the boolean NOT operator (`!`) to "reverse" a boolean statement. The following code examples show a conditional that checks if the player did not win.

When comparing against `true` or `false` values, we might tend to write `didPlayerWin != true` in our conditional.

```javascript
var didPlayerWin = false;

if (didPlayerWin != true) {
  console.log('player didnt win!');
}
```

However, the best practice is to put the `!` operator in front of the boolean variable, like `!didPlayerWin`. The following example is semantically the same as the previous example.

```javascript
var didPlayerWin = false;

if (!didPlayerWin) {
  console.log('player didnt win!');
}
```

### Encode Snake Eyes with NOT Operator

**Dice Game with 2 Dice and Snake Eyes Pseudo Code**

```
if
the guess is equal to the first random number
AND
the guess is equal to the second random number
AND
the dice are NOT snake eyes
then the user wins.
```

**Snake Eyes Boolean Statement**

The following statement encodes snake eyes in our program, where both `diceRoll1` and `diceRoll2` have a value of 1.

```javascript
diceRoll1 == 1 && diceRoll2 == 1;
```

**NOT Snake Eyes Boolean Statement**

To express *NOT* snake eyes, we can negate the above boolean statement with the `!` operator, making sure to surround the snake eyes statement with parentheses (`()`) to indicate that the `!` applies to the entire snake eyes statement and not just the first part. The following evaluates to `true` when the dice rolls do *not* represent snake eyes, i.e. when `diceRoll1` and `diceRoll2` do not *both* have the value of 1.

```javascript
!(diceRoll1 == 1 && diceRoll2 == 1);
```

## Conditional Debugging

{% embed url="<https://youtu.be/yXtC954S2W4>" %}

We've written pseudo-code, we've written JavaScript, we've controlled and tested our logic, yet our code could still have errors. Let's analyse common conditional errors and learn strategies to diagnose them.

### Consider Common Conditional Errors

#### Boolean Expression Not Evaluating to True

When we use `&&` , both boolean statements must be true for the combined statement to be true. If we only need 1 of the boolean statements to be true, use `||` instead.

#### Boolean Expression has Syntax Error

Did we unintentionally use the assignment operator `=` instead of the comparison operator `==`?

#### Incorrect Logic in Boolean Statement

Are the parentheses in our boolean statement arranged such that the boolean logic matches what we wish to accomplish?

### Deconstruct and Verify Each Condition

If the above common conditional errors are insufficient to debug our problem, we can use a more fine-grained debugging strategy. By now, many of our conditionals comprise multiple boolean statements connected by logical operators such as `||`, `&&`, and `!`. If the program behaviour is incorrect, we can methodically deconstruct our conditionals to verify each component.

For a given conditional like the following, we can console log each component of the conditional. We can then inspect each variable and boolean expression value. Note the helpfulness of labelling each console log for output clarity. Try not to introduce bugs while debugging by mislabeling console logs.

#### Sample Conditional

```javascript
if (
  randomDiceNumber == input ||
  randomDiceNumber + 1 == input ||
  randomDiceNumber - 1 == input
) {
  myOutputValue = 'you win';
}
```

#### Sample Debugging Code

```javascript
console.log('random dice number:');
console.log(randomDiceNumber);
console.log('input');
console.log(input);
console.log('random dice equals input:');
console.log(randomDiceNumber == input);
console.log('random dice plus 1 equals input:');
console.log(randomDiceNumber + 1 == input);
console.log('random dice minus 1 equals input:');
console.log(randomDiceNumber - 1 == input);
```

## Exercises

{% hint style="info" %}
Share your work with your section: save the code you write into another file. Name it `share.js` (A file only for sharing in the community channel.) Send the code file as a snippet in your section community channel.
{% endhint %}

### Follow Along

Duplicate and run the dice game versions above.

### New Winning Conditions

Create new versions of our dice game for each of the following winning conditions.

1. User wins if guess is within 1 for any of 2 dice.
2. User wins if guess is within 1 for all 2 dice.
3. User wins if guess is within 1 of either dice but the user does not roll snake eyes.
4. User wins if guess is within 1 of either dice or if the user rolls snake eyes.

{% hint style="info" %}
If the above exercises are taking a long time, we may wish to complete the subsequent pre-class modules before returning to these exercises.
{% endhint %}

## Further Reading

Past students have found this [slide deck](https://www.cs.cmu.edu/~mrmiller/15-110/Handouts/boolean.pdf) helpful in understanding Boolean logic.


# 4.4: Input Validation

## Learning Objectives

By the end of this lesson, you should:

* Be familiar with the concept of "Data Types".
* Understand what *input validation* means and why we use it.
* Know how to use the `Number()` function to convert a string to a number.
* Know what the `NaN` data type is.

## Introduction

So far in any of our dice-guessing games, the program doesn't restrict players from entering "bananas", 38373, or any value other than 1 to 6. In the way we've written our code so far, there may not be errors for invalid input, but there will be situations in SWE Fundamentals where invalid input causes syntax or logical errors. To preempt these errors, we may wish to guide the player by providing feedback when their input is invalid.

We will use our dice game to demonstrate input validation. We'll first see how to detect if the player typed in a number, then we'll detect if the player's number is within the desired range of 1 to 6.

## Input Data-Type Validation

When running the `main` function via clicking the submit button, the `input` parameter will always be a *string* data type. The `input` string may sometimes *contain* number *characters* - e.g. "5", "9383733", or a combination of letter with number characters, e.g. "abc123", but the variable will nonetheless be of type string.

How can we check if the characters in `input` are *only* numbers? If we expect only number characters, how can we convert `input` to be a number and not a string?

### `Number` Function

We can try to convert a variable from string to number type with the `Number` function. If the string value has only number characters in it, `Number` will transform the string into a number.

```javascript
var input = '444';
var inputNum = Number(input); // inputNum is 444
```

{% hint style="warning" %}
In certain projects and exercises during SWE Fundamentals, we will compare the value of `input` with a number as part of program logic. This can result in unexpected errors if we do not transform `input` from string to number first.

Whenever we expect `input` to represent a number, we should always cast it to a number with `Number(input)` before using it. This will help prevent unexpected errors where `input` may not equal what we expect, for example when comparing "1" with 1.
{% endhint %}

### NaN

{% embed url="<https://youtu.be/P24Rp6HmMkM>" %}

When we use the `Number` function to convert a value that isn't only numbers, `Number` may return a `NaN` value. NaN stands for "not a number". For example, the following code generates `NaN`.

```javascript
var input = 'papayas';
Number(input);
```

NaN also occurs when we attempt a math operation that doesn't result in a valid number. The following are examples.

```javascript
2 * 'chocolate';
```

```javascript
'dogs' / 32;
```

```javascript
0 / 0;
```

Note that `NaN` is a valid value in JavaScript, like `0` or `1`. The following examples store `NaN` in variables.

```javascript
var count = NaN;
```

```javascript
var count = 'papayas' * 12;
```

```javascript
var input = 'papayas';
var inputCount = Number(input);
```

#### Number Type Validation Logic

{% embed url="<https://youtu.be/6RMjO0FbyQc>" %}

We can use NaN to write logic like the following.

> If we try to convert a value to a number and we get the result NaN, then the value is not a number.

#### Number.isNaN

To help us implement our logic above, JavaScript provides a `Number.isNaN` function that returns whether a given value has value `NaN`. This is because a direct comparison of a value with `NaN` doesn't work in JavaScript. The following code would not work as we might expect.

```javascript
// this will say FALSE, which is incorrect
Number('bananas') == NaN;
```

The following is an example of `Number.isNaN`, which is built-in to JavaScript. `Number.isNaN` returns a boolean value.

```javascript
var input = 'hello';
var result = Number(input);
console.log(Number.isNaN(result));
```

To complete our logic, we might add a conditional such that our code looks like the following.

This is an example of an if/else conditional. The `else` code block will be executed ***only when*** the `if` code block is not fulfilled.\
In this case, only when `Number(input)` is NOT "Not a Number" (meaning it IS a number), the program will execute the `else` code block to run the regular game logic.\
Otherwise, if `Number(input)` is "Not a Number", only the `if` code block is executed and the regular game logic within the `else` block will not.

```javascript
if (Number.isNaN(Number(input))) {
  myOutputValue = 'sorry please enter a number.';
} else {
  // regular app logic here
}
```

### Input Range Validation

{% embed url="<https://youtu.be/mjkj-OfCLKc>" %}

Now that we've verified that `input` contains only numbers, let's verify that input is between 1 and 6. We could write a long conditional like the following...

```javascript
if (
  input == 1 ||
  input == 2 ||
  // ... etc
) {
  // ...
}
```

...or we could express this range with comparison operators less than or equal to (`<=`) and greater than or equal to (`>=`). The if conditional in both examples evaluates to `true` when `input` is between 1 and 6.

```javascript
// if number is greater than or equal to 1 AND less than or equal to 6
if (input >= 1 && input <= 6) {
  // number is between 1 and 6
}
```

Note the functionality of the 2nd example is the same as the 1st, easier to understand, and easier to write, especially when we have a wider range, for example with a 20-sided dice. There are other ways to validate a number range, for example with less than (`<`) and greater than (`>`) operators like we do below.

## Dice Game Code With Input Validation

Our dice game code looks like the following with input validation.

```javascript
var rollDice = function () {
  // produce a decimal between 0 and 6
  var randomDecimal = Math.random() * 6;
  // remove the decimal
  var randomInteger = Math.floor(randomDecimal);
  // add 1 to get a number between 1 and 6 inclusive
  var diceNumber = randomInteger + 1;
  return diceNumber;
};

var main = function (input) {
  var myOutputValue = '';

  // first check if input is a number
  if (Number.isNaN(Number(input)) == true) {
    myOutputValue = 'sorry please enter a number.';
  } else {
    // then check if input is between 1 and 6
    if (input < 1 || input > 6) {
      myOutputValue = 'sorry please enter a number from 1 - 6';
    } else {
      // the input is 1-6, go ahead with the dice game
      var randomDiceNumber = rollDice();
      if (randomDiceNumber == input) {
        myOutputValue = 'you win';
      } else {
        myOutputValue = 'you lose';
      }
    }
  }

  return myOutputValue;
};
```

### Simplify Logic with Multiple `return` Statements in Single Function

You may notice that the above example has several levels of nested if and else statements. If we have more types of input validation, this can make our code unnecessarily complex. Luckily, there is a simple way to reduce complexity by using multiple `return` statements in our functions.

Notice the multiple `return` statements in the `main` function below. This simplifies our logic by reducing nesting of if and else blocks. Functions exit after `return` statements, i.e. nothing in the function is executed after `return`, making `return` statements convenient ways to exit our logic if input is invalid.

```javascript
var rollDice = function () {
  // produce a decimal between 0 and 6
  var randomDecimal = Math.random() * 6;
  // remove the decimal
  var randomInteger = Math.floor(randomDecimal);
  // add 1 to get a number between 1 and 6 inclusive
  var diceNumber = randomInteger + 1;
  return diceNumber;
};

var main = function (input) {
  var myOutputValue = '';

  // first check if input is a number
  if (Number.isNaN(Number(input)) == true) {
    myOutputValue = 'sorry please enter a number.';
    return myOutputValue;
  }

  // then check if input is between 1 and 6
  if (input < 1 || input > 6) {
    myOutputValue = 'sorry please enter a number from 1 - 6';
    return myOutputValue;
  }

  // the input is 1-6, go ahead with the dice game
  var randomDiceNumber = rollDice();

  if (randomDiceNumber == input) {
    myOutputValue = 'you win';
    return myOutputValue;
  }

  myOutputValue = 'you lose';
  return myOutputValue;
};
```

## Exercises

### Add Validation to Past Game

Choose one of your previous dice game implementations and add validation logic from this module.


# Additional Resources 4

For the curious and the hungry

## Introduction <a href="#introduction" id="introduction"></a>

If you'd like to learn more, this page contains a non-exhaustive, unordered list of useful resources. These resources are primarily related to Module 4, but also expand the scope of what has been covered, and touch on concepts and fundamentals that we will cover in future modules. You will see some of these resources repeated in other pages.

## Logic

1. [Brilliant.org: Computer Science Fundamentals](https://brilliant.org/courses/computer-science-essentials/)
2. [JavaScript.info: Comparisons](https://javascript.info/comparison)
3. [FCC: Basic JavaScript - Use Conditional Logic with If Statements](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-conditional-logic-with-if-statements)
4. [W3S: JavaScript `if else if`](https://www.w3schools.com/js/js_if_else.asp)\`\`
5. [Kenrickles: `ifs` vs `if else if`code demonstration](https://replit.com/@kenrickles/Difference-between-MultipleIfs-and-If-else-Ifs#index.js)
6. [MDN: Making Decisions in Your Code](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals)
7. [W3S: JavaScript Switch Statement](https://www.w3schools.com/js/js_switch.asp)
8. [Digital Ocean: How to Use the Switch Statement in JavaScript](https://www.digitalocean.com/community/tutorials/how-to-use-the-switch-statement-in-javascript)

## Input Validation

1. JavaScript String Methods:
   1. [.toLowerCase()](https://www.w3schools.com/jsref/jsref_tolowercase.asp)
   2. [.toUpperCase()](https://www.w3schools.com/jsref/jsref_touppercase.asp)
   3. [.trim()](https://www.w3schools.com/jsref/jsref_trim_string.asp)
   4. [.includes()](https://www.w3schools.com/jsref/jsref_includes.asp)
   5. [.split()](https://www.w3schools.com/jsref/jsref_split.asp)


# 5.1: Program Lifecycle and State

## Learning Objectives

By the end of this lesson, you should be able to:

* Explain the difference between a global and local variable.
* Understand when and why to use global variables.
* Declare and use global variables.
* Briefly explain "function scope".

## Introduction

{% embed url="<https://www.youtube.com/watch?v=oxxwcMJN8ec>" %}

Our programs have so far handled ephemeral *(temporary)* data that exists only while `main` or the relevant parent function is running. Now we will handle data that ***persists across*** runs of `main`, and functions in our app in general.

## Scope Hierarchy

Variables defined "higher up" the scope hierarchy will be available to reference in "lower" scopes, but not the other way around.

Globally-defined variables can be accessed in function scope and block scope, and anywhere else in the program, hence *global.* Variables defined in block scope can only be accessed within that block.

![](https://www.stevethedev.com/storage/app/uploads/public/5aa/d54/a47/5aad54a47d2e0123286333.png)

### Global Scope

Any variables defined outside of a function or a block of code exists in global scope. This include function definitions. So `main`, and any other functions we have written are in global scope. This allows us to *call* the function inside other functions or nested blocks of code.

So far, we have been creating variables inside of a function or a block of code, but nothing is stopping us from creating a variable at the "top level" of `script.js`, in global scope.

### Global Variables

We will use our dice game to demonstrate the value of data *persistence*. In a dice game, we may want to keep track of the "bank roll" or score for the duration of our game. We need a syntax to store a value (bank roll in this case) that we read and update when `main` runs and is also available ***the next time*** `main` runs.

The syntax we will use is called "**global variables**". Global variables in SWE Fundamentals will persist from **when the program loads** in the browser to when **we close the tab or reload the page**. Try running the following code line by line in Chrome DevTools. The variable `number` persists across our commands, but when we refresh the page, `number` is no longer available. Similarly, our global variable data will persist across function calls, but **not across browser sessions**.

```javascript
var number = 5;
number = number * 2;
number;
```

### Function Scope

Sensibly, variables declared within the function definition exist in function scope. When your program first loads, the functions are defined, but are not yet *executed* until a function call is made. You can verify this by opening the console, and checking the value of `main`.

Understand that the function `main` that we have been using is defined in the **global scope**, so the browser knows what it is, but attempting to access any variables defined within the function via the console will result in an error.

Once the function has been executed, the program returns to the scope from when the function was called, and all the variables declared and used by the program within the function are effectively forgotten. **Only the return \_value**\_\*\* persists\*\*. This return value, as you have already been doing before, is stored into another variable.

Consider the example below where `convertKmToMiles(input)` is assigned to `myOutputValue` (line 6).

```javascript
var convertKmToMiles = function (input) {
  return input / 1.609;
};

var main = function (input) {
  var myOutputValue = convertKmToMiles(input);
  return myOutputValue;
};
```

Different functions have their own scope. **Variables declared in one function are not accessible in another function**. Hence it is possible to re-use variable names in different functions, or more generally, in different scopes. However, you are strongly advised against this.

In contrast to "global variables" then, "local variables" are variables created within a smaller scope within the global scope.

Recall the `main` function we've been using so far. In this function, `myOutputValue` only exists during the execution of `main`, corresponding to 1 Submit-button click.

If we try to inspect the value of `myOutputValue` in the console after clicking Submit, `myOutputValue` doesn't exist.

```javascript
myOutputValue;
```

This behaviour is common to all variables declared inside a function, and a demonstration of **"function scope"** in JavaScript. This means that variables declared in a function are available for the life of that function, then they disappear.

### Block Scope

Block scoping applies to any variable defined in a block of code within a pair of `{}`. In SWE Fundamentals, this is mostly blocks of code defined by if-statements.

Similar to Function Scope, once the program exits the block and returns to a higher scope, variables declared within the block are effectively forgotten and inaccessible.

## Global State

{% embed url="<https://www.youtube.com/watch?v=xVIAh_o4mPc>" %}

Building on the logic above, global variables can thus be used as a "global state" of sort.

This is the idea that we can **declare variables outside** of functions and have those variables ***persist across*** function calls, keeping their values intact.

In this example, we persist `papayaCount`, in this case a count of the number of times a user has clicked Submit. `papayaCount` is part of `myOutputValue`, which shows the user how many times they have clicked Submit.

```javascript
// Variables in the Global Scope - papayaCount and main
var papayaCount = 0;
var main = function (input) {
  // Variables in the Function Scope (of the main function) - myOutputValue
  papayaCount = papayaCount + 1;
  var myOutputValue = 'You have ' + papayaCount + ' papayas';
  return myOutputValue;
};
```

### Global Variables for Dice Guessing

{% embed url="<https://youtu.be/X-b_LJAJIsU>" %}

Bank roll or score is an application of the global "counter" variable to our dice game. In the following example, we increment `bankRoll` every time the player correctly guesses the dice roll.

```javascript
var bankRoll = 10;

var main = function (input) {
  var randomDiceNumber = rollDice();

  var myOutputValue = 'you lose. current bank roll: ' + bankRoll;

  if (randomDiceNumber == input) {
    bankRoll = bankRoll + 1;

    myOutputValue = 'you win. current bank roll: ' + bankRoll;
  }

  return myOutputValue;
};
```

## Exercises (Base)

### Follow Along

Follow along with the videos and duplicate the code.

### **App Setup**

For the following exercises, start with the SWE Fundamentals Starter Code template and replace the code in `script.js` with the following dice game code.

```javascript
var rollDice = function () {
  // produces a decimal starting from 0 and ending BEFORE 6 (5.999999...)
  var randomDecimal = Math.random() * 6;

  // take off the decimal -> 0 to 5
  var randomInteger = Math.floor(randomDecimal);

  // it's a number from 0 - 5 ... add 1 -> 1 to 6
  var diceNumber = randomInteger + 1;

  return diceNumber;
};

var main = function (input) {
  var randomDiceNumber = rollDice();

  var myOutputValue = 'you lose';

  if (randomDiceNumber == input) {
    myOutputValue = 'you win';
  }

  return myOutputValue;
};
```

### **Last Roll**

Create a version of the dice game that tells the user what their previous dice roll was.

#### Sample Output

```
Your last roll was 4. You just rolled a 3. You guessed 3. You win!
```

### **Win / Loss**

As the user continues to play the game, tell them what their current win / loss percentage is.

#### Sample Output

```
You win 23.5% of the time. You just rolled a 4. You guessed 3. You lose!
```

## Exercises (More Comfortable)

### **Most Rolled**

Keep track of the number that's rolled the most times.

#### Sample Output

```
You just rolled a 4. 2 is the number you roll the most. You guessed 3. You lose!
```

### **Guessing**

If the player guess is off-by-1 they win 1 point. If the player guess is exact they win 2 points.

### **Advanced Guessing**

The player guess can be off by up to 4. If the player guess is off-by-4 they win 1 point. Off-by-3, 2 points, off-by-2, 3 points, off-by-1, 4 points, exact, 5 points.

## Reference Solutions

[Click here ](https://github.com/rocketacademy/fundamentals-starter-code/blob/8.1-refSolns-moreComfortable/script.js)to view the reference solution. Please only refer to the reference solution after you have attempted the exercise. Note that there are many ways to implement the exercise and the reference solution is only 1 way.


# 5.2: Program State for Game Modes

## Learning Objectives

By the end of this lesson, you should:

* Know how to use [global variables](/5-managing-state-and-input-validation/5.1-program-lifecycle-and-state#global-variables) to change the "state" of your program.
* Be familiar with the concept and practice of "refactoring"

## Introduction

{% embed url="<https://youtu.be/rVJq7gFYrxc>" %}

We can use global state to expand the functionality of our apps. For games, we can use global state to keep track of game modes to treat inputs differently depending on the game mode.

## Global State for App Modes

The following code outputs a different default quote depending on whether the app mode is green or blue. Note that we get the same output until we command the program to change modes. To change app modes, we can use the special input words `greenmode` and `bluemode`. Note that the initially-assigned value of `mode` is the default app mode.

```javascript
var mode = 'green';

var main = function (input) {
  if (input == 'greenmode') {
    mode = 'green';
  } else if (input == 'bluemode') {
    mode = 'blue';
  }

  var myOutputValue =
    'A fool sees not the same tree that a wise man sees. -William Blake';

  if (mode == 'blue') {
    myOutputValue =
      'The sea, once it casts its spell, holds one in its net of wonder forever. -Jacques Cousteau';
  }

  return myOutputValue;
};
```

## App Mode to Accept and Store User Name

{% embed url="<https://youtu.be/q5ovHXBy82U>" %}

In addition to keeping score, we may also want to persist data such as user name to personalise our app. In the following example, we persist user name when in a "waiting for user name" app mode. At the beginning of the game, the first input is saved as the user name. After that first input, the program changes the game mode to "dice game", and subsequent inputs are considered inputs to the dice game. Throughout the game, the app can refer to the `userName` variable to personalise output for the current user.

```javascript
var currentGameMode = 'waiting for user name';
var bankRoll = 10;
var userName = '';

var rollDice = function () {
  var randomDecimal = Math.random() * 6;
  var randomInteger = Math.floor(randomDecimal);
  var diceNumber = randomInteger + 1;
  return diceNumber;
};

var main = function (input) {
  var myOutputValue = '';

  if (currentGameMode == 'waiting for user name') {
    // if the game mode is user name... set the name as the input
    userName = input;

    // now that we have the name, switch the mode
    currentGameMode = 'dice game';

    myOutputValue = 'Hello ' + userName;
  } else if (currentGameMode == 'dice game') {
    // if the game mode is dice game... define userGuess as the input
    var userGuess = input;
    // dice game logic
    var randomDiceRoll = rollDice();
    myOutputValue =
      userName +
      ' you lost! you guessed: ' +
      input +
      '. you rolled: ' +
      randomDiceRoll +
      '. current bank roll: ' +
      bankRoll;

    if (userGuess == randomDiceRoll) {
      bankRoll = bankRoll + 1;
      myOutputValue =
        userName +
        ' you won! you guessed: ' +
        input +
        '. you rolled: ' +
        randomDiceRoll +
        '. your current bank roll: ' +
        bankRoll;
    }
  }

  return myOutputValue;
};
```

## Refactoring Code

{% embed url="<https://youtu.be/Uq0K9LdoSqE>" %}

As our programs become larger and more complicated we want to be able to "**refactor**" our programs to be more concise, understandable, and testable. We can use functions as subroutines and use parameters and return values to help us control the flow of data in our program. The following example is a refactored version of the code from the previous section, where we extract the dice game logic and put it into a new function `playDiceGame`. This is desirable because it makes it easier to skim the logic of our app by reading the `main` function. It also makes it easier to test logic in isolation, for example by running functions independently in the browser console.

```javascript
var currentGameMode = 'waiting for user name';
var bankRoll = 10;
var userName = '';

var rollDice = function () {
  var randomDecimal = Math.random() * 6;
  var randomInteger = Math.floor(randomDecimal);
  var diceNumber = randomInteger + 1;
  return diceNumber;
};

var playDiceGame = function (userName, userGuess) {
  var message = '';

  // dice game logic
  var randomDiceRoll = rollDice();
  message =
    userName +
    ' you lost! you guessed: ' +
    userGuess +
    '. you rolled: ' +
    randomDiceRoll +
    '. current bank roll: ' +
    bankRoll;

  if (userGuess == randomDiceRoll) {
    bankRoll = bankRoll + 1;
    message =
      userName +
      ' you won! you guessed: ' +
      userGuess +
      '. you rolled: ' +
      randomDiceRoll +
      '. your current bank roll: ' +
      bankRoll;
  }

  return message;
};

var main = function (input) {
  var myOutputValue = '';

  if (currentGameMode == 'waiting for user name') {
    // set the name
    userName = input;

    // now that we have the name, switch the mode
    currentGameMode = 'dice game';

    myOutputValue = 'Hello ' + userName;
  } else if (currentGameMode == 'dice game') {
    myOutputValue = playDiceGame(userName, input);
  }

  return myOutputValue;
};
```

## Exercises

### Follow Along

Duplicate the Blue / Green app above.

### Red Mode

Add a Red mode to the game. A reference solution can be found [here](https://github.com/rocketacademy/fundamentals-starter-code/tree/8.2-refSolns).


# Additional Resources 5

For the curious and the hungry

## Introduction <a href="#introduction" id="introduction"></a>

If you'd like to learn more, this page contains a non-exhaustive, unordered list of useful resources. These resources are primarily related to Module 5, but also expand the scope of what has been covered, and touch on concepts and fundamentals that we will cover in future modules. You will see some of these resources repeated in other pages.

## Scope

1. FreeCodeCamp Exercises:
   1. [Global Scope and Functions](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/global-scope-and-functions)
   2. [Local Scope and Functions](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions)
   3. [Global vs Local Scope in Functions](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/global-vs--local-scope-in-functions)
2. [A Simple Explanation of Scope in JavaScript](https://dmitripavlutin.com/javascript-scope/)
3. [Understanding Scope in JavaScript](https://www.digitalocean.com/community/tutorials/understanding-scope-in-javascript)
4. [Everything You Wanted to Know About JavaScript Scope](https://ultimatecourses.com/blog/everything-you-wanted-to-know-about-javascript-scope)


# 6.1: Arrays

## Learning Objectives

By the end of this lesson, you should be able to:

* Explain what an array is.
* Use arrays to store similar "kinds" of data.
* Access data stored in an array.
* Use the built-in array methods of `push()` and `pop()` to manipulate data in an array

## Introduction

{% embed url="<https://youtu.be/CI09j_aHLE0>" %}

We've built relatively complex programs using functions and conditionals with global state. In this module we will learn a new data type, or "data structure", to be precise: dynamic-length data "**arrays"**. We'll then learn how to manipulate arrays using a syntax called "**loops**". Just like each concept we've learned previously, the mechanic of the individual concepts will be relatively simple, but when we combine these concepts with previous concepts, the complexity of our apps can increase greatly.

## Arrays are a Type of Data Collection

Values of each data type we have seen so far can be stored inside variables, e.g. numbers, strings, booleans, and even functions. Arrays can also be stored inside variables, but have an additional capability: to store 0 or more variables inside them. Arrays can thus be described as variable-length **"data collections"**, because they are a "collection" of data.

## Arrays Only Store 1 "Kind" of Data at a Time

Arrays are data structures that store 0 or more values of the same kind. By "kind" we don't just mean the same data type, e.g. numbers, strings, or booleans. By "kind" we also mean the same *conceptual* kind of data. For example, we might store computer-generated dice rolls in an array, or user guesses in an array, where both dice rolls and user guesses are numbers, but we would likely not store both dice rolls and user guesses in the *same* array, because each is a different "kind" of data.

{% hint style="warning" %}
JavaScript lets us add any data type into any array, regardless of what's already inside. The following would be considered valid JavaScript syntax.

```javascript
var myValues = [23, 'rocks', true, 0.345, 'awesome'];
```

However, the **concept** of the array is for holding data of the same kind, e.g. numerical dice rolls, and this almost always means the data is of the same JavaScript data type. Please do not deviate from this in SWE Fundamentals.
{% endhint %}

## 2 Conceptual Types of Arrays

We can use arrays in 2 conceptual ways: to store static-length data and to store dynamic-length data.

### Arrays as Static Data Collections

1 way we can use arrays is to store data that will never change. Examples of this are names of days of the week, and letters in the English alphabet. After we initialise these arrays, we will most likely only read from them, and not edit the values inside the arrays.

#### Example: Array Containing Names of Days of the Week

```javascript
var daysOfTheWeek = [
  'Monday',
  'Tuesday',
  'Wednesday',
  'Thursday',
  'Friday',
  'Saturday',
  'Sunday',
];
```

**Example: Array Containing Letters in the Alphabet**

```javascript
var letters = ['a', 'b', 'c'];
```

### Arrays as Static-Length Collections with Dynamic Data

Another way we can use arrays is to store data that may change, but will always have the *same* *number* of elements. An example of this is storing temperatures of each day in the past week. There are always 7 days in the past week, thus there will always be 7 elements in our array, but the *value* of each element can change depending on the temperature on the relevant day.

**Example: Temperatures of Each Day in Past Week**

```javascript
var dailyAverageTemperatureInPastWeek = [30, 32, 29, 34, 36, 38, 32];
```

### Arrays as Dynamic Data Collections

We can represent data that our program needs to alter as it runs. The program is responsible for keeping track of these data values, and making the array grow larger or smaller.

**Record a list of all guesses a user makes in the game.**

```javascript
var winningDiceGuesses = [3, 4, 2, 1, 4];
```

#### List of the sales recorded up to the current day (whichever current date this program runs)

```javascript
var salesThisMonth = [34, 23, 12, 78, 56];
```

## Array Properties

Arrays have unique properties that allow us to represent data in new ways: **Position** and **order**.

### Position

We access elements in an array through **"indexes"** that represent the position of each array element. In the following example, element 1 is at index 0, element 2 at index 1, and element 3 at index 2. Arrays are 0-indexed, meaning the first element is always at index 0. Index 0 is always the left-most array position, and the last index is the right-most array position.

```
  0    1    2
['a', 'b', 'c']
```

We can use square-bracket (`[]`) syntax to retrieve any element in an array by specifying that element's index in the square brackets.

```javascript
var letters = ['a', 'b', 'c'];
var value = letters[2];
```

{% hint style="info" %}
What happens when we try to access an array element that doesn't exist?

```javascript
letters[234534534534];
```

{% endhint %}

#### Using User Input as Array Index

The following example uses user input to retrieve a value at a specific index in the `letters` array.

```javascript
var letters = ['a', 'b', 'c'];

var main = function (input) {
  var myOutputValue = 'your letter: ' + letters[input];
  return myOutputValue;
};
```

### Order

Array positions imply order, e.g. the element at index 0 comes before the element at index 1. The following array implies "a" is before "b".

```javascript
var letters = ['a', 'b', 'c'];
```

## Array Data Manipulation

Let's learn how to alter, insert, and remove data from arrays. Notice the following code does not manipulate array values. It stores the value of the 3rd array element in a variable `value`, but does not alter the `letters` array.

```javascript
var letters = ['a', 'b', 'c'];
var value = letters[2];
```

The following are methods to alter values in arrays.

### Altering Existing Values in Arrays

Create an array with values inside.

```javascript
var temperatures = [23, 43];
```

Alter a value inside the array by assigning a new value to the original value's location in that array. This will only alter the value at the specified location in the array, and not any other values. This allows us to reassign values in the array after we initialise the array.

```javascript
// Reassign the value at index 0 to a new value.
temperatures[0] = 99;
```

### Inserting and Removing New Elements from Arrays

There are 2 methods we will use often in SWE Fundamentals to add and remove elements from arrays: `push` and `pop`.

#### `push`

`push` adds a value to the **end** of an existing array. `push` accepts the value to be inserted as a parameter.

```javascript
var temperatures = [23, 43];
// Add the parameter to push (33) to the end of the temperatures array.
// The temperatures array will be [23, 43, 33].
temperatures.push(33);
```

#### **`pop`**

`pop` removes the **last** element from an array and *returns* it.

```javascript
var temperatures = [23, 43];
// Remove the last element (43) from the temperatures array.
// The temperatures array will be [23], and lastElement will be 43.
var lastElement = temperatures.pop();
```

### Example: Add User Input to Array

The following is an example dice game that records and outputs all prior user guesses.

```javascript
// Store guesses in a global array that persists across Submits.
var guesses = [];
var main = function (input) {
  // Add the user's guess to the guesses array.
  guesses.push(input);
  // Generate a random dice number.
  var randomDiceNumber = rollDice();
  // Initialise output to communicate loss.
  // Output the record of all guesses regardless of loss or win.
  var myOutputValue = 'You lose. Your guesses: ' + guesses;
  // If the guess matches the dice roll, change output to communicate win.
  if (randomDiceNumber == input) {
    myOutputValue = 'You win. Your guesses: ' + guesses;
  }
  // Return output value.
  return myOutputValue;
};
```

## Exercises

### Follow Along

Implement the above code and verify results.


# 6.2: Loops

## Learning Objectives

By the end of this lesson, you should be able to:

* Explain how loops are used in the control flow of a program.
* Use a `while` loop to run a code block for a fixed number of times.
* Use loops within loops.
* Be familiar with both the `for`-loop and `while`-loop syntax.

## Introduction

{% embed url="<https://youtu.be/wn3G_OO32kg>" %}

We've defined an array, added values to it, and inspected those values individually, but haven't yet learned how to systematically manipulate each element in the array, no matter how long the array is. To do this we will learn 1 more control structure: "**loops"**.

In SWE Fundamentals we will mostly use loops to iterate over array elements. Loops can also be used without arrays, for example to perform an action until a condition is no longer `true`, but we will not see this often in SWE Fundamentals.

A loop defines a **code block** (with curly braces) that runs until the loop condition is no longer met. We'll look at loops in isolation first, then see them in the context of arrays.

### While Loop

While loops are the most fundamental type of loop in programming, and the concept exists in many programming languages. The following is a "while loop" that runs 10 times, i.e. until its condition is no longer met. Notice how we define a counter before the loop, and increment the counter at the end of the loop. The loop finishes when the counter reaches 10.

```javascript
// Initialise a counter to 0.
var counter = 0;
// Set the while loop condition to continue when counter is less than 10.
while (counter < 10) {
  // Log hello with each iteration of the loop.
  console.log('hello');
  // Increment the counter by 1 at the end of each loop iteration.
  counter = counter + 1;
}
```

#### While Loop with Input-Based Condition

Let's create a program that outputs values in a loop, where the loop condition depends on user input.

```javascript
var main = function (input) {
  var myOutputValue = '';
  var counter = 0;
  // Continue the loop while counter is less than the input value
  while (counter < input) {
    // Add 1 "yes" to the output for every loop iteration.
    myOutputValue = myOutputValue + 'yes';
    counter = counter + 1;
  }
  return myOutputValue;
};
```

{% hint style="warning" %}
Note that except for rare exceptions, the incrementation of the counter (`counter = counter + 1`) should be the last statement in the loop block. If you find yourself writing any statements below that, it may not be what you intended.
{% endhint %}

### Loops and Conditionals

{% embed url="<https://youtu.be/ozrUPHZWfIw>" %}

#### While Loop with Input-Based Condition and Conditionals Inside Loop

Let's create a program that outputs values in a loop, where loop condition depends on user input, with additional conditional statements inside the loop. In the following example, the conditionals inside the loop help the program combine 2 different strings into program output.

```javascript
var main = function (input) {
  var myOutputValue = '';
  var counter = 0;
  // Continue the loop while counter is less than the input value
  while (counter < input) {
    // If counter is less than 5, add "yes" to output
    if (counter < 5) {
      myOutputValue = myOutputValue + 'yes';
      // Otherwise, add "no" to output
    } else {
      myOutputValue = myOutputValue + 'no';
    }
    counter = counter + 1;
  }
  return myOutputValue;
};
```

#### Conditional Logic Variations

Loops and conditionals alone are powerful tools to create output patterns. One of the main tricks with loops is identifying the pattern we want and working backward to construct the logic within the loop. The following example uses the modulus (`%`) operator in a conditional in a loop to alternate strings in output.

```javascript
var main = function (input) {
  var myOutputValue = '';

  var counter = 0;
  while (counter < input) {
    // If counter is even, add "yes" to output
    // The modulus (%) operator returns the remainder after division
    // If a number divided by 2 equals 0, we consider it even.
    if (counter % 2 == 0) {
      myOutputValue = myOutputValue + 'yes';
      // Otherwise, add "no" to output
    } else {
      myOutputValue = myOutputValue + 'no';
    }
    counter = counter + 1;
  }

  return myOutputValue;
};
```

### Loops and Functions

{% embed url="<https://youtu.be/5qeXMmGRhZY>" %}

We can also combine loops and functions. Functions in loops allow us to move code blocks (i.e. complex logic) outside loop definitions, breaking down our code into smaller components, helping simplify our code logic.

In the following example, we define `rollDice` as a standalone function, and call `rollDice` from inside our loop. This helps keep our loop logic clean by separating the details of `rollDice` out from the loop.

```javascript
var main = function (input) {
  var myOutputValue = '';
  var counter = 0;
  while (counter < input) {
    // Roll dice inside the loop, generating a random dice roll each iteration
    var diceRoll = rollDice();
    // Add each dice roll to output
    myOutputValue = myOutputValue + ' ' + diceRoll + ' ';
    // Increment counter at end of each iteration
    counter = counter + 1;
  }
  return myOutputValue;
};
```

### Loops and Loops

{% embed url="<https://youtu.be/wxUafGMsOw4>" %}

### Nested Loops to Simulate Dimensions

If we put a loop inside a loop we can represent 2 dimensions of output. Note we use `<br>` to create new rows. `<br>` is a newline HTML tag that can help us format our output.

```javascript
var main = function (input) {
  var myOutputValue = '';
  // Initialise the outer counter, rowCounter
  var rowCounter = 0;
  while (rowCounter < input) {
    // Inside the outer loop, initialise the inner counter, columnCounter
    var columnCounter = 0;
    // Every time the outer loop runs, the inner loop runs repeatedly until
    // the inner loop condition is met.
    while (columnCounter < input) {
      // Each time the inner loop runs, it adds "x" to output
      myOutputValue = myOutputValue + 'x';
      columnCounter = columnCounter + 1;
    }
    // At the end of each outer loop, add a <br> tag to begin a new row
    myOutputValue = myOutputValue + '<br>';
    rowCounter = rowCounter + 1;
  }
  // After the outer loop has run to completion, return the output compiled
  // by the above loops.
  return myOutputValue;
};
```

## For Loops

Most languages have variations on the while loop above that behave similarly. One common variation is the "for loop". For loops are a more concise syntax for looping over a fixed number of iterations. Whenever we have a fixed number of iterations we should use a for loop if possible. The 2 following examples behave the same, but the for loop syntax is more concise.

### While Loop Syntax

```javascript
// Initialise counter
var counter = 0;
// Declare loop condition
while (counter < 10) {
  console.log('hello');
  // Increment counter
  counter += 1;
}
```

### For Loop Syntax

```javascript
// Initialise counter, declare loop condition, and increment counter in 1 line
for (var counter = 0; counter < 10; counter += 1) {
  console.log('hello');
}
```

The key difference in for loop syntax is that **all loop management code is consolidated in the top parenthesis group**. However, when the code runs, each step actually **happens in the same order as in the while loop example**. These steps are the following.

1. Declare and initialise counter variable
2. Evaluate condition
3. Increment counter

To solidify understanding of loops, we suggest using while loops until you are comfortable with loop mechanics.

{% hint style="info" %}
In other code examples you may see the incrementation step replaced by `counter++`. This adds 1 to `counter`. At Rocket we prefer ESLint's recommendation of `counter += 1` syntax. See ESLint's reasons against `++` syntax [here](https://eslint.org/docs/rules/no-plusplus).
{% endhint %}

## Base Exercises

### Follow Along

Implement the above code.

### Simple Loop with Variations

1. Create a loop in the `main` function. Make the loop run 6 times, adding `"hello"` to `myOutputValue` with each loop iteration.
2. What happens if `counter` starts as a number other than zero?
3. What happens if, inside the loop, you alter the `counter` by adding a number other than one?
4. What happens if you change the condition inside the loop from `counter < 6` to `counter <= 6`?

### Loop within Loop

1. Create nested loops in the `main` function, where the outer loop runs 3 times and the inner loop runs 3 times per outer loop. Concatenate `"hello"` to `myOutputValue` in the inner loop. How many times do we see `"hello"`?
2. Add `"<br>"` to `myOutputValue` in the outer loop so that the program makes a new line for each outer loop.
3. What happens if `outerCounter` starts as a number other than zero?
4. What happens if `innerCounter` starts as a number other than zero?
5. What happens if, inside the loop, you alter `outerCounter` by adding a number other than one?
6. What happens if, inside the loop, you alter `innerCounter` by adding a number other than one?
7. What happens if you change the outer loop condition from `outerCounter < 3` to `outerCounter <= 3`?
8. What happens if you change the inner loop condition from `innerCounter < 3` to `innerCounter <= 3`?
9. Update loop conditions to use `input` to control how many times the loops run.
10. Update our code such that the inner loop runs twice the number of times as the outer loop. How many more times do we see `"hello"`?

### Infinite Loop

Make a loop that never stops running. Be prepared to stop / kill this Chrome tab, because it will freeze. We should be able to observe this tab's performance in Windows Task Manager or MacOS Activity Monitor.


# 6.3: Loops with Arrays

## Learning Objectives

By the end of this lesson, you should be able to:

* Use the built-in `.length` array property.
* Use either a while or for loop to access or manipulate elements of an arbitrary-length array.

## Introduction

{% embed url="<https://www.youtube.com/watch?v=CMsjCb19_9s>" %}

Often we want to perform actions on all elements of arrays of arbitrary length. We can use loops to run code on each array element sequentially.

The trick to using loops with arrays is to link the `counter` loop concept with the `index` array concept. Typically, the counter represents the current index of the array, and the length of the array is the maximum counter value plus 1. The "plus 1" is because array indexes are 0-indexed, thus the maximum valid array index is the array length minus 1.

## Looping Over Arrays

To get the length of an array, we can use the `.length` method. This method exists on every array.

```javascript
var letters = ['a', 'b', 'c'];
letters.length; // This returns 3, the number of elements in letters
```

In the following example we use `letters.length` to determine the number of loop iterations. We use `index` to access each element in the array sequentially, 1 element per loop iteration.

```javascript
// Index starts at 0, representing the 0th index of the array
var index = 0;
// We will iterate over the letters array
var letters = ['a', 'b', 'c'];
// Run the loop while index is less than the length of the array
while (index < letters.length) {
  // letters[index] represents a different element for each loop iteration
  var currentLoopLetter = letters[index];
  // Log the current element in each iteration
  console.log(currentLoopLetter);
  // Increment the index at the end of each iteration
  index = index + 1;
}
```

## Address Book Example

Let's create a practical example of loops with arrays using an address book. Our address book stores unique names in an array, i.e. will not add a name if it is already in the book.

```javascript
// Initialise an empty names array
var names = [];
var main = function (input) {
  // Set a boolean value found to a default value of false
  var found = false;
  
  // Loop over the names array, and set found to true if the input name already
  // exists in the names array
  var index = 0;
  while (index < names.length) {
    var currentName = names[index];
    if (currentName == input) {
      found = true;
    }
    index = index + 1;
  }

  // If no duplicate name was found, add the input name to the names array 
  if (!found) {
    names.push(input);
  }

  // Return the full array of names
  var myOutputValue = 'All names: ' + names;
  return myOutputValue;
};
```

## Exercises

### Follow Along

Implement the above code.


# Additional Resources 6

For the curious and the hungry

## Arrays

1. [W3S: Arrays](https://www.w3schools.com/js/js_arrays.asp)
2. [W3S: Array Methods](https://www.w3schools.com/js/js_array_methods.asp)
3. [FreeCodeCamp: Array Exercises](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/store-multiple-values-in-one-variable-using-javascript-arrays)

## Loops

1. [MDN: Loops](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code)
2. [JavaScript.info: `while` and `for` loops](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code)
3. [FreeCodeCamp: Loop Exercises](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-while-loops)


# 7.1: Git

## Learning Objectives

By the end of this lesson, you should be able to:

1. Explain what *Version Control* is..
2. Briefly explain what Git is, and why it is used.
3. Be familiar with common git commands.
4. Initialise a Git repository and make commits.
5. Refer to the Git Cheat Sheet when needed.

## Introduction

{% hint style="info" %}
Before following along, make sure you have your git settings setup correctly as per [Required Software](/course-logistics/required-hardware-and-software/required-software-2#intro-to-git). Ask in your section community channel if you are unsure about any settings. Ensure that the default branch name for a new git repository is `main` and not `master`, by setting:

```
git config --global init.defaultBranch main
```

This will help us avoid problems when working with GitHub later. You can input this command more than once with no adverse effects, so you can always re-type it to be sure, or check all global settings:

```
git config -l
```

You can read more about why GitHub recently changed their default branch name from master to main [here](https://www.theserverside.com/feature/Why-GitHub-renamed-its-master-branch-to-main).
{% endhint %}

{% embed url="<https://youtu.be/GudllO59HJQ>" %}

## Version Control

Version control is a system that allows us to track changes over the lifetime of a file. A system like this isn't limited to code, and isn't limited to text files. It could be used for video files or other assets, or other text files such as contracts or articles.

The system of version control is a fundamental part of being a software engineer, and of developing a complex software project. In this course we'll use version control to keep track of our work, and submit our assignments using the web app GitHub.

## Git

Git is the most popular version control system for developers, and the version control system we'll be using. It was invented by the same person who invented Linux, to help coordinate large complex software projects between distributed teams of engineers.

In SWE Fundamentals we'll be learning Git so that we can keep track of different versions of our code. In [8.2 (GitHub Repo Browsing)](/8-github/8.4-github-repo-browsing) we'll cover how to browse and get back these older versions, but in this section we'll only cover some basic actions within Git and how to record the versions of our code in the first place.

Don't worry if some of the version control concepts are hard to understand now, we'll slowly be expanding our use and knowledge of Git as the course goes along. Git is not programming so it's simply a tangential tool to help as the code becomes harder to build and keep track of.

### Why Do We Need Git?

In order to do programming it's not strictly necessary to use Git or any version control. We want to use it mainly because, even though there is a lot of overhead for understanding the command line interface and learning the basic Git concepts, we want to ***eliminate the fear of breaking a given set of code***. As we'll soon see, the main task of programming is to incrementally build up code that will *inevitably* have errors. One of the main uses of version control (for all programmers, not only in SWE Fundamentals) is to make sure that introducing a new error is not catastrophic. When all new small changes are carefully saved in Git versions, we can be sure that whatever new code we try won't result in an unfixable error.

## Git Terminology

![Parts of a Git repository](/files/-MEaYyO_oSP_clp0WuAZ)

### Repository

A core concept in Git is the "Repository", or "Repo" for short. This is a folder that holds all the code for one project.

### Commits

A Git Repo consists of a time series of commits in the order that they were recorded in the Git system. A commit contains a set of changes to one or more files. These changes can be changes to contents of a file, but also include addition of a new file, deletion of a file, or renaming or moving a file.

### Staging

With Git, changes need to be staged before they can be committed. Staging is useful for when we may wish to make multiple commits out of the changes we have made locally. We can choose which changes go in which commit by staging the files we wish to add to each commit before running the commit command. For example, if I've changed files A and B for features A and B respectively, I could first stage only A and commit A, then stage only B and commit B. I would then have 2 independent commits for A and B that I could inspect or revert independently.

## Git Commands

In this course we'll be using the command line to manipulate Git. There are other ways to manipulate Git, including several GUI applications, but the command line is the most canonical and widely-used way to manipulate Git.

### init

```
git init
```

`git init` is the command to create a new Git repository. We will not be using this command in SWE Fundamentals because we download starter code with `git clone`.

{% hint style="danger" %}
Creating a repo inside a repo can cause problems. If we are in the command line and running `git status` doesn't throw an error, we are already inside a Git repo. Don't do `git init` or `git clone` in this directory.
{% endhint %}

### status

```
git status
```

`git status` is the command to see the current status of the repo. This is typically used to see which files are "staged for commit" in green, and which files are "not staged for commit", in red. To be staged means that if we were to run `git commit` at that moment, the changes to the staged files would be included in the commit.

![Example of git status output. script.js is "not staged for commit".](/files/-MEabtNCZkkH-TsIU0Ci)

### diff

`git diff` is the command that shows the changes made within a given file or directory.

```
git diff <path>
```

![](/files/-MEar9XhKeOFrNd6H-k9)

{% hint style="info" %}
Often our changes will be longer than the terminal window height, and `git diff` will open a special menu to navigate these changes. To exit this menu, use `q`, as suggested in [1.3: Command Line's Troubleshooting section](https://github.com/rocketacademy/basics-docs/blob/main/7-version-control/1-introduction/1.3-command-line.md#troubleshooting-the-command-line).
{% endhint %}

### add

`git add` is the command that ***stages*** files for commits. ***Staging*** is a label for a group of files, where all "***staged***" files will be included in the next commit. `git status` will show us which files are ***staged*** and not ***staged***. ***Staged*** files will appear in green, and files that have not been staged, in red. In Git, creating a commit happens in 2 steps.

1. At least one file is labeled as "staged" with the `add` command.
2. A commit is created that includes the staged files with the `commit` command

```
git add <path>
```

![](/files/-MEaqQMlJyya48gvt50h)

### commit

`git commit` creates the commit record in the repo. We must use the `-m` option to include a "commit message", a short sentence about what we changed. Commit messages typically include **what** was changed and **why** a change was made.

```
git commit -m "message that describes the changes"
```

{% hint style="warning" %}
Running `git commit` without `-m` might bring you into the `vi` editor. If you get stuck in `vi` type `Esc` and `:q!`, followed by `Enter` to get out.

`vi` looks like the following.

<img src="/files/-Mdvm6E5rNHKYjSNx1gp" alt="" data-size="original">
{% endhint %}

{% hint style="warning" %}
The first time you make a Git commit you may encounter an error asking you to run the following commands:

```
git config --global user.name "First Name Last Name"
git config --global user.email "example@example.com"
```

This is normal. Git is asking us to set our Git identity so that any commits we make are tied to our name and email. Once you run those commands, you should be able to make commits as expected.
{% endhint %}

### log

Finally, to see a list of the commits in this repo (including the one you just created) use `git log`

```
git log
```

{% hint style="info" %}
Eventually our list of commits will be longer than the terminal window height, and `git log` will open a special menu to navigate this list. To exit this menu, use `q`, as suggested in [1.3.: Command Line's Troubleshooting section](https://github.com/rocketacademy/basics-docs/blob/main/7-version-control/1-introduction/1.3-command-line.md#troubleshooting-the-command-line).
{% endhint %}

## Cheat Sheet

Create a Git repo

```
git init
```

Check repo status, e.g. which files are staged

```
git status
```

View changes in unstaged files

```
git diff
```

Mark file(s) as "staged" to prepare them for commit

```
git add <FILE_NAME>
```

Create a commit with currently-staged files

```
git commit -m "fixed spelling error"
```

View past commits

```
git log
```

{% hint style="warning" %}
Git version control is a deep topic. We are only covering a tiny portion of all the Git functionality in SWE Fundamentals to give a small look into the world of developer workflow and version control. This will be a tool that we hope will be valuable in your coding later in the course. Don't worry if you don't understand everything! We'll also see more about Git later in [module 8](/8-github/8.1-intro-to-github).
{% endhint %}

## **Exercises**

You may wish to refer to the [command line cheatsheet](/1-introduction/1.3-command-line#cheat-sheet) and [Git cheatsheet](#cheat-sheet), and use [window snapping](/course-logistics/required-hardware-and-software/recommended-set-up#window-snapping-software) to position 3 windows on your screen simultaneously: VSCode, the relevant cheatsheet, and these instructions.

### Create a Haiku

We will create poetry, save and edit it using the command line and Git.

1. Open the command line and create a folder for our poetry using `mkdir`.
2. `cd` into the folder, and initialise it as a git repo using `git init`
3. Create a text file in the command line using `touch haiku.txt` and open it in VSCode with the command `code haiku.txt`
4. Write a [haiku](https://en.wikipedia.org/wiki/Haiku) about trees in the text file and save the file. A haiku is a Japanese poem that follows the convention of 5 syllables, 7 syllables, and 5 syllables on each of 3 lines respectively.
   1. If writing poetry is difficult, feel free to make up something :) The content isn't particularly important for this exercise.
5. Stage and commit your new text file.
6. Edit our poem to reference leaves. Make a commit for our changes.
7. Add a 2nd poem about winter in another file. Commit this file to the repo.
8. Add a title to our poem about trees. Add the title above the text in the file, and change the filename to reflect the title. Note here that we can change more than one file, and only stage the trees file for committing. In this way we can say which files go into a given commit. Don't stage or commit the winter poem.
9. Use `git log` to see the change log of the current repository.

{% hint style="info" %}
**Hint:** When typing in the command line we can press the `tab` key and the command line will try to auto-complete the current command, file, or folder name. This can help reduce unnecessary typing and typos
{% endhint %}

### Committing and Tracking Changes to Project 1

Navigate to your *Scissors Paper Stone* directory, and initialize it as a git repo. Make your first commit with a meaningful, but brief message describing your current progress on the project. As you continue adding to the project, make meaningful commits at each checkpoint. Approach your Section Leader if you have any questions. When we learn how to use and navigate GitHub, we will be able to visualize our progress, and travel through time via these commits.


# Additional Resources 7

For the curious and the hungry

## Git

1. [Git and GitHub in Plain English](https://blog.red-badger.com/2016/11/29/gitgithub-in-plain-english)
2. [What is Version Control Systems?](https://www.youtube.com/watch?v=8oRjP8yj2Wo)
3. [Getting Started: About Version Control](https://git-scm.com/book/en/v2/Getting-Started-About-Version-Control)
4. [Learn Git Branching](https://learngitbranching.js.org) (game)
5. [W3S: Git Exercises](https://www.w3schools.com/git/git_exercises.asp)


# 8.1: Intro to GitHub

## Learning Objectives

At the end of this lesson, you should:

* Be *familiar* with GitHub
* Understand briefly how GitHub extends the capabilities of Git

## Introduction

{% embed url="<https://www.youtube.com/watch?v=dn7r4333c4g>" %}

GitHub is a web application that hosts Git repositories on the internet. It is a centralised set of repositories developers use to hold "official" copies of their code.

### Why Use GitHub?

In Fundamentals we'll be using GitHub as a place to download starter code, and, when we cover [8.2](/8-github/8.2-github-fork-and-clone) (GitHub Fork and Clone) we'll use it to submit projects and store our code and code versions online.

Don't worry for now if the structure of local and remote repositories seems confusing, we'll be covering these topics again more in-depth in [8.2](/8-github/8.2-github-fork-and-clone) and [8.3](/8-github/8.4-github-repo-browsing).

![A Git "remote" is a shared copy of a code repository, typically hosted on a platform like GitHub](/files/-MEcjfhOXLy3AxW0gjLG)


# 8.2: GitHub Fork and Clone

## Learning Objectives

At the end of this lesson, you should:

* Be able to use the GitHub Fork feature.
* Be able to use the `git clone` command.
* Be able to use the `git push` command.

## Introduction

We will learn more features of Git and GitHub to start and submit SWE Fundamentals projects. As a reminder, Git is the *version control system* and GitHub is the code-hosting website built on top of Git. GitHub extends the capabilities of Git by adding visual code browsing, social features, and collaboration features.

{% hint style="warning" %}
In the below video we demonstrate `git push origin master`, but for SWE Fundamentals `git push` will suffice. `origin` refers to the target Git remote, and `master` refers to the target branch. **Rocket Academy has updated our repos to use `main` as the default branch** name as per GitHub's latest convention, so if you wanted to specify the full command including remote and branch for SWE Fundamentals, you could use **`git push origin main`**.
{% endhint %}

{% embed url="<https://youtu.be/uMNcnLWTmZU>" %}

### GitHub Fork

"Fork" is the GitHub term for *copying* a repo from one GitHub account to another. We can fork a repo by clicking the Fork button on a given GitHub repo page. Forking allows us to make changes to a repo and save those changes to *our own* GitHub account's copy of the repo. Our account's repo is essentially ***independent*** from the original, forked repo.

![How to find the fork button on a repo page.](/files/Kafk9D5Py5lwNWSUd7xX)

"Fork" is a GitHub concept. Forking is not built-in to the Git version control system.

![A "fork" is when we copy a repo from another account to our own inside of GitHub.](/files/-MF68PHy5ncUHRCPcADs)

## Git Clone

We'll use a Git command to download or "clone" a copy of SWE Fundamentals starter code. `<REPO_DOWNLOAD_URL>` is the download URL of our repo, obtained by clicking the Download Code button on the repo's [GitHub page](https://github.com/rocketacademy/fundamentals-starter-code). `<LOCAL_REPO_FOLDER_NAME>` is the name of the destination folder that is created (containing the contents of the repo) when we run the Git command.

**Command Template**

```bash
git clone <REPO_DOWNLOAD_URL> <LOCAL_REPO_FOLDER_NAME>
```

**Sample Command**

```bash
git clone https://github.com/rocketacademy/fundamentals-starter-code.git fundamentalsash-starter-code-test
```

![Clone a repo onto your computer from GitHub](/files/-MEcm7TGou4rbzV6bgyV)

GitHub enables us to coordinate differences between local and "official" versions of the code, but we won't concern ourselves with that just yet.

### Git Push

We will learn 1 new Git command `push` to send local code commits from our computers to GitHub. `push` can also be used as a general command to move code between "remote" repos, but during SWE Fundamentals we will only be using `push` to push code to GitHub.

![The "git push" command can be used to send local code commits to GitHub.](/files/-MF69ZT24IiutUi8JnWT)

## Cheatsheet

Here is the workflow for SWE Fundamentals projects:

1. Go to the project repo page. Click the "Fork" button to copy the repo to our own GitHub account.
2. In the command line on our local computer, **clone the repo from our own Github account's copy of the repo.**
3. Once the repo is on our computer, make the changes we want, and follow the Git workflow and [cheatsheet ](/7-version-control/7.1-git#cheat-sheet)to commit those changes.
4. `git push` our changes to our repo. **Refresh** the repo page to see our commits in the repo.
5. Create a [pull request](/8-github/8.3-github-pull-request) in GitHub. This connects our work on the repo *in our account* to the original Rocket Academy repo. Fill in the survey and submit.

## Exercise

1. Fork a copy of the [Fundamentals *Beat That*! repo](https://github.com/rocketacademy/basics-beat-that) as setup for Project 2.
2. Clone the repo into a folder on your local machine.
3. Once you start working on your project, make frequent commits and use `git push` to update your GitHub repo.


# 8.3: GitHub Pull Request

## Learning Outcomes

By the end of this lesson, you should be able to:

* Make a GitHub Pull Request.

### GitHub Pull Request

{% embed url="<https://youtu.be/y32p-DDj1Zw>" %}

A GitHub "[**pull request**](https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/about-pull-requests)" (PR) is a request to pull changes from 1 repo on GitHub to another. PRs are most commonly used as a *code-review mechanism*, where developers submit PRs for review before merging the code in those PRs to their company's shared repo. We will use PRs in SWE Fundamentals to submit projects.

When we've pushed our changes to our repo, we'll click the "Pull requests" button to create a new pull request.

![How to find the pull request tab and new pull request button in GitHub.](/files/-MF676tddxq9_sLF_l73)


# 8.4: GitHub Repo Browsing

## Learning Objectives

By the end of this lesson, you should:

* Be familiar with navigating GitHub.
* Know how to view the commit history of a repo.
* Know how to navigate the Pull Requests tab in GitHub

## Introduction

{% embed url="<https://youtu.be/a-flBCpOmBU>" %}

One of the biggest benefits of Git is the ability to see contents of previous commits or versions. We can do this within the command line interface of Git, but it is easier on the GitHub website. Familiarise yourself with everything the GitHub website can display about your repo.

## Repo and Commit Navigation

![View a list of all commits.](/files/-MHuUvo5w8aEHGV78W-G)

![See the contents of each commit.](/files/-MHuU5K7op0Y53Camo0t)

![Commit contents include a "diff" for every changed file.](/files/-MHuU1D6-7r6gvNGVAAF)

## Pull Request Navigation

![View the full file, not just a "diff" of changes between old and new versions of the file.](/files/-MHuTyTDGgtCHop8e1KI)

![View a list of all pull requests on a repo.](/files/-MHuTvA68Ju0k28Jlxti)

![View details of a single pull request.](/files/-MHuTseOr_m30S4zYfq3)

![View a list of all commits within this pull request.](/files/-MHuTpLgyJmbXs1E-O1P)

{% hint style="info" %}
**What if I want to undo something from a previous commit?**

We can "roll back" our repos to a previous commit with the `git revert` command, but due to the small nature of our apps in Coding Fundamentals, it may be easier to "roll forward" by copying the code we want from a previous commit in GitHub, pasting that code into our local repo, and creating a new commit for these changes.
{% endhint %}

## Exercises

### Follow Along

Follow along with the video to navigate your own repo.


# 8.5: Deployment

## Learning Outcomes

By the end of this lesson, you should be able to:

* Deploy your project as a GitHub Page.

## Walkthrough

In order to make your repo code accessible to anyone on the internet you only need to follow a few steps on the GitHub repo page.

1\) Navigate to the settings page of the repo.

![](/files/-MGr_QzJuFxUN62w0g3A)

2\) Scroll down to the GitHub Pages section and click the dropdown

![](/files/-MGr_aZnWDlGBAcE6qW7)

3\) Select the **`main`** branch.

![](/files/uo2ff9XO2ZCRBgjWJdA0)

4\) Click the save button.

![](/files/-MGr_zYXIo4KWE0SLe6Y)

5\) The page will refresh and when you scroll back down to the GitHub pages section the URL of your repo will be displayed there.

![](/files/-MGraNyeu3gP8Zavfl38)

{% hint style="warning" %}
Note that if for any reason you changed around any of the file structure of the repo this may not work correctly right away. `index.html` needs to be at the root of the repository.
{% endhint %}

## **Exercise**

### **Deploy SWE Fundamentals Projects**

Go into the settings and deploy your *Beat That!* project.


# Additional Resources 8

For the curious and the hungry

## Git

1. [What is Version Control Systems?](https://www.youtube.com/watch?v=8oRjP8yj2Wo)
2. [Getting Started: About Version Control](https://git-scm.com/book/en/v2/Getting-Started-About-Version-Control)
3. [Learn Git Branching](https://learngitbranching.js.org) (game)
4. [W3S: Git Exercises](https://www.w3schools.com/git/git_exercises.asp)

## GitHub

1. [Git and GitHub in Plain English](https://blog.red-badger.com/2016/11/29/gitgithub-in-plain-english)
2. [GitHub for Noobs](https://www.youtube.com/watch?v=1h9_cB9mPT8\&t=13s) (video playlist)


# 9.1: JavaScript Objects

## Learning Objectives

By the end of this lesson, you should be able to:

* Explain what an Object is in JavaScript.
* Explain when and why to use an Object datatype.
* Explain the differences between Objects vs Arrays.
* Declare an Object using JavaScript syntax.
* Access, add, or replace attributes in an Object.

## Introduction

{% embed url="<https://www.youtube.com/watch?v=11z4g8BOxXg>" %}

In this module we will introduce a new data structure called the JavaScript **Object**. This data structure is called different names in different contexts. For example, JS Objects are known as "hash tables" in computer science, "dictionaries" in Python, and "HashMaps" in Java. The JS Object is \***not**\* the same "object" concept referred to in Object Oriented Programming.

We will use Objects to implement card games. It turns out that cards are easily represented by Objects and a clear demonstration of why Objects can be useful.

### How to Represent a Card Deck?

{% embed url="<https://www.youtube.com/watch?v=vSIm-Y9KANg>" %}

What would be the best way to represent a deck of cards in code? A deck of cards is a set of data (cards) that is of the same type (each card has the same attributes). This implies an array. We could create an array like the following.

```javascript
var cardDeck = ['nine of hearts', 'ten of hearts', 'jack of hearts'];
```

Is this a good representation of a card deck? Let's think abstractly about what attributes belong to a card deck.

#### Deck Order

A deck of cards is implicitly ordered. An array was a good choice to represent this.

#### Card Attributes

1. Each card has a rank. Our array of strings stores this rank in the sub-strings "nine", "ten", or "jack". Card ranks have order that we do not represent in our strings, e.g. `queen > jack`.
2. Each card has a suit. Our array of strings stores this suit in the sub-string "hearts".

How would we obtain rank and suit attributes of cards in our deck? In our above example, we could perform string manipulation to extract rank and suit values, but we would subsequently also have to write logic to compare rank strings to determine card order. Let's see if we can represent card attributes in a more convenient manner.

### Objects Store Compound Data

Objects are perfect for representing single units of data (e.g. cards) that themselves contains smaller units of data that are attributes of the larger unit. The attributes of an Object need not be the same data type- they can be any data type, and each attribute can have its own data type. The following example is an Object representation of a single playing card.

```javascript
// Objects are defined with curly-brace syntax and can be stored in variables.
var playingCard = {
  // Each attribute is defined with a key and a value.
  // The key is before the colon (:), and the value is after the colon.
  // Attributes are separated by a comma and newline.
  // Use a number to represent rank for easy comparison with other cards
  rank: 11,
  suit: 'heart',
  // Store an additional "name" attribute to correctly name face cards and aces.
  name: 'jack',
};
```

The example encodes 3 attributes of a playing card. `rank` is a number to facilitate comparison with other cards. `suit` is still a string but now easily accessible without string manipulation. `name` is used for display purposes, to quickly convert the `rank` number into a string. This is especially helpful for face cards whose names are not the English word of the `rank` number.

### How to Access Object Attributes

We can use the `.` operator to access Object attributes. In the following code snippet, we access each of the `playingCard` Object's attributes with the `.` operator. We can also access Object attributes using `[]`notation, but this will typically not be necessary.

```javascript
// Access the rank attribute
playingCard.rank;
// Access the suit attribute
playingCard.suit;
// Access the name attribute
playingCard.name;
```

### Objects with Arrays

We can combine objects and arrays to store more complex data types, such as a deck of cards. Each card is represented by an object, and the set of cards is represented by an array.

```javascript
var cardDeck = [
  {
    rank: 1,
    suit: 'heart',
    name: 'one',
  },
  {
    rank: 2,
    suit: 'heart',
    name: 'two',
  },
  // ...
];
```

### Objects, Arrays, and Loops

Given the above card deck representation, we can use a loop to access all cards in a deck.

```javascript
// Initialise index to 0 to start from the beginning of the array
var index = 0;
// Define loop condition to loop until index is the length of cardDeck
while (index < cardDeck.length) {
  // Access attributes of each card with dot notation.
  console.log(cardDeck[index].name);
  // Construct a string using attributes of each card object
  var cardTitle = cardDeck[index].name + ' of ' + cardDeck[index].suit;
  // Log the string
  console.log(cardTitle);
  // Increment the card index
  index = index + 1;
}
```

Inside the loop we can access a specific card's attributes using dot notation on that card's object in the array.

```javascript
// Get the name of the 1st card
cardDeck[0].name;
```

### Objects vs. Arrays

When should we use Objects versus Arrays? Here is a summary.

|                                                 | Objects                                                                                      | Array                                                                                                                                                                |
| ----------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Is the data ordered or unordered?               | Unordered                                                                                    | Ordered                                                                                                                                                              |
| What kind of data is stored inside?             | Attributes that represent different types of data, e.g. colours, suits, and ranks for cards. | Elements that are all the same type of data, both in terms of data type (e.g. boolean, number, string, Object, Array) and data meaning (e.g. all elements are cards) |
| What operations do you want to do on this data? | Access a single piece of the data: `card.rank` `card.suit`                                   | Do the same operation to every piece of data you have (in a loop).                                                                                                   |

### Card Shuffling

{% embed url="<https://www.youtube.com/watch?v=8DRwHSiyGe8>" %}

We can shuffle elements in an array by swapping random elements in the array repeatedly. We can apply this concept to shuffling cards, where each element in a card deck array is an object representing a playing card. The following code simulates card shuffling and will be useful for the card games we will implement.

```javascript
// Get a random index ranging from 0 (inclusive) to max (exclusive).
var getRandomIndex = function (max) {
  return Math.floor(Math.random() * max);
};

// Shuffle the elements in the cardDeck array
var shuffleCards = function (cardDeck) {
  // Loop over the card deck array once
  var currentIndex = 0;
  while (currentIndex < cardDeck.length) {
    // Select a random index in the deck
    var randomIndex = getRandomIndex(cardDeck.length);
    // Select the card that corresponds to randomIndex
    var randomCard = cardDeck[randomIndex];
    // Select the card that corresponds to currentIndex
    var currentCard = cardDeck[currentIndex];
    // Swap positions of randomCard and currentCard in the deck
    cardDeck[currentIndex] = randomCard;
    cardDeck[randomIndex] = currentCard;
    // Increment currentIndex
    currentIndex = currentIndex + 1;
  }
  // Return the shuffled deck
  return cardDeck;
};
```

### High Card

{% embed url="<https://www.youtube.com/watch?v=ZMDQwazN8I0>" %}

High Card is a card game where each player draws a random card, and the player with the highest card wins. Below is a sample implementation of High Card. We will soon be creating other card games, combining all we have learned so far in SWE Fundamentals.

In the following implementation, we use the JS array `pop` method to draw a random card from the deck. `pop` removes and returns the last array element (i.e. draws a card from the top of the deck). We can rely on `pop` to draw a random card because the deck is already shuffled.

After drawing cards, we can use the cards' `rank` attributes to compare which is higher.

```javascript
// Initialise the card deck representation as an array of objects
var deck = [
  // card1,
  // card2,
  // ...
];

// Shuffle the deck and save it in a new variable shuffledDeck
// to communicate that we have shuffled the deck.
var shuffledDeck = shuffleCards(deck);

var main = function (input) {
  // Draw 2 cards from the top of the deck
  var computerCard = shuffledDeck.pop();
  var playerCard = shuffledDeck.pop();

  // Construct an output string to communicate which cards were drawn
  var myOutputValue =
    'Computer had ' +
    computerCard.name +
    ' of ' +
    computerCard.suit +
    '. Player had ' +
    playerCard.name +
    ' of ' +
    playerCard.suit +
    '. ';

  // Compare computer and player cards by rank attribute
  // If computer card rank is greater than player card rank, computer wins
  if (computerCard.rank > playerCard.rank) {
    // Add conditional-dependent text to the output string
    myOutputValue = myOutputValue + 'Computer wins.';
    // Else if computer card rank is less than player card rank, player wins
  } else if (computerCard.rank < playerCard.rank) {
    myOutputValue = myOutputValue + 'Player wins!';
    // Otherwise (i.e. ranks are equal), it's a tie
  } else {
    myOutputValue = myOutputValue + "It's a tie.";
  }

  // Return the fully-constructed output string
  return myOutputValue;
};
```

## Hard-Coded Card Deck

1 acceptable way to initialise a standard 52-card deck in our code is to hard-code it, i.e. manually specify each card and each of its attributes in code. Use this hard-coded deck for this module's exercises below.

```javascript
var deck = [
  {
    name: 'ace',
    suit: 'hearts',
    rank: 1,
  },
  {
    name: '2',
    suit: 'hearts',
    rank: 2,
  },
  {
    name: '3',
    suit: 'hearts',
    rank: 3,
  },
  {
    name: '4',
    suit: 'hearts',
    rank: 4,
  },
  {
    name: '5',
    suit: 'hearts',
    rank: 5,
  },
  {
    name: '6',
    suit: 'hearts',
    rank: 6,
  },
  {
    name: '7',
    suit: 'hearts',
    rank: 7,
  },
  {
    name: '8',
    suit: 'hearts',
    rank: 8,
  },
  {
    name: '9',
    suit: 'hearts',
    rank: 9,
  },
  {
    name: '10',
    suit: 'hearts',
    rank: 10,
  },
  {
    name: 'jack',
    suit: 'hearts',
    rank: 11,
  },
  {
    name: 'queen',
    suit: 'hearts',
    rank: 12,
  },
  {
    name: 'king',
    suit: 'hearts',
    rank: 13,
  },
  {
    name: 'ace',
    suit: 'diamonds',
    rank: 1,
  },
  {
    name: '2',
    suit: 'diamonds',
    rank: 2,
  },
  {
    name: '3',
    suit: 'diamonds',
    rank: 3,
  },
  {
    name: '4',
    suit: 'diamonds',
    rank: 4,
  },
  {
    name: '5',
    suit: 'diamonds',
    rank: 5,
  },
  {
    name: '6',
    suit: 'diamonds',
    rank: 6,
  },
  {
    name: '7',
    suit: 'diamonds',
    rank: 7,
  },
  {
    name: '8',
    suit: 'diamonds',
    rank: 8,
  },
  {
    name: '9',
    suit: 'diamonds',
    rank: 9,
  },
  {
    name: '10',
    suit: 'diamonds',
    rank: 10,
  },
  {
    name: 'jack',
    suit: 'diamonds',
    rank: 11,
  },
  {
    name: 'queen',
    suit: 'diamonds',
    rank: 12,
  },
  {
    name: 'king',
    suit: 'diamonds',
    rank: 13,
  },
  {
    name: 'ace',
    suit: 'clubs',
    rank: 1,
  },
  {
    name: '2',
    suit: 'clubs',
    rank: 2,
  },
  {
    name: '3',
    suit: 'clubs',
    rank: 3,
  },
  {
    name: '4',
    suit: 'clubs',
    rank: 4,
  },
  {
    name: '5',
    suit: 'clubs',
    rank: 5,
  },
  {
    name: '6',
    suit: 'clubs',
    rank: 6,
  },
  {
    name: '7',
    suit: 'clubs',
    rank: 7,
  },
  {
    name: '8',
    suit: 'clubs',
    rank: 8,
  },
  {
    name: '9',
    suit: 'clubs',
    rank: 9,
  },
  {
    name: '10',
    suit: 'clubs',
    rank: 10,
  },
  {
    name: 'jack',
    suit: 'clubs',
    rank: 11,
  },
  {
    name: 'queen',
    suit: 'clubs',
    rank: 12,
  },
  {
    name: 'king',
    suit: 'clubs',
    rank: 13,
  },
  {
    name: 'ace',
    suit: 'spades',
    rank: 1,
  },
  {
    name: '2',
    suit: 'spades',
    rank: 2,
  },
  {
    name: '3',
    suit: 'spades',
    rank: 3,
  },
  {
    name: '4',
    suit: 'spades',
    rank: 4,
  },
  {
    name: '5',
    suit: 'spades',
    rank: 5,
  },
  {
    name: '6',
    suit: 'spades',
    rank: 6,
  },
  {
    name: '7',
    suit: 'spades',
    rank: 7,
  },
  {
    name: '8',
    suit: 'spades',
    rank: 8,
  },
  {
    name: '9',
    suit: 'spades',
    rank: 9,
  },
  {
    name: '10',
    suit: 'spades',
    rank: 10,
  },
  {
    name: 'jack',
    suit: 'spades',
    rank: 11,
  },
  {
    name: 'queen',
    suit: 'spades',
    rank: 12,
  },
  {
    name: 'king',
    suit: 'spades',
    rank: 13,
  },
];
```

## Exercises

### Follow Along

Implement the High Card code above to get a working High Card game.

### Highest of 2 Cards

Change the High Card program so that the player and computer each draw 2 cards instead of 1. The player with the highest of any of the cards wins.

## Reference

### Object Dereferencing: `myObj.name` vs `myObj[name]` vs `myObj['name']`

`myObj.name` and `myObj['name']` are equivalent.

`myObj[name]` returns the value that corresponds to the key with the value stored inside the variable `name`. For example, if we declare `var name = 'Luke';`, then `myObj[name]` is equal to `myObj.Luke`.

We cannot use `.` notation for numbers. For example, for an object key with value `'1'`, we cannot do `myObj.1`. We must do `myObj[1]` or `myObj['1']`, where JS auto-converts `1` in the former example to `'1'` since object keys can only be strings.


# 9.2: Card Deck Generation with Loops

## Learning Objectives

By the end of this lesson, you should be able to:

* Create a representation of a standard deck of cards in JavaScript, where each card is an Object, and the deck is an Array of Objects, using a loop.

## Introduction

{% embed url="<https://www.youtube.com/watch?v=FG8QVeq5y-k>" %}

At the end of [Module 9.1: JavaScript Objects](/9-javascript-objects/9.1-javascript-objects#hard-coded-card-deck) we shared a hard-coded card deck. This would work for our applications, but we may wish to use loops to generate this deck to be more concise and so we can more easily modify the deck if we need to. Creating the card deck with loops is also a useful exercise in identifying patterns and automating them with loops.

## Card Deck Generation Code

We define a `makeDeck` function that returns a generated standard 52-card deck. Read inline comments to understand the mechanics of this function.

```javascript
var makeDeck = function () {
  // Initialise an empty deck array
  var cardDeck = [];
  // Initialise an array of the 4 suits in our deck. We will loop over this array.
  var suits = ['hearts', 'diamonds', 'clubs', 'spades'];

  // Loop over the suits array
  var suitIndex = 0;
  while (suitIndex < suits.length) {
    // Store the current suit in a variable
    var currentSuit = suits[suitIndex];

    // Loop from 1 to 13 to create all cards for a given suit
    // Notice rankCounter starts at 1 and not 0, and ends at 13 and not 12.
    // This is an example of a loop without an array.
    var rankCounter = 1;
    while (rankCounter <= 13) {
      // By default, the card name is the same as rankCounter
      var cardName = rankCounter;

      // If rank is 1, 11, 12, or 13, set cardName to the ace or face card's name
      if (cardName == 1) {
        cardName = 'ace';
      } else if (cardName == 11) {
        cardName = 'jack';
      } else if (cardName == 12) {
        cardName = 'queen';
      } else if (cardName == 13) {
        cardName = 'king';
      }

      // Create a new card with the current name, suit, and rank
      var card = {
        name: cardName,
        suit: currentSuit,
        rank: rankCounter,
      };

      // Add the new card to the deck
      cardDeck.push(card);

      // Increment rankCounter to iterate over the next rank
      rankCounter += 1;
    }

    // Increment the suit index to iterate over the next suit
    suitIndex += 1;
  }

  // Return the completed card deck
  return cardDeck;
};
```

## Exercises

### Follow Along

Implement a card deck generation function from scratch. What might you do differently?


# 10.1 HTML

## Learning Objectives

By the end of this lesson, you should be able to:

* [ ] Define HTML
* [ ] Understand Basic HTML Syntax
* [ ] Use Basic HTML Syntax

## Introduction

We've completed the basics of how to code with JavaScript. Our hope is that you have some idea of how a program goes from conception to working code.

This module is only an introduction to HTML and CSS. HTML and CSS are the building blocks of everything you *see* on the *web*. HTML and CSS are **not** programming languages, as they do not involve *logic.* HTML is the raw data that makes up a webpage: tables, lists, input and output boxes. CSS is adds style to the raw data. However, we may want to apply the programming logic we have learnt to manipulate and change what is displayed on the browser - we will see how to do that in Module 6.

{% hint style="info" %}
When we learnt JavaScript, we first learnt the programming concepts before we learnt the specific syntax. This will be the same for HTML and CSS. We will not be exploring all HTML elements or all CSS styles and syntax, that would be like trying to learn a new human language by reading the dictionary and memorising every word. Try not to worry about learning and knowing all possible HTML attributes or all style properties. Instead, try to approach it with creative discovery: \_"How can I achieve this effect or style?" .\_Try to achieve something new, and read new code. Embrace creative discovery!
{% endhint %}

### What is HTML

HTML stands for Hyper Text Markup Language. In the same way you can [use certain tags](https://faq.whatsapp.com/general/chats/how-to-format-your-messages/?lang=fi) to make words **bold**, *italic*, or ~~strikethrough~~ in a text messaging app like WhatsApp, HTML defines tags that mark-up plaintext files to be formatted differently when opened by a browser application.

All browsers have an HTML engine built in that can read and interpret the syntax in an HTML file.

Tags tell the browser what type of elements are on the page and also how those elements relate to each other. Just like an editor would mark up content of an article, a programmer can mark up a web page by using tags and attributes.

The first thing to learn is the proper syntax of a basic HTML page. HTML uses tags wrapped around content to control the flow and look.

For example, a paragraph tag is used to surround the text of the paragraph and let the browser know that it is a paragraph. The browser then applies its default styling to the paragraph. The paragraph tag looks like this:

![](https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FXGhIVzyDelxQf93vGnXP%2Fuploads%2FHPkYmQ8RdpUzRZvtAAQA%2Fhtml%20elements.png?alt=media\&token=c0bc25bb-b315-4e7a-b7e9-2d1ee9c04114)

The \<p> is called the opening tag and the \</p> is called the closing tag. Both must be included to tell the browser where the paragraph begins and ends. What is written between the tags is displayed on the browser page, not the tags. Most tags have an opening and closing tag with the content in between.

Tags are generally nested inside each other to maintain structure and flow of content.

### HTML Elements

These are some common HTML elements, and their tags:

|                             HTML Tag                             |                                    Element                                   |
| :--------------------------------------------------------------: | :--------------------------------------------------------------------------: |
|       [\<div>](https://www.w3schools.com/tags/tag_div.asp)       |         A div, or division, is a generic container for HTML elements.        |
|         [\<p>](https://www.w3schools.com/tags/tag_p.asp)         | A paragraph. A new line is automatically added before and after a paragraph. |
| [\<b>, \<i>](https://www.w3schools.com/html/html_formatting.asp) | Bold, italics. Usually used within another HTML element, like \<p> or \<div> |
|    [\<h1> to \<h6>](https://www.w3schools.com/tags/tag_hn.asp)   |                      Used to defined headers on a page.                      |
|    [\<button>](https://www.w3schools.com/tags/tag_button.asp)    |                                   Buttons!                                   |
|     [\<input>](https://www.w3schools.com/tags/tag_input.asp)     |                   An input field where user can enter data.                  |
|         [\<a>](https://www.w3schools.com/tags/tag_a.asp)         |                 Anchor, used to link other pages or website.                 |

You can explore more HTML elements and tags [**here**](https://www.w3schools.com/TAgs/default.asp).

### HTML Element Attributes

HTML elements have \_attributes; a\_n attribute is used to define the characteristics of the element and is placed inside the element's opening tag. All attributes are made up of two parts − a **name** and a **value.**

#### IDs

An ID is a unique identifier for an HTML element. Only one ID can be applied to an element, though if you break this rule you won't get any errors, maybe just some unintended behaviours. Having a unique ID allows for a user to programmatically select and manipulate the associated element\*\*,\*\* which we will learn how to do later.

```markup
<p id="player-card-one">ace of spades</p>
```

#### Style

The `style` attribute allows us to define how the element appears on the screen. For example, if we wanted to change the font color of our paragraph element, we might do so using the `style` attribute like this:

```html
<p style=“colour: red;”> This text would be red </p>
```

In this case, the name of the attribute is `style` and the value is `"color: red"`, which can be confusing. In earlier versions of HTML, there was a `colour` attribute, and a different attribute for background-colour, and so on, which were all eventually subsumed under the `style` attribute. This requires the value of the style attribute to specify what style *property* is being defined. The style attribute also allows for the defining of other properties, such as changing the font-size or adding a border to an element. We will learn more about styling next.

### Exercise

1. In any of your HTML files, add a new HTML element.
2. Edit the element's background colour using the style attribute.


# 10.2: CSS

This page will give an introduction to HTML, CSS and how to reference HTML and CSS using JS so that a SWE can change the styling of the page.

## Learning Objectives

By the end of this lesson, you should be able to:

* [ ] Define CSS.
* [ ] Understand and use CSS Syntax
* [ ] Add styles to HTML with CSS.
* [ ] Understand what the cascade does.

### Intro To CSS

Built on top of HTML to add more visual control and complexity, CSS specifies styles on an HTML element or set of elements. The CSS code specifies visual properties unrelated to the written content on an HTML page. In practice there are 2 uses for CSS: element **styling** and **layout**.

#### Element Styling

CSS helps us change visual properties of HTML elements, such as fonts, background images, or rounded corners on buttons. Together with JS DOM manipulation, which we will learn in Module 6, we can use CSS to implement visual logic within an application, such as hiding or showing cards and flipping elements 90 degrees.

#### Layout

CSS can help us divide our UI into visual sections. This is one of the most tricky aspects of CSS, because CSS was not *originally* intended for layout design. CSS content in Rocket's Bootcamp will focus on implementing UI layouts.

## CSS Syntax

CSS is a declarative language. It doesn't tell the browser what to do but rather describes the rules that the browser then uses to render the page. CSS became popular because it was predictable and forgiving in its syntax. It was also easy to learn.

The concept of cascading styles is unique to CSS. To cascade means that styles can inherit and overwrite styles through its hierarchy called *specificity*.

CSS styling can be applied in three ways:

1. In-line styling.
2. Internal styling.
3. External styling.

For Coding Fundamentals, we will focus on just the first 2.

### In-line Styling

We have already seen in-line styling: it \*\*\*\* is written inside the HTML opening tag as an property-value pair. This is the simplest and most direct way of defining the style of a HTML element:

```html
<p style="“color:" red;”>This text would be red</p>
```

If more than one style declaration is applied:

```html
<p style="“color:" red; font-weight: bold;”>This text is red and bold</p>
```

However, applying, tracking, and managing styles of individual HTML elements in a complex, large HTML file can quickly get messy. Perhaps we wanted to apply a certain style to all the paragraph elements on a page, and define it once. It would make it much easier to manage, and ensure that style changes applied to all the necessary elements, without having to proofread each line of the HTML file.

### **Internal Styling**

**Internal styling** allows us to define the style for elements, or groups of elements centrally. These rules are defined within the HTML document, hence internal styling.

#### Sample Syntax

```css
selector {
  property: value;
  property: value;
}
```

As a declarative language, CSS uses selectors and declarations to apply styling rules to HTML pages. The syntax for CSS starts with a selector: the HTML element(s) we want to define style rules for. Then a declaration code block is created using open and closing curly braces. Inside the declaration code block are the style rules, in a similar syntax as in-line styling. You can have as many rules as needed. It is conventional to put each rule on its own line in code.

All CSS rules are placed inside the `<head>` tag of the page and is wrapped inside the `<style>` tag. In this example, the selector of p is chosen to style all the paragraph tags on the page.

```html
<html>
  <head>
    <title>Page Title</title>
    <style>
      p {
        color: white;
      }
    </style>
  </head>
  <body>
    <p>This text is white</p>
    <p>This text is also white!</p>
  </body>
</html>
```

### **External Styling**

**External styling** is when the styles are defined in a *separate file* and is referenced by index.html. This allows for better neatness and organisation, and for a styles to be centrally defined in a single *stylesheet* and applied across various HTML files, if necessary.

When defining styles in a `.css` file, it is not necessary to have opening and closing `<style>` tags. Rather, the entire file is **linked** into the `.html` file using a link tag, in the `<head>` of the document:

```html
<html>
  <head>
    ...
    <link rel="stylesheet" href="styles.css" />
    ...
    <html></html>
  </head>
</html>
```

`rel="stylesheet"` specifies the relationship of the file that we are linking, in this case the linked file defines the styles of the current HTML file, and it is known as the stylesheet. `href` stands for hyperlink reference, which defines the location of the file to be linked. If `styles.css` is in the same folder as the HTML file, we can simply provide the name of the file as the location.

## CSS Selectors: Classes and IDs

### Classes

Previously, we used HTML elements as selectors when defining CSS rules, either internally or externally. This makes things neater and easier to manage, but does not provide a lot of flexibility. Perhaps we want to apply a certain styling to a group of elements in our web page, but not all `<p>` elements. This can be achieved by using CSS classes, and assigning the relevant HTML element that class as an attribute.

A class in a CSS file comprises several characteristics that can be applied to any HTML element to define its visual identity. More than one class can be applied to an element and more than one element can be assigned a class. When defining a set of rules for a class, the selector is prefixed with a period, followed by the user-defined class name, as so:

```css
.card {
  background-color: pink;
}

.face-up {
  font-size: 20px;
}
.face-down {
  font-size: 0px;
}

.page-link {
  font: 'comic-sans';
}
```

```markup
// This is the HTML File

<p class="card face-down">ace of spades</p>
<p class="card face-up">ace of clubs</p>
```

### IDs

We can also define CSS rules for IDs. In this case, the prefix is #. As IDs should be unique, these CSS rules should only be applying to a single HTML element:

```css
#player-card-one {
  border: 3px solid red;
}

#save-button {
  color: green;
}
```

When defining HTML elements in `index.html`, we can initially assign them an ID or a class. IDs are unique, and should not be applied to multiple elements (just like your ID number), but multiple HTML elements can share classes, and HTML elements can belong to multiple classes. Not all HTML elements need to have an ID or a class.

## Cascade

Why *Cascading* Style Sheets? With so many different ways to define CSS rules, it is not difficult to imagine a situation where there are conflicting rules applying to a single HTML element. The cascade is what determines which rules actually get applied to our HTML. There are 3 main factors in determining the cascade:

1. Specificity,
2. Inheritance, and
3. Rule order.

For Coding Fundamentals, we will only focus on 3. Rule Order. You are free to read up on the rest. Rule order simply means that all the rules are applied sequentially, and in order. So if there 2 or more rules that governed the colour of a `<p>` element, the rule that is applied last will be the one that is preferred.

```javascript
<html>
    <head>
    ...
    <link rel="stylesheet" href="styles.css">
      <title> Page Title </title>
         <style>
            p{
               color: white;
            }
         </style>
   </head>
   <body>
	<p> This text is white </p>
	<p style="color: red;"> This text is RED! </p>
	<p> This text is back to white :) </p>
   </body>
<html>
```

## Common CSS properties

Now that you are familiar with the general syntax, here are some common properties you can begin experimenting with:

|                                Property                               |                       Description                       |
| :-------------------------------------------------------------------: | :-----------------------------------------------------: |
|      [color](https://www.w3schools.com/cssref/pr_text_color.asp)      |                 Sets the color of a text                |
|       [font](https://www.w3schools.com/cssref/pr_font_font.asp)       |     Sets all the font properties in one declaration     |
|        [border](https://www.w3schools.com/cssref/pr_border.asp)       |        Sets border properties in one declaration        |
| [background](https://www.w3schools.com/cssref/css3_pr_background.asp) | Set different background properties in one declaration. |

[Here is a list](http://web.simmons.edu/~grabiner/comm244/weekthree/css-basic-properties.html) of more, but not all, properties.

## SWE Fundamentals Starter Code

Take a look at `index.html` from the `fundamentals-starter-code`.

Look for the code from `<body>` onwards, and notice that some HTML elements have IDs and Classes associated with them.

```html
<h1 id="header">🚀 SWE Fundamentals 🚀</h1>

<!-- 
  The <div> tag defines a division or a section in an HTML document, 
  and is commonly use as a "container" for nested HTML elements. 
-->

<div class="container">
  <!-- The <p> tag defines a paragraph element. -->
  <p>Input:</p>

  <!-- 
    The self-closing <input /> tag represents a field for a user 
    to enter input. 
  -->

  <input id="input-field" />

  <!-- 
    The self-closing <br /> tag represents a line break - 
    a line's worth of spacing before displaying the next element. 
  -->

  <br />

  <!-- The <button> tag represents.. you guessed it! a button. -->

  <button id="submit-button">Submit</button>

  <p>Output:</p>

  <div class="output-div" id="output-div"></div>
</div>
```

The code within `<script>` tags reference some of these HTML elements, and define the logic that has been associating the Submit button and input/output fields to the main function. We will soon take a closer look at the syntax and concepts that make this work.

## Exercise

1. <mark style="color:red;background-color:yellow;">Be creative!</mark> <mark style="color:blue;">Explore!</mark> <mark style="color:blue;background-color:red;">Express yourself!</mark>


# 10.3: The Document Object Model

## Learning Objectives

By the end of this lesson, you should be able to:

* [ ] Briefly explain the Document Object Model (DOM).
* [ ] Reference HTML elements using classes and IDs
* [ ] Perform basic DOM manipulation in the browser console.

## Overview

Now we'll describe more about the browser environment we've been working with. This section is meant as a crash course on the rest of the browser system.

Here we can distinguish between **domain knowledge** - technical knowledge of a specific system, and **general programming knowledge**, which we've been focusing on during this course.

## Introduction

In [10.4: DOM Manipulation](/10-advanced/10.4-dom-manipulation), we will learn how to make our web applications more interactive by using JavaScript *logic* to change the previously-static elements that are rendered by the browser. We can effectively write programs that change what the user sees. We can tell the browser *"change the background color of this element when the submit button is clicked"* or *"disable this button if the user runs out of money"* or, if you are feeling nefarious, *"make this pop-up appear"*.

In order to do that, we must first be able to *reference* HTML elements that have already been rendered and link them to JavaScript variables, so that we can manipulate them the same way we manipulated data previously.

{% hint style="info" %}
Similar to how we started with entering commands into the console in [2.1 Operations](/2-basic-data-manipulation/2-operators-and-expressions), we will first explore and experiment with the DOM in the browser console. Visit your [deployed site](https://rocketacademy.github.io/basics-starter-code-2.0/) and follow along in the console.
{% endhint %}

{% embed url="<https://youtu.be/AP8YcJ9MR64>" %}

## DOM - Document Object Model

By now you should be familiar that while the browser primarily reads `index.html` , the entire web page that is displayed is built from multiple files together, such as `script.js` and `styles.css`. Even within `index.html`, there is the `<head>` and `<body>` elements, each of which contain child elements. Data from various sources together define the information and structure of the \_document t\_hat is processed and displayed by the browser.

![](https://www.freecodecamp.org/news/content/images/2021/01/images.png)

The Document Object Model, or DOM, is a ***representation*** of the contents of a webpage. Specifically, it's a tree-like representation of nodes and objects. By representing the entire document in an object-oriented way, we can use JavaScript to interact with and manipulate the displayed page in a dynamic way.

When we want our JavaScript to take in any inputs from the user or display any outputs on the browser, we have to use some part of the DOM functionality.

When the document is processed by the browser, a set of objects are created that represents the document, along with pre-defined *methods* and *functions* that we can use.

We've already seen one: `console.log()`. To be specific, `console` is an *object* of the DOM created by the browser, which has a pre-defined `.log()` *method.* Other `console` methods include \*\* `.clear()` \*\* or `.table()`*.*

Besides `console,` the other major objects that represent the DOM are `window` and `document`. We will next explore the `document` object and the `document.querySelector()` method.

{% hint style="info" %}
Open the console and type in the variable names `window` and `document` to see the values in the console. Click the triangles to the left of the output to see inside them. What is there?
{% endhint %}

## Accessing Elements in the DOM

{% embed url="<https://youtu.be/eLYFvfY1lKU>" %}

Not every node in the DOM "tree" is pre-defined as an object. You can use JavaScript object notation to access nested *nodes* in the document object: try `document.body` or `document.head`, or more generally: `document.children`. We can then use nested object notation to access child elements, so `document.body.children[0]` will access the first nested element in the `<body>`. This clearly isn't intuitive, what if we were looking for a specific element?

`document.querySelector()` allows us to do just that. It takes in, as input, a search query and returns the first element in the DOM that matches. If we wanted to access a paragraph element, for example, we could use `document.querySelector("p");`

If we wanted to access a *specific* paragraph, we can do so by referencing it's id or class by using a . or # prefix, respectively.

`document.querySelector("#submit-button")` will return the element that has the id "submit-button".

`document.querySelector(".card")` will return the first element that has the "card" class.

We can store the returned element in it's own variable, which will then allow us to access element properties or use other DOM methods on the element itself. Putting it all together:

```javascript
var button = document.querySelector('#submit-button');
button.innerText;
button.innerText = 'Click Me!';
```

Can you guess what `.innerText` is or does? What happens when you execute the code above in the console?

### Adding Elements to the DOM

{% embed url="<https://youtu.be/9E2wbG8Y6OY>" %}

We have already seen how to use `document.querySelector()` to access elements that are already on the page. What if we wanted to create a new element and add it to the document, without having to edit `index.html`?

#### Creating an Output

We can use the DOM to create elements and put them on the page.

```javascript
var coolParagraph = document.createElement('p');
coolParagraph.innerText = 'hey, cool!!!1!';
```

After we've created this element we need to tell the DOM to put it into the page.

```javascript
document.body.appendChild(coolParagraph);
```

## Exercise

1. Visit your deployed site and open the console.
2. Change the background colour of the `<div>` with class `"container"` using the DOM.
   1. Hint: you may want to access the `style` attribute of the `<div>` element.
3. Create and add a new HTML element to the page using the console.


# 10.4: DOM Manipulation

## Learning Objectives:

By the end of this lesson, you should be able to:

* [ ] Create, select and manipulate HTML elements using DOM-related methods.
* [ ] Write JavaScript logic that manipulates the DOM based on user input.

## Introduction

We have seen how we can manipulate the DOM via JavaScript in the console. Now let's take a look at how we can pre-program DOM manipulation to happen based on user input.

Conceptually, we are still just defining **inputs** and **outputs.** Now inputs include how the user interacts with the browser, which can include mouseovers, scrolls, drag and drops, clicks or double clicks, and output is manipulation of the Document that the user is interacting with.

## Inputs and Outputs

#### Defining an Input

{% embed url="<https://www.youtube.com/watch?v=6fEp-k32Tv8>" %}

An input to our JavaScript program is called an **event**. Similar to how we can define functions as blocks of code that will only run when the function is called, we can write code that will only run when the user interacts with the browser via an **event**. We do this with the provided `.addEventListener(`) method. The method takes in 2 inputs:

1. The [event type](https://developer.mozilla.org/en-US/docs/Web/Events)
2. The code block to be executed when the event is triggered, **defined as a function**.

Some useful events include:

* click
* dblclick
* keypress
* keydown
* keyup

You can find a more complete list with explanations of each event on [this page](https://www.w3schools.com/jsref/dom_obj_event.asp).

Let's go back to basics, and print out "Hello, world!" in the console whenever a button is clicked. The syntax for that might look something like this:

```javascript
var newButton = document.createElement('button');
newButton.innerText = 'Hello';
newButton.addEventListener('click', function () {
  console.log('hello, world!');
});
document.body.appendChild(newButton);
```

This means we can program the browser in such a way that when the user makes an action, the browser calls our function - and this is exactly how our `main` function works. Except that we aren't just limited to clicking on the submit button or getting the value the user typed into an input field/textbox.

The function for an event is referred to as a ***callback*** function. In the case of an event listener, the callback function takes the triggered event as an input parameter and does whatever actions it was declared to do due to this trigger. Now we can look at how this was defined for you in index.html of the starter code:

```javascript
<script>
      // Declare and define a variable that represents the Submit Button

      var button = document.querySelector("#submit-button");

      // When the submit button is clicked, access the text entered
      // by the user in the input field

      // And pass it as an input parameter to the main function as
      // defined in script.js

      button.addEventListener("click", function () {

        // Set result to input value
        var input = document.querySelector("#input-field");

        // Store the output of main() in a new variable
        var result = main(input.value);

        // Display result in output element
        var output = document.querySelector("#output-div");

        output.innerHTML = result;

        // Reset input value
        input.value = "";
      });

  </script>
```

## Advanced Applications in the Browser

{% embed url="<https://www.youtube.com/watch?v=mT-oeRViW9M>" %}

The pattern of:

1. Being able to create any representation of data on the screen
2. Have complete control over what actions the user can take at any time

means that your app should have complete control over every element on the screen.

Modern development for applications that run in the browser ( the browser is the front-end ) are libraries and frameworks that allow programmers to manage all of these elements and inputs.

Some popular libraries include [ReactJS](https://reactjs.org), [Angular](https://angular.io), and [Vue](https://vuejs.org). These are well out of the scope of SWE Fundamentals; React is one of the later modules in Rocket's Bootcamp.

## More Examples

Read through the comments to see what's actually happening.

```markup
<p>
    <input id="starter-ex"/>
</p>
<button id="starter-button">submit me</button>
```

```javascript
// make a variable out of the input and button
var input = document.querySelector('#starter-ex');
var button = document.querySelector('#starter-button');

// call this function
var myButtonClicked = function () {
  // get the current value that's been typed into the input
  var typedValue = input.value;

  // create a new h2
  var newHtwo = document.createElement('h2');

  // set the text inside this new element
  newHtwo.innerText = typedValue;

  // make the h2 appear on screen
  document.body.appendChild(newHtwo);

  // empty out the HTML input
  input.value = '';
};

// say which function to call *when* the user clicks the button
button.addEventListener('click', myButtonClicked);
```

## Exercises

### Follow Along

1. Implement the above code.
2. Using fundamentals-starter-code, write logic that grabs and references HTML elements, and change the background color of the `container` element every time the submit button is clicked.


# 10.5: Advanced Debugging with Sources Tab

![debugging meme](/files/-MkGzxyFX_z8nneOnM6I)

## Introduction

{% embed url="<https://youtu.be/si4JPK6zZ7c>" %}

As your code becomes more complex `console.log`s may not be sufficient to understand what your code is doing or where your errors are coming from.

As always, one of the fundamental goals in the process of building a program is to be able understand all its states and values at each step. You had some intuition or intention about what those states and values were when you wrote the program, but either it's hard to know exactly what they are at each point, or they diverge from what you thought they were. `console.log` allows you to examine the forensics of what the values were when the program ran.

The next level of debugging techniques and tools is the ability to be able to look at the values in your code ***\*as it is running\****. To be able to press the pause button in the middle of the program and look around at everything and then click to play the program forward again.

### Sources Tab

{% embed url="<https://youtu.be/9SW2ysq2Gnc>" %}

The sources tab is where the debugging tools live. This tab has many features to it but we will just be covering the bare minimum of it's functionality.

You can refer to the official chrome dev tools guide here if you wish to dive further into the subject: <https://developers.google.com/web/tools/chrome-devtools/javascript>

#### Setting a breakpoint

Open the script.js file by clicking in it in the file browser column. Set a breakpoint by clicking in the code file line number column. A blue arrow will appear. Note that you can't edit any code in this view.

![](/files/-MGNh1lPAYThmfQECowm)

#### Looking around with the console

Click the three dots in the upper right hand side to get the dropdown menu. Click on "Show console drawer".

![](/files/-MGNh5c36p59NFttgTUp)

The normal console will appear as a pane below the sources tab.

![](/files/-MGNhAZnx2qnKIXCFDm9)

#### Pause on Debugger / Pressing Play

Run your code to get the debugger to pause. The play arrows that advance the debugger are above the screen and in the control pane of the sources tab.

![](/files/-MGNhE3gBOTzsHWcrpyT)

### Debugging Strategies

{% embed url="<https://youtu.be/HjXyyRbkpG8>" %}

### `console.log`

`console.log` should be the default way to try to understand your code. When it seems like you need more precision, or if a console won't be able to cover the breadth of data you need to look at, you can switch to debugger.

### Debugger

Debugger allows you to see into the code exactly when and where you want to. It gives you a level of insight that you can't get only with `console.log`.

## Exercises

### Drawing App Debugging

Open your drawing game and set a breakpoint inside the loop. Open the console to inspect the values at that point. Advance the debugger to see the values as the loop continues.

Use `git clone` to get a copy of [Kai's reference solution for the drawing app. ](https://github.com/kai-rocket/basics-drawing)Open it in the browser and set a breakpoint inside the inner loop. Open the console to inspect the values at that point. Advance the debugger to see the values as the loop continues.


# DOM

## Setup

1. Clone the [DOM starter code](https://github.com/rocketacademy/basics-next-steps-dom).
2. Please refer to [10.2: Browser Applications with DOM](/10-advanced/10.3-browser-applications-with-dom) if you need a refresher.

## Base

### Creating Elements

#### makeBox

Create an empty function called `makeBox`. `makeBox` will create a new HTML element on screen each time it's called.

If you were to write out the HTML element it would look like the following.

```markup
<div>
    <p>Make Box was Called</p>
    <p>Hello :)</p>
</div>
```

Specifically `makeBox` needs 7 steps.

1. Create the `p` paragraph tag. Something like: `var pOne = document.createElement('p');`
2. Fill the tag with text using `innerText`. Something like: `pOne.innerText = 'haha';`
3. Create a second `p` paragraph tag.
4. Fill the tag with text using `innerText`.
5. Create the `div` tag.
6. Put both `p` tags into the `div` tag using `appendChild`. Something like: `divTag.appendChild( pOne );`
7. Put the `div` tag onto the page with `document.body.appendChild.`

Edit `style.css` so you can clearly identify the box.

```css
div {
  background-color: white;
  border: 2px solid red;
  padding: 10px;
  margin: 10px;
}
```

Call the `makeBox` function inside of `script.js`.

#### makeCard

Create a function `makeCard` that creates card elements with the following HTML structure. See the next code snippet for how to set an `img` tag's `src` attribute in JS.

```markup
<section>
  <p>
    Hello Ducks
  </p>
  <p>
    <img src="https://gblobscdn.gitbook.com/assets%2F-MBhJa4xpezxI4J9lolG%2F-MGrF6rE0CBWVzznQayq%2F-MGrGfwNRi1D6aKWmg4G%2Fducks2.jpeg?alt=media&token=9dff244b-10e8-4fab-ab68-715e09998ff3"/>
  </p>
</section>
```

Here is how we might set an `img` tag's `src` attribute in JS.

```javascript
imgTag.src =
  'https://gblobscdn.gitbook.com/assets%2F-MBhJa4xpezxI4J9lolG%2F-MGrF6rE0CBWVzznQayq%2F-MGrGfwNRi1D6aKWmg4G%2Fducks2.jpeg?alt=media&token=9dff244b-10e8-4fab-ab68-715e09998ff3';
```

Edit `style.css` for `makeCard` to better identify our cards in the UI.

```css
section {
  background-color: grey;
  border: 2px solid blue;
  padding: 10px;
  margin: 10px;
}
```

Call `makeCard` in `script.js`.

### Responding to HTML Events

Update the `makeBox` function to also render a button with the words "Make Card". The corresponding HTML might look like the following, but we will construct it using JS.

```markup
<div>
  <p>Make Box was Called</p>
  <p>Hello :)</p>
  <button>Make Card</button>
</div>
```

Trigger the `makeCard` function when the user clicks the "Make Card" button by calling `addEventListener` on the button with `makeCard` as the callback function.

```javascript
var button = document.createElement('button');
button.innerText = 'Make Card';
button.addEventListener('click', makeCard);
```

## More Comfortable

### Multi-Card Button

Change the `makeCard` function so that it creates multiple cards when the button is clicked. We can create and append elements in a loop inside `makeCard`.

### More Images

1. Get another image URL from the internet
   1. Search for an image
   2. Right click on the image in Chrome
   3. Select "Copy Image Address"
2. Put these images into an array and loop over each image in the array to create the set of cards

### Random Image

Change `makeCard` so that when the user clicks, she gets a single card with a random image.

### Random Number of Images

Add an input to the box created by `makeBox`. The user can fill out a number X in the input. When they click the button, X images appear inside the new card.


# Further Readings

## More JavaScript Practice

<https://www.asmarterwaytolearn.com/js/index-of-exercises.html>

## JavaScript with DOM

Khan Academy has a good set of follow-on lessons that will dovetail with the DOM material we covered here in [10.2](/10-advanced/10.3-browser-applications-with-dom) and [11](/11-post-course-exercises/pce-dom).

{% embed url="<https://www.khanacademy.org/computing/computer-programming/html-css-js>" %}

## Javascript Programming

Khan Academy also has some fun lessons that are more focused around programming concepts and fun things to build.

{% embed url="<https://www.khanacademy.org/computing/computer-programming/programming>" %}

{% embed url="<https://www.khanacademy.org/computing/computer-programming/programming-games-visualizations>" %}

{% embed url="<https://www.khanacademy.org/computing/computer-programming/programming-natural-simulations>" %}

## Computer Science Fundamentals

For a broader Computer Science overview of the field, **Harvard's CS50** is a good choice. This course is quite a bit more difficult than Fundamentals and uses the C programming language, among others.

You can take the course through a MOOC (Massive Open Online Course) at EdX: <https://www.edx.org/course/introduction-computer-science-harvardx-cs50x> or, use the course materials separately: [https://cs50.harvard.edu/](https://cs50.harvard.edu)

Alternatively, you can attempt <https://teachyourselfcs.com/> where it lists subjects you will encounter over the course of taking a Computer Science degree.

## Building Real World Projects

If you're interested in how real-world software systems are built you can begin to learn about a modern set of libraries and tools you'd need to do that.

### Front-end

This Codecademy course is the closest to the material we've already covered that will show you how modern Front-end apps are built: <https://www.codecademy.com/learn/paths/front-end-engineer-career-path>\
\
Note: Front-end here, refers to the browser, where we ran all of the code in Fundamentals.

### Back-end

This Codecademy course covers the basics of backend JavaScript servers that you would need to know to work with the internet, requests and handling data, like with the SQL language.

<https://www.codecademy.com/learn/paths/back-end-engineer-career-path>


# Day 2: Basic File and Data Manipulation

## Introduction

We will now put to use what we have learned so far. Before you attempt a problem, be sure to:

1. Read through the entire problem statement individually.
2. Check your understanding of the problem by **discussing with your partner**:
   1. What the program needs to do.
   2. How it can be implemented.
3. Write or type, in plain English, the instructions you and your partner want your program to follow.

For some problems you may need to google for information. Remember that as pairs, you are also googling together. **Please switch driver and navigator for each problem statement.**

When you run into a bug, talk out loud with your partner what you *expected* to happen, and what happened instead, before attempting to find a solution.

If needed, use the **'ask host for help'** function in Zoom. You may also find the **"annotate" feature** in Zoom useful when pair programming.

## Base

For each exercise, make a copy of the [starter code](https://github.com/rocketacademy/fundamentals-starter-code/archive/refs/heads/main.zip) as per the [recommended folder structure for Fundamentals](/course-logistics/required-hardware-and-software/recommended-set-up). For some exercises you may need to google for information.

See an example of all problems [here](https://rocketacademy.github.io/fundamentals-starter-code/day1/index.html).

### **Minutes in Weeks**

The user will enter a number of weeks. The program should output the number of minutes in those weeks in the output box.

Format the output nicely. Like: `In 3 weeks there are 30240 minutes! Wow!`

### **Fahrenheit to Celsius**

The user enters a temperature in Fahrenheit. The program should output the conversion to Celsius in the output box.

Format the output nicely.

### **Road Trip Cost**

The user will enter the length of a planned road trip in his brand new Ferrari. The program should output the estimated fuel cost of the road trip.

A new Ferrari consumes 9km/litre. Petrol costs $2.20/litre.

Format the output nicely.

### **Ice Cream Buffet**

There's all-you-can-eat ice cream at the buffet. The buffet receives ice cream in 400ml containers. To save money the buffet only provides 70ml cups for customers to get ice cream.

The user will enter a number of trips to the ice cream station (picking up **1 cup per trip**) and the app will calculate how many **containers** of ice cream you would consume. It is ok to show the number of containers in decimal format.

### **Time to Type Sonnets**

The user will enter their words-per-minute typing speed. The app will calculate how long it will take them to type all of Shakespeare's sonnets in hours.

For simplicity, assume 17,677 words in all of Shakespeare's sonnets.

## Comfortable

See an example of all problems [here](https://rocketacademy.github.io/fundamentals-starter-code/day2/).

### Cost of Air Con

The user enters the number of hours of air-con use, and the app tells them the cost.

An aircon machine uses 2 kilowatts of electricity.

Electricity costs $0.20 per kilowatt-hour.

### Screen Time

The user will enter the number of hours spent per day on their favourite app, and the program renders how many days you will spend in your lifetime on this app.

Assume an average life expectancy of 82 years.

On [Android 10](https://wellbeing.google/tools/), [iOS 12](https://support.apple.com/en-us/HT208982), and later versions, we can see how many hours per day we spend on each app. Find the number of hours you spend per day on the app you use most. If you're not able to find this, you can google for common statistics.

For example, if I spend 2 hours per day on WhatsApp and I live an average lifetime of 82 years, how many total days will I spend on WhatsApp during my life?

## More Comfortable

### Ice Machine

A hotel uses an ice machine to prepare ice for guests. They want to start the ice machine as close to each event as possible, so that the ice doesn't melt. In order to do this, they need to estimate how long they will need to run the ice machine.

Create a program that estimates the duration the ice machine needs to run. The user will input the number of guests for the event.

Assume each guest needs 2 drinks. Each drink has 4 ice cubes. Each cube weights 1.5 grams. The hotel's American-made ice machine produces 5 pounds of ice per hour.

### Beer Order

Create a program for a bar to calculate how many kegs of beer they will need every day. The user will enter the average number of customers per day, and the app will estimate how many half-barrel-size kegs the bar needs per quarter.

Assume an average customer drinks 2 pints per visit. There are 124 pints of beer in a half-barrel keg.

## Reference Solution

[Here](https://github.com/rocketacademy/fundamentals-starter-code/blob/day1/script.js) is a reference solution for the Data Manipulation exercises above. Please only view the reference solution for each exercise after you have attempted the exercise yourself. Note that there are many ways to implement these solutions and the reference solution is only 1 way.


# Day 3: Functions

## Introduction

Today we will write functions to perform data transformations, similar to examples in [3.1: Functions](/3-structuring-and-debugging-code/3.1-functions). For each exercise, make a copy of the [starter code](https://github.com/rocketacademy/fundamentals-starter-code/archive/refs/heads/main.zip) as per the [recommended folder structure for Fundamentals](/course-logistics/required-hardware-and-software/recommended-set-up). For some exercises you may need to google for information.

**Please switch driver and navigator each exercise, and share your solutions with your partner.**

## Knowledge Check

Before you begin, check that you and your partner can answer the following:

* [ ] How do you define a function?
* [ ] How do you execute a function?
* [ ] Where can you execute a function?
* [ ] How many times can you use a function?
* [ ] What is the purpose of the `return` keyword? What happens if we omit the `return` keyword from a function?

## Learning Outcomes

* Practice **writing helper functions** *(and not just solve for the correct calculation)*
* Executing multiple helper functions as part of the overall program.
* Practice creating contextual, meaningful variables.

## Base

*If you have attempted these problems as part of More Comfortable in Day 1, today re-write the code such that all of the logic is in helper functions and not solely in* `main.`

See an example of all problems [here](https://rocketacademy.github.io/fundamentals-starter-code/day2/).

### Cost of Air Con

The user will enter the number of air-con use time, the app will then be able to estimate the cost it will need to run.

The air-con needs 2 kilowatts of electricity per hour to run.&#x20;

Electricity cost $0.20 per kilowatt per hour

### Screen Time

The user will enter the number of hours spent per day on their favourite app, and the program renders how many days you will spend in your lifetime on this app.

Assume an average life expectancy of 82 years.

On [Android 10](https://wellbeing.google/tools/), [iOS 12](https://support.apple.com/en-us/HT208982), and later versions, we can see how many hours per day we spend on each app. Find the number of hours you spend per day on the app you use most. If you're not able to find this, you can google for common statistics.

For example, if I spend 2 hours per day on WhatsApp and I live an average lifetime, how many total days will I spend on WhatsApp in my lifetime?

### Ice Machine

A hotel uses an ice machine to prepare ice for guests. They want to start the ice machine as close to each event as possible, so that the ice doesn't melt. In order to do this, they need to estimate how long they will need to run the ice machine.

Create a program that estimates the duration the ice machine needs to run. The user will input the number of guests for the event.

Assume each guest needs 2 drinks. Each drink has 4 ice cubes. Each cube weights 1.5 grams. The hotel's American-made ice machine produces 5 pounds of ice per hour.

### Beer Order

Create a program for a bar to calculate how many kegs of beer they will need to order for each quarter-year (output) based on their estimated number of daily customers (input).

Assume that the average customer drinks 2 pints per visit; and each keg of beer pours exactly 124 pints.

## More Comfortable

### Cost of Cellular Data

Create a program to calculate how much a user will pay for their the $19.99 50GB post-paid data plan. The user will enter how many GB they use per month, and the app will tell them how much they are paying per GB of data used.

Assume that if the user exceeds 50GB, they will automatically purchase an additional 50GB plan. You may find the built-in function `Math.ceil` helpful for this *(you can google how to use it)*.

For example, if the user only used 1GB this month, the app would calculate $19.99 per GB as the user paid $19.99 for the 50GB plan but only used 1GB. If the user used 2GB this month, the app would calculate $9.98 per GB. If the user used 51GB this month the user would have automatically been billed for 2 plans and the app would calculate $0.78 per GB.

### Mortgage Calculator

Create a mortgage calculator for a bank. This bank is just starting so their loan terms are simple and the same for everyone. The user will enter the loan amount. The interest is 3% APR. The loan duration is 10 years.

Output several values including:

1. How much the customer will pay back in total, including the principal.
2. How much the customer will pay just in interest.
3. How much the customer's monthly payment will be.

{% hint style="warning" %}
**Concatenating Strings and Numbers**

Sometimes when trying to add 2 numbers you may find that your numbers concatenate instead of add. For example, when adding '1' + 1 in your code, the result may be '11' instead of 2. This is because one of your numbers may be represented in JS as a string, most commonly when the number comes from the `input` variable in our programs.

To resolve similar issues, try converting `input` to a number with [JS' built-in Number function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) before using it, e.g. `const loanAmt = Number(input)`.

The following is a more detailed breakdown of JS behaviour when concatenating strings and numbers.

1. String + String
   1. 'hello' + 'hi' will return 'hellohi'
   2. '2' + '2' will return '22'
2. Number + Number
   1. 2 + 2 will return 4
3. Number + String
   1. 2 + '2' will return '22'
      {% endhint %}

## Reference Solution

[Here](https://github.com/rocketacademy/fundamentals-starter-code/blob/day2/script.js) is a reference solution for Day 2 exercises. Please only view the reference solution for each exercise after you have attempted the exercise yourself. Note that there are many ways to implement these solutions and the reference solution is only 1 way.


# Day 4: If Statements, Boolean Or, Boolean And

## Introduction

Today we will practice if statements and logical OR operators.

See an example of all problems [**here**](https://rocketacademy.github.io/fundamentals-starter-code/day3/index.html).

**Please switch driver and navigator each exercise, and share your solutions with your partner.**

## Knowledge Check

Before you begin, check that you and your partner can answer the following:

* [ ] Why use logic in our programs?
* [ ] What is an if statement?
* [ ] What is a code block? What marks the start and end of a block of code?
* [ ] What is a Boolean value? What is a Boolean variable?
* [ ] What is a Boolean operator? What are the different kinds of Boolean operators?

## Base

### Lucky 11

Create a dice game that allows a user to roll 2 dice and submit a guess when the Submit button is clicked. The user wins if either

1. One of the dice roll matches their guess, or
2. If the total dice roll is 11.

Otherwise the user loses.

{% hint style="info" %}
To test your winning logic, consider using [code control logic from Module 4.3](/4-conditional-logic/4.3-boolean-and-not#code-control), where we temporarily return a fixed number at the start of our random number generator function.
{% endhint %}

### Hawker Food Categorisation

Hawker food is a convenient and affordable food option in Singapore. To help educate non-Singaporeans about hawker food, create an app that takes a hawker dish name as input, and tells users whether the dish has a "rice", "noodle", or "other" base. Some sample dishes are: "chicken rice", "roti prata", "nasi lemak", "hokkien mee", "bak kut teh", and "laksa".

For example, if a user enters "laksa", the program should output "noodle". If a user enters "roti prata", the program could output "other".

Please use the `||` operator.

## Comfortable

### 4D with Single-Digit Comparison

[4D](http://www.singaporepools.com.sg/en/rules/Pages/4d-game-rules-general.html) is a popular betting game in Singapore run by Singapore Pools. Rocket Academy does not endorse gambling.

Create a version of 4D where the player wins if their guess matches **any** of the 4 digits. The player will input a **single** digit, and the computer generates 4 random digits between 0 and 9. If the player-inputted digit matches **any** of the randomly-generated digits, the player wins.

In addition to the win/loss result, output the player guess and all randomly-generated digits so the player can see how close they were.

### Hawker Food Randomness

The uncle at your favourite hawker stall has decided to challenge himself and serve a random hawker dish to each customer. The dishes in his repertoire are: "chicken rice", "roti prata", "nasi lemak", "hokkien mee", "bak kut teh", and "laksa". Customers that correctly guess Uncle's dish receive a free meal.

Create an app that uses random numbers to help Uncle decide which dish to cook. The customer can only input dish names. If the customer correctly guesses Uncle's dish, let her know that she gets a free meal!

{% hint style="info" %}
Reminder: There is no need to complete all exercises on this page. Once comfortable with the concepts, feel free to move on to 'Project Planning: Scissors Paper Stone'. You can always come back and attempt the additional problems when you are feeling *more comfortable.*
{% endhint %}

## More Comfortable

### 4D with Winning Range

Create a version of 4D where the player wins if they guess within 1000 (above or below) of the winning 4-digit number. Consider using comparison operators such as less than (`<`) and greater than (`>`).

### Hawker Food Omakase

{% hint style="danger" %}
Hawker Food Omakase is hard! It took Kai about 45 minutes to create the reference solution.
{% endhint %}

Uncle has decided to serve an omakase option, and output a menu based on customer input.

1. Customers can input either "rice" or "noodle", and Uncle will choose either 2 random rice or 2 random noodle dishes for them. Assume Uncle's rice dishes are "chicken rice", "nasi lemak", and "bak kut teh", and Uncle's noodle dishes are "hokkien mee", "laksa", and "beef hor fun".
2. Roti prata is neither rice nor noodle, but Uncle can randomly choose to include it as one of the two dishes if he feels like it.
3. Uncle charges more for omakase and uses premium descriptions for his dishes. Feel free to get creative. To create a new line in the output box you can use the string `'<br>'`, which generates a new line in HTML output.
4. Output at the end if sambal is included. Not all dishes come with sambal, for example roti prata and bak kut teh don't come with sambal.

#### Sample Output

The customer inputs "rice" and the app chooses 2 random rice dishes, nasi lemak and bak kut teh. Roti prata is randomly not chosen. Sambal is included because nasi lemak typically comes with sambal.

```
Uncle has prepared a selection of dishes for you!

To begin, Nasi Lemak, a fragrant coconut rice. Accompanied by Korean-style fried chicken wing, organic ikan bilis and free-range egg.

This will be followed by Bak Kut Teh, a simmered pork rib broth with fatty pork rib. Accompanied by braised peanuts, you tiao crullers and freshly-blanched chai sim.

Chilli sambal will be included.
```

## Reference Solution

[Here](https://github.com/rocketacademy/fundamentals-starter-code/blob/day3/script.js) is a reference solution for Day 3 exercises. Please only view the reference solution for each exercise after you have attempted the exercise yourself. Note that there are many ways to implement these solutions and the reference solution is only 1 way.


# Day 5: Program State

## Introduction

Today we will practice using global variables to store and change the state of the program..

See an example of all problems [**here**](https://rocketacademy.github.io/fundamentals-starter-code/day4/index.html).

**Please switch driver and navigator each exercise, and share your solutions with your partner.**

## Knowledge Check

Before you begin, check that you and your partner can answer the following:

* [ ] Why use global variables?
* [ ] What is the difference between global and local variables?
* [ ] Can a global variable be accessed or manipulated within a function?
* [ ] Can a variable declared in `main` be accessed or manipulated in a different helper function?

## Base

### Secret Word

Create a game where a player must correctly guess secret words to win.

The computer chooses a random word from a set of three words. Feel free to use whatever words you'd like, but we will be using the words *"banana"*, *"chisel"*, and *"faucet"*.

To win the game the player must guess correctly **twice** in **total;** but is allowed to guess wrongly in between their two correct guesses.

For each guess, output all information such as the guessed word, the secret word, and how many correct guesses the player still needs until she wins.

## Comfortable

### Secret Word Twice in a Row

Update Secret Word with an additional rule: The player must guess correctly twice *in a row* to win.

### Secret Word X in a Row

Update Secret Word game such that the number of times the player needs to guess correctly in a row changes between rounds.

We define "round" as all gameplay until a player wins. The number of times the player needs to guess correctly is a number from 2 to 4, randomly chosen at the start of the round.

When the player wins, the computer updates the number of times the player needs to guess correctly in a row for the next round.

Consider using [input control from Module 6.3](/4-conditional-logic/4.3-boolean-and-not#code-control) to test your logic.

## More Comfortable

{% hint style="info" %}
Reminder: There is no need to complete all exercises on this page. Once comfortable with the concepts, feel free to move on to [Scissors Paper Stone: Part 2](/projects/project-1-scissors-paper-stone/project-1-scissors-paper-stone-part-2) You can always come back and attempt the additional problems when you are feeling *more comfortable.*
{% endhint %}

### Dice Within

Create a new version of our Coding Fundamentals dice game (where the player guesses the dice roll) that randomly becomes easier or harder. At the beginning of the game and each time the player wins, the computer selects a random number from 1 to 3, which we call the "within number". If any of the player's guesses fall within the dice roll plus or minus the within number, the player wins.

For example: the app randomly chooses 3 as the within number. The player can guess within 3 of the dice roll to win the game. The player guesses 2 and the dice roll is 5. The guess is within 3 of the dice roll so the player wins the game. At this point, the computer adjusts the difficulty of the game by choosing a new within number.

### Dice Within with 2 Dice

Update our dice game to include an additional dice. With each player guess, the computer rolls 2 dice. If the player guess is within either of the 2 dice rolls plus or minus the within number, the player wins.

### Dice 4D

Update our dice game to allow the player to play a round of 4D every 2 times the player wins the dice roll guess. Use [input control from Module 4.3](/4-conditional-logic/4.3-boolean-and-not#code-control) to verify our 4D game logic, that it is possible to win this 4D game.

### Secret Word Twice in a Row 2

Update Secret Word with the following additional rules.

1. The player must guess correctly twice in a row to win
2. Secret words cannot be repeated 2 guesses in a row. E.g. the secret word cannot be "banana" for 2 player guesses in a row. If the secret word for the 1st guess were "banana", the secret word for the 2nd guess would have to be either "chisel" or "faucet".

## Reference Solution

[Here](https://github.com/rocketacademy/fundamentals-starter-code/blob/day4/script.js) is a reference solution for Day 4 exercises. Please only view the reference solution for each exercise after you have attempted the exercise yourself. Note that there are many ways to implement these solutions and the reference solution is only 1 way.


# Day 6: Scissors Paper Stone Redux

## Objectives

1. Play partner's game on your machine.
2. Read partner's code.
3. Edit and discuss code together.
4. Improve each other's projects.

## Code Review

On days when projects are due, we will review each others' code in groups of 2 or 3 during class. If there is a group of 3, the triplet will do individual code review together so that everyone gets to review someone else's code, then split into 2 groups for pairing.

### 1. Run Partner's Code

Open the code in the browser and test it. What does it do? If you're not sure what it does look inside `script.js` to see.

### 2. Read Partner's Code

Read the code:

1. How does it work?
2. Does it have any obvious errors?
3. Does it implement something that you were trying to do?
4. Does it implement a feature that you haven't started yet? How does the code work?

**Code Review Reflection Questions**

While you are reading, note down the answers to the following questions: No need to be comprehensive, but pick out parts of the code you found notable.

1. Note a line of code (or multiple lines) that you think works well. This could be the logic of the code, or just a well-named variable. Explain why it works well.
2. Note a line of code (or multiple lines) that you thought was unclear or you can't figure out. How would you explain why is it unclear or hard to figure out?
3. Note a line of code (or multiple lines) where you found a bug. Why is it a bug? Do you have a solution?

### 3. Edit Partner's Code

It may be helpful to make changes to the code to help you understand it better. Write some `console.log` that would help you figure out what the code does. Break the code in a certain way to prove how it works or doesn't work.

### 4. Discuss

Once both partners are done with #1-4, discuss what you saw. Read out and review together the answers to the 3 questions you wrote down from above.

## Improve Project Together

You'll be pair programming on one person's project at a time.

**The driver will be the person who is \_not**\_\*\* working on their own code.\*\*

Once done with one person's code, send the code to your pair (it's their project) via a community channel code snippet. Switch to work on the other person's code.

Work on the game in the following order:

### 1. Fix Errors

If there are any errors or bugs in a project, pair to fix those problems.

### 2. Add Features

If there were any features you wanted to implement but couldn't, use this time to pair-program your desired features, or anything else you'd like to see in your game.

If you have nothing else to add, here are some ideas:

#### A) Multi Game - Guess the Word

Your pair will turn the Scissors Paper Stone game into a Multi game app. Add a mode for a new "guess the secret word" game. The user will type in "word game" (or any secret phrase of your choice) to switch to this mode.

The game itself will be the same as the game in the code example in [4.1](/4-conditional-logic/4.1-intro-to-logic#simple-conditional-example-secret-phrase)

#### B) Dice Game

Add a third mode to the super game, a guess the dice roll game. The user will enter "dice game" to switch to this mode. (The dice game is the same dice game as the original basic version in [4.1](/4-conditional-logic/4.1-intro-to-logic#dice-game)).

### 3. Comfortable

Continue to add to the Scissors Paper Stone game. Complete the [version 1 more comfortable](/projects/project-1-scissors-paper-stone/project-1-scissors-paper-stone-part-1#more-comfortable) or [version 2 more comfortable](/projects/project-1-scissors-paper-stone/project-1-scissors-paper-stone-part-2#more-comfortable) features that haven't been implemented yet.


# Day 7: Loops

## Introduction

Today we will practice arrays and loops. For each exercise except Infinite Loop, make a copy of the [starter code](https://github.com/rocketacademy/fundamentals-starter-code).

Pick either one of the Emoji Drawing or Multi-Dice Game exercise and work through from Base to your preferred level of comfort, before attempting the other exercise.

{% tabs %}
{% tab title="Emoji Drawing" %}

#### Base

Use loops to create an app that draws emojis into the grey box. See [here](https://support.microsoft.com/en-us/windows/windows-10-keyboard-tips-and-tricks-588e0b72-0fff-6d3f-aeee-6e5116097942) for how to input Emoji on Windows and [here](https://support.apple.com/en-sg/guide/mac-help/mchlp1560/mac) for how to input emoji on Mac.

See an example of all problems [**here**](https://rocketacademy.github.io/fundamentals-starter-code/day5/drawingemoji/index.html)**.**

**Number of Characters**

The user will enter a number of characters to display on the screen.

For example, if the user enters 4 they will see this:

![](/files/-MNS29H3lAidTAY1g37r)

**Square**

The user will enter the dimensions of a square to display on the screen.

Use a loop within a loop and the `<br>` HTML tag in your output to create the square.

For example, if the user enters 4 they will see this:

![](/files/-MFaZs6SHcL2uPWDNwFt)

#### Comfortable

**Triangle**

The user will enter the dimensions of a triangle to display on the screen.‌

Use a loop within a loop, a conditional and the `<br>` HTML tag in your output to create the triangle.

For example, if the user enters 4 they will see this:

![](/files/-MFa_4dzFATYUaHIUhSP)

#### More Comfortable

**Outline Square**

The user will enter the dimensions of a square to display on the screen. The square is outlined by a different character.

For example, if the user enters 4 they will see this:

![](/files/-MFaaeuGuRVPdtE7JTPc)

**Center Square**

The user will enter the dimensions of a square to display on the screen. The square is outlined by a different character and there is another different character in the center. The app doesn't allow dimensions that will not allow the center character.

For example, if the user enters 5 they will see this:

![](/files/-MFab4_PWJVownX9ljUx)
{% endtab %}

{% tab title="Multi-Dice Game" %}

#### Base

More dice rolling and guessing! See an example of all problems [**here**](https://rocketacademy.github.io/fundamentals-starter-code/day5/dicegame/index.html).

1. Create a dice-guessing game with a variable number of dice rolls determined by the user.
2. The game will have 2 modes.
3. In the 1st mode, the user will enter the number of dice they wish to roll.
4. In the 2nd mode, the user will enter a guess that will apply to all dice rolls. For example, if the user has chosen to roll 2 dice in Mode 1 and guesses 4 in Mode 2, that guess of 4 will apply to both Dice 1 and Dice 2.
5. After the user guesses, the program will run a loop where the number of iterations is the number of dice rolls from Mode 1. Each loop iteration will roll a dice and verify if the user has won.
6. If the user guesses correctly for any of the dice rolls, the user wins.
7. The game keeps track of and outputs the overall win-loss record.

#### More Comfortable

**Multi-Round Multi-Dice Game**

1. Alter the previous multi-dice game such that the user plays 4 rounds in the 2nd mode.
2. After the user enters their guess in Mode 2, the program enters a loop that runs 4 rounds.
3. Within each round the game will roll the number of dice the user specified and compare them with the single user guess.
4. If the user guessed correctly for any dice rolls in a round, they win that round.
5. The game will continue to output overall win-loss record, where each of the 4 rounds count as wins or losses.

**Two Player Multi-Round Multi-Dice Game**

1. Change the game to support 2 players, starting with Player 1.
2. The gameplay follows the multi-round multi-dice game above. After each player's turn, that player will have won between 0 and 4 rounds, because each player plays 4 rounds per turn.
3. The game alternates between players indefinitely and outputs win-loss record for each player.

**Multi-Player Multi-Round Multi-Dice Game**

Change the game to ask how many players are playing the game. Players will take turns playing the game as above.
{% endtab %}
{% endtabs %}

## Reference Solution

[Here ](https://github.com/rocketacademy/basics-drawing/pull/9/files)is a reference solution to the Drawing exercises, and [here](https://github.com/rocketacademy/fundamentals-starter-code/blob/day6/script.js) is a reference solution for Dice Game exercises. Please only view the reference solution for each exercise after you have attempted the exercise yourself. Note that there are many ways to implement these solutions and the reference solution is only 1 way.


# Day 8: Arrays and Loops

## Introduction

Today we will practice arrays with occasional loops through the game of Mad Libs. Note that loops may not be necessary for every exercise.

Mad Libs is a word game where players fill in the blanks with random words, such that the final sentence is usually funny. If you're unfamiliar with Mad Libs, please read the Wikipedia description [here](https://en.wikipedia.org/wiki/Mad_Libs).

#### Example "Mad Lib" Sentence from Wikipedia

```
"___________! he said ________ as he jumped into his convertible ______ and drove off with his _________ wife."
 exclamation           adverb                                     noun                         adjective
```

## Getting Started

For the 1st exercise, make a copy of the [starter code](https://github.com/rocketacademy/fundamentals-starter-code). For subsequent exercises, feel free to comment out your previous code and create a new `main` function for the current exercise. Please switch driver and navigator each app.

See an example of all problems [**here**](https://rocketacademy.github.io/fundamentals-starter-code/day7/index.html).

## Base

### Mad Libs Adjectives

#### Example Mad Lib in Code

The following code is the above example Mad Lib written in JavaScript, where the exclamation, adverb, and noun have been hard-coded and `randomAdj` refers to the random adjective our program will randomly select to complete the Mad Lib.

```javascript
var madLib =
  '"WOW!" he said EXCITEDLY as he jumped into his convertible PAPAYA and drove off with his ' +
  randomAdj +
  ' wife.';
```

#### Instructions

*Please read all instructions before getting started.*

1. When the Fundamentals Starter Code app loads, the user can input 1 adjective at a time to store in the app. Store the user-inputted adjectives in a global array variable.
2. When the user inputs the word "create" the app completes the Mad Lib with a random word from the user-inputted adjectives array and outputs the completed Mad Lib in the grey box.

#### Random Elements from an Array

In order to get a random value from an array we can generate a random integer in the range of: zero to the last index of the array.

```javascript
var getRandomIndex = function (arrayLength) {
  // create a random number from zero to array length minus one.
  // this number is in the range from the first
  // index (zero) to the last index (array length minus one)
  var randomIndex = Math.floor(Math.random() * arrayLength);
  return randomIndex;
};
```

## Comfortable

### Popular Mad Libs

Keep track of which words are selected. Create and allow the user to switch to a new game mode that always shows a completed Mad Lib on Submit using the set of words (verb, adjective, etc.) that the app has (randomly) selected most often so far.

### Input and Create Mode

When the Fundamentals Starter Code app loads it starts in "input", or normal mode. In input mode, the user can add adjectives to their adjectives list with each Submit.

When the user inputs "create", change the game mode to create mode. In create mode, each Submit prompts the app to complete your Mad Lib.

### Input Multiple Words

When the Fundamentals Starter Code app loads, the user can input 1 or more adjectives to store in the app with each Submit. To input more than 1 word for each Submit, the user would give each word separated by a space, e.g., "*green nice silly*". We can use JavaScript's string `split` method to split the input string into an array of substrings. See W3Schools docs [here](https://www.w3schools.com/jsref/jsref_split.asp) for details.

{% hint style="info" %}
Reminder: There is no need to complete all exercises on this page. Once comfortable with the concepts, feel free to work on Project 2: *Beat That!* as a pair, or go back and solve / refactor previous *More Comfortable* exercises like [*Hawker Food Omakase*](/in-class-exercises/day-4-if-statements-boolean-or#hawker-food-omakase) with your newly learnt skills.
{% endhint %}

## More Comfortable

### Mad Libs Multiple Word Types

Update our Mad Lib to take additional word types.

```javascript
var madLib = `${randomExclamation}! he said ${randomAdverb} as he jumped into his convertible ${randomNoun} and drove off with his ${randomAdj} wife.`;
```

Create modes to input words from different word types, e.g. exclamation, adverb, noun, and adjective. For each type, prompt the user what type of word they should be entering. If it's too tedious to support 4 word types, considering starting with 2 word types.

### Sets of Mad Libs

Store an array of Mad Lib sentences in your app. For example, Mad Lib 1 might be:

> She asked {adverb} for the {noun} and when they were rude, she said {exclamation} and hung up the {adjective} phone.

Mad Lib 2 might be:

> It was a {adjective}, cold November day. I woke up to the {adjective} smell of {noun} roasting in the {noun} downstairs.

Update create mode to pick a random Mad Lib sentence and set of words and output the completed Mad Lib in the grey box on Submit.

Feel free to see Google results [here](https://www.google.com/search?q=mad+lib+examples\&tbm=isch) for potential Mad Lib inspiration.

## Reference Solution

[Here](https://github.com/rocketacademy/fundamentals-starter-code/tree/day7) is a reference solution for Day 7 exercises. [Here](https://github.com/rocketacademy/fundamentals-starter-code/tree/day7-moreComfortable) is a reference solution for Day 7 More Comfortable exercises. Please only view the reference solution for each exercise after you have attempted the exercise yourself. Note that there are many ways to implement these solutions and the reference solution is only 1 way.


# Day 9: Beat That Redux

## Code Review

On days when projects are due, we will review each others' code in groups of 2 or 3 during class. If there is a group of 3, the triplet will do individual code review together so that everyone gets to review someone else's code, then split into 2 groups for pairing.

### Individual Review

#### 0) Push Your Own Code

Refer to the [push section](/8-github/8.2-github-fork-and-clone#git-push) for the commands needed for this.

#### 1) Clone Partner's Code

You'll be paired up so that you can exchange the links for your repos via your community channel. Remember that the forked repo is the one that is under your GitHub account, not Rocket Academy's. If you have forked the repo but haven't pushed your latest code to GitHub, take a moment now to `git push`. Let your partner know you're updating the repo. Run a `git clone <REPO_URL> <NEW_FOLDER_NAME>` to get a copy of your partner's code.

{% hint style="info" %}
Note: You need to rename the folder when you clone if you already have a folder named after the repo where you're making the clone.
{% endhint %}

#### 2) Run Partner's Code

Open the code in the browser and test it. What does it do? If you're not sure what it does look inside `script.js` to see.

#### 3) Read Partner's Code

Read the code:

1. How does it work?
2. Does it have any obvious errors?
3. Does it implement something that you were trying to do?
4. Does it implement a feature that you haven't started yet? How does the code work?

**Code Review Reflection Questions**

While you are reading, note down the answers to the following questions: No need to be comprehensive, but pick out parts of the code you found notable.

1. Note a line of code (or multiple lines) that you think works well. This could be the logic of the code, or just a well-named variable. Explain why it works well.
2. Note a line of code (or multiple lines) that you thought was unclear or you can't figure out. How would you explain why is it unclear or hard to figure out?
3. Note a line of code (or multiple lines) where you found a bug. Why is it a bug? Do you have a solution?

#### 4) Play with Partner's Code

It may be helpful to make changes to the code to help you understand it better. Write some `console.log` that would help you figure out what the code does. Break the code in a certain way to prove how it works or doesn't work.

#### 5) Discuss

Once both partners are done with #1-4, discuss what you saw. Read out and review together the answers to the 3 questions you wrote down from above.

### Peer Review

You'll be pair programming on one person's project at a time. The goal is to get working versions for each person. **The driver will be the person who is \*not\* working on their own code.**

Once done with one person's code, send the code to your pair (it's their project) via a community channel code snippet. Switch to work on the other person's code.

{% hint style="info" %}
Note: If you are working on your partner's code you can't push to their repo because GitHub repos are read-only to non-owners by default.
{% endhint %}

If you both have working versions, implement a new feature in one of the projects together.

## More Comfortable

Implement [More Comfortable exercises](/projects/project-2-beat-that#more-comfortable) in the project writeup. Once done, push your code to update your pull request in GitHub.

## Reference Solution

[Here](https://github.com/rocketacademy/basics-beat-that/pull/10/files) is a reference solution for Beat That. Please review the reference solution to see how we can improve our solutions!


# Day 10: Moar Cards / Chat Bot

## Introduction

Today we will practise JavaScript Objects. Choose one of the two exercises, *Moar Cards* or *Chat Bot*, and work your way through up till your preferred level of comfort. You are free to complete the other exercise at your own time.

{% tabs %}
{% tab title="Moar Cards" %}

#### Base

Feel free to copy the card deck generation function from [9.2: Card Deck Generation](/9-javascript-objects/9.2-card-deck-generation-with-loops#card-deck-generation-code) and the card shuffling functions from [9.1: JavaScript Objects](/9-javascript-objects/9.1-javascript-objects#card-shuffling) into your `script.js` file.

**Display Single Card**

Build an app using the Fundamentals Starter Code and the pre-class deck functions such that when the user clicks Submit, draw a single card from a shuffled deck and show it to them.

**Low Card**

Implement the High Card game from [9.1: Objects](/9-javascript-objects/9.1-javascript-objects#high-card) with 1 difference: the winner is the person with the *lowest* card.

**Low Card with Queen Winner**

Alter the Low Card game such that if any player draws a Queen, they win.

**Low Card Hands**

The player can input how many cards they want. The lowest of the player's cards is compared against the computer's 1 card. Show the player all the cards that they drew. Rules from above exercises continue to apply.

**Low Card Suit Output**

Implement a nice-looking output for Low Card. Use a helper function to display each card nicely with emoji (♠️, ♥️, etc.). Try to avoid repeating code if possible.

Example:

```
Player 1 drew:
1 of ♦️.

Player 2 drew:
6 of ♣️.

6 of ♣️ beats 1 of ♦!
Player 2 wins!
```

#### More Comfortable

**Low Card with Wild Card**

Update our latest Low Card implementation with the following twist. At the beginning of the game, pick (but do not draw) a random card in the deck to be the Wild Card. If either player draws the Wild Card, that player automatically wins.

**Low Card with Player-Chosen Wild Card**

Same rules as Low Card with Wild Card, except at the beginning of the game the player names a single card as input to be the Wild Card. The Wild Card can be identified with a card name and suit.

**Low Card with Bets**

Allow the player to wager points on each round. Add a new mode for the beginning of each round where the player selects the number of points to wager. They win the wagered points if they win, and lose the points if they lose or draw. The player begins with 100 points. After each round, output the player's remaining points.

**Low Card 2-Player Mode**

2 human players play against each other. The computer draws 3 cards for each player at the start of the game. The players take turns playing 1 card from their hand at a time. For each card played per player, the lowest card wins. The player that wins the best of 3 wins overall. The grey box will tell the players to switch so they don't see each other's cards.

**Low Card 2-Player Mode with Pairs**

Update the previous game logic such that if any player gets a pair in their hand, they win.

#### Reference Solutions

[Here](https://github.com/rocketacademy/fundamentals-starter-code/blob/day9/script.js) is a reference solution for Day 9 exercises. Please only view the reference solution for each exercise after you have attempted the exercise yourself. Note that there are many ways to implement these solutions and the reference solution is only 1 way.
{% endtab %}

{% tab title="Chat Bot" %}

#### Introduction

Today we will practice more complex code logic with nested objects and arrays.

We will make a chat bot that asks questions when the submit button is clicked. The user can respond by typing and submitting input and the bot can respond further. Please read all exercises before beginning to see how the chat bot can become more complex.

{% hint style="info" %}
**Please ensure you understand** [**the different ways to access elements in JavaScript Objects**](/9-javascript-objects/9.1-javascript-objects#reference) **before starting.**
{% endhint %}

**Sample Chat Bot Conversation**

The following is a sample conversation between Bot and User.

```
Bot: Hey, wow you seem happy today! Have you been coding? (yes/no/maybe)
---
User: Yes.
---
Bot: Wow! Me too! I've been working on the Blackjack project. Makes my day!
```

**Store Chat Bot Responses in Object**

We will use JavaScript Objects to encode the chat bot's potential responses.

```javascript
var answersAndResponses = {
  yes: `Wow! Me too! I've been working on the Blackjack project. Makes my day!`,
  no: 'Oh ok, just normally happy ;)',
  maybe: 'It seems the very thought of coding makes people happy!',
};
```

**Retrieve Chat Bot Responses with User Input**

We can retrieve the relevant chat bot response by using user input to access the relevant response from the answers object.

```javascript
// value of input is 'yes'
var responseText = answersAndResponses[input];
```

#### Base

**Single Chat Bot Answer Set**

Implement the chat bot described above, that asks a yes/no/maybe question and can respond to a user's response of "yes", "no", or "maybe".

**Multiple Chat Bot Answer Sets**

Extend the capabilities of the chat bot by storing question and answer text in the same object, like the following.

**Sample Answer Set**

```javascript
var questionAndAnswerSet = {
  question:
    'Hey, wow you seem happy today! Have you been coding? (yes/no/maybe)',
  answers: {
    yes: `Wow! Me too! I've been working on the Blackjack project. Makes my day!`,
    no: 'Oh ok, just normally happy ;)',
    maybe: 'It seems the very thought of coding makes people happy!',
  },
};
```

To have our chat bot support more than 1 question, put the above `questionAndAnswerSet` object into an array of chat bot answer sets, and add a 2nd answer set to our array. The bot will pick which question to ask and answer next.

**Sample Array of Answer Sets**

```javascript
var questionAndAnswerSets = [
  {
    question:
      'Hey, wow you seem happy today! Have you been coding? (yes/no/maybe)',
    answers: {
      yes: `Wow! Me too! I've been working on the Blackjack project. Makes my day!`,
      no: 'Oh ok, just normally happy ;)',
      maybe: 'It seems the very thought of coding makes people happy!',
    },
  },
  {
    question:
      'Do you enjoy coding most during the day, night, or both? (day/night/both)',
    answers: {
      day: 'Ah yes, when the sun is high in the sky, I can feel its energy too.',
      night: 'Under the calm and gentle moon, I also find my focus.',
      both: "Indeed, I could code 24/7 if I didn't have to sleep!",
    },
  },
];
```

Implement a chat bot that alternates between these 2 questions.

**Chat Bot Stores User's Name**

Add a new chat bot question that asks for the user's name and responds with a sentence containing the user's name. After greeting the user, the chat bot proceeds with the question from previous exercises.

**Sample Chat Bot Conversation**

```
Bot: Hey! I'm Robocop. What's your name?
---
User: Kai
---
Bot: Kai! What a cool name.

Kai, Hey, wow you seem happy today! Have you been coding? (yes/no/maybe).
```

Use the user's name in the bot's subsequent output. You may want to store the user name in a global variable.

**Sample Subsequent Bot Output**

```
Bot: Kai! Hey, wow you seem happy today! Have you been coding? (yes/no/maybe).
```

**Chat Bot Stores User's Age**

Update the chat bot to ask for the user's age after their name. The chat bot's response will differ based on the user's age. For example, we can respond with different outputs if the user is under 20, between 20-60, and above 60.

**Sample Chat Bot Conversation**

```
Bot: Hey! I'm Robocop. What's your name?
---
User: Kai
---
Bot: Kai! What a cool name. How old are you?
---
User: 63
---
Bot: What a wise age, Kai! Hey, wow you seem happy today! Have you been coding? (yes/no/maybe).
```

#### More Comfortable

**Chat Bot Named Answer Sets**

Update our chat bot answer set array to be an object whose keys are answer set IDs and values are answer sets. Also add a `nextQuestion` key to each answer set object, whose value is always an answer set ID, enabling us to chain question sequences in a named manner. This doesn't add new functionality beyond ordering questions using an array, but it sets up the next exercise Dynamic Chat Bot.

**Sample Answer Set Collection**

```javascript
var questionAndAnswerSets = {
  hasBeenCoding: {
    question:
      'Hey, wow you seem happy today! Have you been coding? (yes/no/maybe)',
    answers: {
      yes: `Wow! Me too! I've been working on the Blackjack project. Makes my day!`,
      no: 'Oh ok, just normally happy ;)',
      maybe: 'It seems the very thought of coding makes people happy!',
    },
    nextQuestionId: 'timeOfDay',
  },
  timeOfDay: {
    question:
      'Do you enjoy coding most during the day, night, or both? (day/night/both)',
    answers: {
      day: 'Ah yes, when the sun is high in the sky, I can feel its energy too.',
      night: 'Under the calm and gentle moon, I also find my focus.',
      both: "Indeed, I could code 24/7 if I didn't have to sleep!",
    },
    nextQuestionId: 'weather',
  },
  weather: {
    question: "Are you most productive when it's sunny or raining? (sun/rain)",
    answers: {
      sun: 'The sun warms my heart and powers me to code.',
      rain: 'The rain washes away my distractions and allows me to focus.',
    },
    nextQuestionId: 'hasBeenCoding',
  },
};
```

**Dynamic Chat Bot**

Update our chat bot to choose a next question based on the answer that the user gives. This next question's ID can be stored in the object that corresponds to the user's answer. See the following sample answer set collection for inspiration. Note that some questions have `nextQuestionId` nested within specific answers, and other question have `nextQuestionId` fixed for the question.

**Sample Answer Set Collection**

```javascript
var questionAndAnswerSets = {
  hasBeenCoding: {
    question:
      'Hey, wow you seem happy today! Have you been coding? (yes/no/maybe)',
    answers: {
      yes: {
        response:
          "Wow! Me too! I've been working on the Blackjack project. Makes my day!",
        nextQuestionId: 'timeOfDay',
      },
      no: {
        response: 'Oh ok, just normally happy ;)',
        nextQuestionId: 'happiness',
      },
    },
  },
  timeOfDay: {
    question:
      'Do you enjoy coding most during the day, night, or both? (day/night/both)',
    answers: {
      day: 'Ah yes, when the sun is high in the sky, I can feel its energy too.',
      night: 'Under the calm and gentle moon, I also find my focus.',
      both: "Indeed, I could code 24/7 if I didn't have to sleep!",
    },
    nextQuestionId: 'weather',
  },
  weather: {
    question: "Are you most productive when it's sunny or raining? (sun/rain)",
    answers: {
      sun: 'The sun warms my heart and powers me to code.',
      rain: 'The rain washes away my distractions and allows me to focus.',
    },
    nextQuestionId: 'hasBeenCoding',
  },
  happiness: {
    question: 'Do arrays or objects make you happier? (arrays/objects)',
    answers: {
      arrays: 'I knew it, arrays are my favourite too.',
      objects: "You're good at coding- objects are hard!",
    },
    nextQuestionId: 'timeOfDay',
  },
};
```

**Fortune Telling**

Add questions to our chat bot that are purportedly for fortune telling, but where the bot always provides standard responses that anyone might believe are individualised. For example, the bot might ask "Let me tell your fortune. If you have a birthmark, where is it on your body?" and respond with "You have a great need for other people to like and admire you."

Such statements that people might feel are individualised but can apply to everyone are known as Barnum statements. Read more about the Barnum effect and statements [here](https://en.wikipedia.org/wiki/Barnum_effect#Early_research).

#### Reference Solutions

[Here](https://github.com/rocketacademy/fundamentals-starter-code/blob/day10/script.js) is a reference solution for Day 10 exercises. Please only view the reference solution for each exercise after you have attempted the exercise yourself. Note that there are many ways to implement these solutions and the reference solution is only 1 way.
{% endtab %}
{% endtabs %}

##


# Day 11: Blackjack Redux, DOM

## Peer-Led Code Review (with Debugger)

Review your partner's code as per [Peer-Led Code Review instructions](/course-logistics/course-methodology#peer-review). Once both have a working game, work on [More Comfortable](#more-comfortable) on one person's code.

## Code Review

On days when projects are due, we will review each others' code in groups of 2 or 3 during class. If there is a group of 3, the triplet will do individual code review together so that everyone gets to review someone else's code, then split into 2 groups for pairing.

### Individual Review

#### 0) Push Your Own Code

Refer to the [push section](/8-github/8.2-github-fork-and-clone#git-push) for the commands needed for this.

#### 1) Clone Partner's Code

You'll be paired up so that you can exchange the links for your repos via your community channel. Remember that the forked repo is the one that is under your GitHub account, not Rocket Academy's. If you have forked the repo but haven't pushed your latest code to GitHub, take a moment now to `git push`. Let your partner know you're updating the repo. Run a `git clone <REPO_URL> <NEW_FOLDER_NAME>` to get a copy of your partner's code.

{% hint style="info" %}
Note: You need to rename the folder when you clone if you already have a folder named after the repo where you're making the clone.
{% endhint %}

#### 2) Run Partner's Code

Open the code in the browser and test it. What does it do? If you're not sure what it does look inside `script.js` to see.

#### 3) Read Partner's Code

Read the code:

1. How does it work?
2. Does it have any obvious errors?
3. Does it implement something that you were trying to do?
4. Does it implement a feature that you haven't started yet? How does the code work?

**Code Review Reflection Questions**

While you are reading, note down the answers to the following questions: No need to be comprehensive, but pick out parts of the code you found notable.

1. Note a line of code (or multiple lines) that you think works well. This could be the logic of the code, or just a well-named variable. Explain why it works well.
2. Note a line of code (or multiple lines) that you thought was unclear or you can't figure out. How would you explain why is it unclear or hard to figure out?
3. Note a line of code (or multiple lines) where you found a bug. Why is it a bug? Do you have a solution?

#### 4) Play with Partner's Code

It may be helpful to make changes to the code to help you understand it better. Write some `console.log` that would help you figure out what the code does. Break the code in a certain way to prove how it works or doesn't work.

#### 5) Discuss

Once both partners are done with #1-4, discuss what you saw. Read out and review together the answers to the 3 questions you wrote down from above.

### Peer Review

You'll be pair programming on one person's project at a time. The goal is to get working versions for each person. **The driver will be the person who is \*not\* working on their own code.**

Once done with one person's code, send the code to your pair (it's their project) via a community channel code snippet. Switch to work on the other person's code.

{% hint style="info" %}
Note: If you are working on your partner's code you can't push to their repo because GitHub repos are read-only to non-owners by default.
{% endhint %}

If you both have working versions, implement a new feature in one of the projects together.

## More Comfortable

Implement [More Comfortable exercises](/projects/project-3-blackjack#more-comfortable) in the project writeup. Once done, push your code to update your pull request in GitHub.


# Project 1: Scissors Paper Stone

✂️📃💎😜

## Introduction

For our first project we will make our own version of the classic [Scissors Paper Stone](https://en.wikipedia.org/wiki/Rock_paper_scissors) game. We have split this project into 2 parts to cater to the pace of Rocket's Fundamentals course. See the [Course Schedule](/course-logistics/schedule-and-pairings) for when we have assigned each part.

{% content-ref url="/pages/-MF9iFNXQIqfL1RBTye6" %}
[Project 1: Scissors Paper Stone (Part 1)](/projects/project-1-scissors-paper-stone/project-1-scissors-paper-stone-part-1)
{% endcontent-ref %}

{% content-ref url="/pages/-MYeKoQiM4z1VjFZPPsv" %}
[Project 1: Scissors Paper Stone (Part 2)](/projects/project-1-scissors-paper-stone/project-1-scissors-paper-stone-part-2)
{% endcontent-ref %}


# Project 1: Scissors Paper Stone (Part 1)

✂️📃💎😜

## Introduction

For our first project we will make our own version of the classic [Scissors Paper Stone](https://en.wikipedia.org/wiki/Rock_paper_scissors) game. We have split this project into 2 parts to cater to the pace of Rocket's Fundamentals course. See the [Course Schedule](https://github.com/rocketacademy/basics-docs/blob/main/projects/project-1-scissors-paper-stone/broken-reference/README.md) for when we have assigned each part.

Part 1 works with the technologies we have learnt so far in Fundamentals, and Part 2 adds additional technologies that we learn in subsequent course days.

## Setup

1. Create a `project` directory in your `fundamentals` code folder to host your projects if you haven't already.
2. Make a copy of the [Fundamentals Starter Code](https://github.com/rocketacademy/fundamentals-starter-code/archive/refs/heads/main.zip) for your Scissors Paper Stone project.

## Base

### Basic Scissors Paper Stone

Create a basic version of Scissors Paper Stone where the user inputs one of "scissors", "paper", or "stone", the program internally randomly chooses scissors, paper, or stone, and the program outputs whether the user won, the program won, or it's a draw.

Rules: scissors beats paper, paper beats stone, and stone beats scissors. If both parties choose the same object, it's a draw.

{% hint style="info" %}
Unsure how to start? Try these steps:

1. Write some pseudo code.
   * What is the input going to be?
   * What should the output be?
   * How will the computer's option be randomly generated?
   * How many different cases are there?
2. Draw a simple flowchart to help you visualise the overall control flow of the program.
3. Start small, test while you build and be ready to debug.
   * It's unwise to attempt to build the entire program in one go before testing.
   * Know that the final shape and form of your program will look different from when you are building it.
   * You can write new lines of code within main first, check that the code works as intended, and then "relocate" / refactor your code as a helper function.
   * Utilise `console.log()` sensibly to check for the right [control flow](/3-structuring-and-debugging-code/3.2-errors#control-flow-checking-is-our-code-running) and [values](/3-structuring-and-debugging-code/3.2-errors#value-checking-are-the-values-correct).
   * Try to test as frequently as you can, and whenever you make a significant change. It builds confidence that things are working as they should and you will catch bugs as soon as they pop up.
4. [Refactor ](https://en.wikipedia.org/wiki/Code_refactoring)your code:
   1. Is all of your logic in `main()`? Can more lines of code be in helper functions?
   2. Are there any unwieldy or long helper functions? Should they be sub-routines which call helper functions instead?
   3. Can any of the logic be streamlined?
      {% endhint %}

### Input Validation

Sometimes the user types something other than "scissors", "paper", or "stone" during gameplay. Add [*input validation*](/4-conditional-logic/4.4-input-validation) to check if what the user types is a valid choice, and if not, kindly let the user know that there are only 3 input options, and ask them to try again.

## More Comfortable

### Formatting

Make the output of your game look nice. You can use string `'<br>'` to create [new lines](https://www.w3schools.com/TAGS/tag_br.asp) in the output. Your output might look something like this:

```
The computer chose scissors ✂️.
You chose paper 🗒.

You lose! Bummer.

Now you can type "scissors" "paper" or "stone" to play another round!
```

### Reverse Game

You decide to prank your friends and create an SPS game where the rules are reversed: scissors beat stone, stone beats paper, and paper beats scissors. Create a version where the rules are reversed. The user can choose to try their luck at reversed mode by adding the word "reversed" to their choice. For example: "reversed stone".

## Reference Solution

[View the reference solution ](https://github.com/rocketacademy/basics-scissors-paper-stone/tree/part1-inclMoreComfortable)for SPS-Part1 (up till More Comfortable). Please only refer to the reference solution after you have attempted the project. Note that there are many ways to implement the project and the reference solution is only 1 way.


# Project 1: Scissors Paper Stone (Part 2)

✂️📃💎🤩

## Introduction

Part 2 assumes we have learned about global variables, and the More Comfortable section assumes we know how to use [global varaibles](/5-managing-state-and-input-validation/5.1-program-lifecycle-and-state#global-variables) as game modes. We'll now update our SPS Part 1 to support [game states](/5-managing-state-and-input-validation/5.2-program-state-for-game-modes#global-state-for-app-modes).

If you completed the [Base features of SPS Part 1](/projects/project-1-scissors-paper-stone/project-1-scissors-paper-stone-part-1#base) but didn't finish the More Comfortable section, please complete Base for SPS Part 2 before going back to attempting More Comfortable for both parts.

## Past Projects

Take a look at past projects by previous Fundamentals students to visualise how the full game can look like.

1. [Muk-jji-ppa](https://lim-jiahao.github.io/basics-scissors-paper-stone/)
2. [Regular and Reverse](https://averygan.github.io/basics-scissors-paper-stone/)

## Base

### Win-Loss Record

Add [state](/5-managing-state-and-input-validation/5.1-program-lifecycle-and-state) to your program such that it keeps track of the number of times the user has won and the number of times the computer has won. Output this win-loss record in a format you like in the program output. You can also output the number of draws and/or each party's winning percentage if you'd like.

### User Name

To make this game more personal, add a feature to collect the user's name as the first input after the page loads. We can prompt the user to enter their name first by adding to the page's HTML. Once the user submits their name, the program can return output to prompt the user to start playing Scissors Paper Stone by entering one of the 3 objects. Use the user's name to personalise win-loss record and other relevant output.

### Formatting

Make the output of your game look nice. You can use the string `'<br>'` to create [new lines](https://www.w3schools.com/TAGS/tag_br.asp) in the output. Add the user name and the win/loss record. Format a message depending on how well the player is doing:

```
The computer chose scissors ✂️.
You chose paper 🗒.

You lose! Bummer.

So far Kai, you've been winning 5/7 turns. Pretty good!
```

## More Comfortable

There is no need to implement all the different features sequentially in one version of your game. Feel free to choose what you find interesting and appropriately challenging and implement only that.

### Reverse Game Mode

You decide to prank your friends and create an SPS game mode where the rules are reversed: scissors beat stone, stone beats paper, and paper beats scissors. Create ***a game mode*** where if a user types in "reverse", it reverses the SPS rules.

### Korean Scissors Paper Stone

The following is adapted from [Wikipedia](https://en.wikipedia.org/wiki/Rock_paper_scissors#Adapted_rules):

> In Korea, a two-player upgraded version exists by the name [muk-jji-ppa](https://en.wikipedia.org/wiki/Muk-jji-ppa). After showing their hands, the player with the winning throw shouts "muk-jji-ppa!" upon which both players throw again. If they throw differently (for example, rock and paper, or paper and scissors), whoever wins this second round shouts "muk-jji-ppa!" and thus the play continues until both players throw the same item (for example, rock and rock), at which point whoever was the last winner becomes the actual winner.

Update your program state such that it can keep track of the most recent winner, and update the program logic to declare the most recent winner the ultimate winner when there is a draw.

### Versions

Allow the player to select if they want to play normal or Korean versions of the game.

### Computer vs. Computer

Add a mode that lets the computer choose for you on each turn.

### Further Variations

Implement other variations to the game as described [here](https://en.wikipedia.org/wiki/Rock_paper_scissors#Variations). The user can select which variation they would like to play.

## Submit

Share your work with your Section mates for peer-learning, and with your SLs for review.

1. Go to [gist.github.com](https://gist.github.com) and login with your GitHub account.
2. Copy code from `script.js` into a new gist.
   1. Title the Gist and the file as you wish
   2. Share your Gist on your community channel!
3. Include the following questions, along with your answers, at the top of your gist:

```
/*
How many hours did you spend on this assignment?:

What part of the assignment did you spend the most time on?:

How comfortable did you feel with this assignment? (1-5):

Is there anything in this code that you feel pleased about?:

What's one aspect of your code you would like specific, elaborate feedback on?:

*/
```

![GitHub gist](/files/WJjHdvNZvoV95ijioCQb)

Share the link to your gist with your Section in your community channel!

## Reference Solution

The reference solution implements the Base functionality for both SPS Parts 1 and 2. Please only refer to the reference solution after you have attempted the project. Note that there are many ways to implement the project and the reference solution is only 1 way.

[View the reference solution ](https://github.com/rocketacademy/basics-scissors-paper-stone/tree/part2-inclMoreComfortable)for SPS-Part2 (up till More Comfortable).


# Project 2: Beat That!

## Introduction

Create a version of the Beat That dice game, where players create the largest number they can by concatenating random dice roll digits. Read the rules for Beat That [here](https://www.activityvillage.co.uk/beat-that).

Have a look a some past student's project to visualise the game - and for inspiration :)

1. [Base](https://eggcodes.github.io/basics-beat-that/)
2. [Comfortable](https://averygan.github.io/basics-beat-that/)
3. [Super Comfortable](https://lim-jiahao.github.io/basics-beat-that/)

## Setup

1. Fork and Clone the [Fundamentals *Beat That!* repo](https://github.com/rocketacademy/basics-beat-that).

## Base

### Requirements

1. There are 2 players and players take turns.
2. When a player clicks Submit, the game rolls 2 dice and shows the dice rolls, for example 3 and 6.
3. The player picks the order of the dice they want. For example, if they wanted the number 63, they would specify that the 2nd dice goes first. You can choose how the player specifies dice order.
4. After both players have rolled and chosen dice order, the player with the higher combined number wins.

### Example

Player 1 rolls 2 dice with dice rolls 3 for Dice 1 and 6 for Dice 2.

```
Welcome Player 1.
You rolled 3 for Dice 1 and 6 for Dice 2.
Choose the order of the dice.
```

Player 1 can pick either Dice 1 or Dice 2 as the first numeral of the combined number.

```
Player 1, you chose Dice 2 first.
Your number is 63.
It is now Player 2's turn.
```

Player 1 picked Dice 2 as the 1st numeral and Dice 1 as the 2nd, thus generating the combined number 63. Player 2 then rolls 2 dice and tries to generate a number greater than 63.

## Walkthrough

If you get stuck, or are unsure on how to start, Bryan will walk you through how to go from breaking down the problem to completion of the Base version of Beat That!

{% embed url="<https://www.youtube.com/watch?v=JODUe_H0kmM>" %}

## Comfortable

### Add some polish!

Your game is working as intended, now it's time to make it look good! We'll edit index.html to personalise our game. If needed, review [1.2 Web Browsers](https://fundamentals.rocketacademy.co/1-introduction/1.2-web-browsers) on how to edit HTML.

At line 29 of index.html, try changing `background-color: pink;` to `background-color: lightblue;` or any [colour ](https://www.w3schools.com/colors/colors_names.asp)of your choice!

```css
#container {
  background-color: lightblue;
  margin: 40px auto;
  max-width: 800px;
  padding: 38px 31px;
}
```

Add 1 or more [paragraphs](https://www.w3schools.com/html/html_paragraphs.asp) after line 64 with instructions on how to play Beat That! It can look something like this:

```html
...

<body>
  <h1 id="header">Fundamentals: Beat That! 🚀</h1>
  <div id="container">
    <p>Hello! Welcome to Beat That! Click submit to start the game.</p>
    <p>Create a two-digit number by selecting the order of your dice rolls.</p>
    <p>The player with the highest number wins! Good luck!</p>
    <p>Input:</p>
    <input id="input-field" />
    <br />
    <button id="submit-button">Submit</button>
    <p>Output:</p>
    <div id="output-div"></div>
  </div>

  ...
</body>
```

Having fun making your game look good? Feel free to explore more HTML and CSS on your own! Here are some resources:

* FreeCodeCamp's [basic HTML](https://www.freecodecamp.org/learn/responsive-web-design/#basic-html-and-html5) and basic [CSS tutorials](https://www.freecodecamp.org/learn/responsive-web-design/#basic-css)
* W3School's CSS [Tutorial](https://www.w3schools.com/css/default.asp) and [Reference](https://www.w3schools.com/cssref/default.asp).

## More Comfortable

Try implementing some, or a combination of, the following feature groups. Feel free to include any other additional features you think of.

{% tabs %}
{% tab title="Score" %}
**Score**

Keep score for each player. The score is the running sum of all numbers that player has generated so far. This means there is no permanent winner, only a temporary leader.

**Leaderboard**

When outputting game results in the output box, also output a leaderboard that lists the 2 players and their scores in decreasing order.
{% endtab %}

{% tab title="Lowest Combined" %}
**Lowest Combined Number Mode**

Add a game mode such that the player with the lowest combined number is the winner.

**Auto-Generate Combined Number**

Update the game to auto-generate the highest (or lowest) combined number from dice rolls. For example, for dice rolls `[6, 3]` in Lowest Combined Number mode, the game would auto-generate the combined number `36`.
{% endtab %}

{% tab title="Variable Dice and Players" %}
**Variable Number of Dice**

1. Create a new version of Beat That that rolls two or more dice per player.
2. At the beginning of each round, ask the players how many dice they would like to play with. Both players will roll the same number of dice each round.
3. Store each player's dice rolls in an array. When each player rolls dice, use a loop to place `n` dice roll values in that player's array, where `n` is the number of dice the players specified at the beginning of the round. Output each player's dice roll values.
4. Auto-generate the optimal combined number based on each player's dice rolls to determine the winner of that round.

**Variable Number of Players**

Allow more than 2 players at a time to play Beat That. At the beginning of the game, ask how many players would like to play. For a variable number of players, feel free to output the leaderboard in any order, because implementing the leaderboard in decreasing order requires advanced logic.
{% endtab %}

{% tab title="Knockout" %}
**Knockout Mode**

Create a mode where if there are more than 2 players, the game can match players against each other 1 at a time until there is 1 final winner. For example, if there are 4 players, the game might first match players 1 and 2. If player 1 wins, the game might then match players 1 and 3. The winner of that match would then play player 4, and the winner of that final round would be the ultimate winner.
{% endtab %}
{% endtabs %}

## Submit

1. [Push](/8-github/8.2-github-fork-and-clone#git-push) the commits in your local repo to GitHub.
2. [Create a pull request](/8-github/8.2-github-fork-and-clone#github-pull-request) to submit your assignment.
3. Please leave your name and **section number \_in the title**\_ of the pull request.
4. Please fill in the questionnaire in the pull request comments when you submit.

## Reference Solution

Please only refer to the reference solution after you have attempted the project. Note that there are many ways to implement the project and the reference solution is only 1 way.

1. [Base](https://github.com/rocketacademy/basics-beat-that/blob/base/script.js)
2. [Auto-Generate Combined Number](https://github.com/rocketacademy/basics-beat-that/blob/moreComfortable-autoGenerateCombinedNum/script.js) (includes Score, Leaderboard, and Lowest Combined Number Mode)
3. [Variable Number of Dice](https://github.com/rocketacademy/basics-beat-that/blob/moreComfortable-variableNumDice/script.js)
4. [Variable Number of Players](https://github.com/rocketacademy/basics-beat-that/blob/moreComfortable-variableNumPlayers/script.js)
5. [Knockout mode](https://github.com/rocketacademy/basics-beat-that/blob/moreComfortable-knockout/script.js)


# Project 3: Blackjack

## Introduction

Implement a simplified version of Blackjack. If you're not familiar with Blackjack, refer to [this video](https://www.youtube.com/watch?v=eyoh-Ku9TCI) for game rules. Our simplified rules are the following. Please read all the requirements before starting it!

1. There will be only two players. One human and one computer *(for the Base solution).*
2. The computer will always be the dealer.
3. Each player gets dealt two cards to start.
4. The player goes first, and decides if they want to hit *(draw a card)* or stand *(end their turn).*
5. The dealer has to hit if their hand is below 17.
6. Each players' score is the total of their card ranks. Jacks/Queen/Kings are 10. Aces can be 1 or 11.
7. The player who is closer to, but not above 21 wins the hand.

## Past Projects

Take a look at some past project as references, and student-voted most-creative projects from previous Batches for inspiration :)

{% tabs %}
{% tab title="General" %}

* [Base](https://rocketacademy.github.io/basics-blackjack/)
* [Comfortable 1](https://awongh.github.io/basics-blackjack/index.html)
* [Comfortable 2](https://eggcodes.github.io/basics-blackjack/)
* [Super Comfortable](https://lim-jiahao.github.io/basics-blackjack/)
  {% endtab %}

{% tab title="Fundamentals 11" %}

* [Wall St. Casino](https://supershazwi.github.io/basics-blackjack/)
* [MCU BlackJack](https://aqifsariman.github.io/basics-blackjack/)
* [BlackJack 99](https://liztanyl.github.io/basics-blackjack/)
* [Kawaii BlackJack](https://yingdan7.github.io/basics-blackjack/)
* [Real Cards™ BlackJack](https://waynerbee.github.io/basics-blackjack/)
* [SouthPark Casino](https://ahshawngoh.github.io/basics-blackjack/)
* [Edwin's Casino](https://edwinyxt.github.io/basics-blackjack/)
* [Cheok's Lounge](https://cheoklate.github.io/basics-blackjack/)
* [**来玩·万辣**](https://sherman168.github.io/basics-blackjack/)
  {% endtab %}

{% tab title="Fundamentals 10" %}

* [SouthPark Casino](https://averygan.github.io/basics-blackjack/)
* [Cat-sino](https://thereselyr.github.io/basics-blackjack/)
* [Simple and Green](https://liangtcode.github.io/basics-blackjack/)
* [90's Night](https://yap83.github.io/basics-blackjack/)
  {% endtab %}
  {% endtabs %}

## Setup

Begin by forking the [Coding Fundamentals Blackjack repo](https://github.com/rocketacademy/basics-blackjack). Once forked, clone your fork of the repo and work on that copy.

## Base

### Gameplay Description

The `main` function runs on each player's turn. The sequence of actions in the game might be the following.

1. Deck is shuffled.
2. User clicks Submit to deal cards.
3. The cards are analysed for game winning conditions, e.g. Blackjack.
4. The cards are displayed to the user.
5. The user decides whether to hit or stand, using the submit button to submit their choice.
6. The user's cards are analysed for winning or losing conditions.
7. The computer decides to hit or stand automatically based on game rules.
8. The game either ends or continues.

{% hint style="info" %}
Note that for the `main` function to perform different logic on user input, for example when a player decides to hit or stand, we may wish to consider using a new game mode.
{% endhint %}

### General Tips

1. Creating helper functions can be a powerful way to refactor your code and keep it neat.
2. Don't be afraid to throw away code, especially if you already know how you would write it better.
3. Commit your code often, whenever you have a small working version. For example, each action listed above would be a commit. Make concise and precise commit messages so that you can reference your old changes later.
4. Review [Coding Strategies](/course-logistics/tips-and-tricks/coding-strategies)

### How to Prioritise Work

Given the above \*final\* action sequence to play a full game, how do we break these down into sub-features that we can work on (and verify they are working) one at a time? We want to work on features in small parts, but not have to redo any work as we expand the capability of the game, so we want to plan ahead to make sure we can start small and scaffold in the later features at the same time.

If you already have an effective strategy for creating your game, you can skip ahead. If you're not sure how to approach the game, try applying the following strategies to get started. The following are strategies for breaking down larger projects into smaller tasks to keep up progress, momentum, and motivation on the project. Please read to the end before starting.

#### First Version: Compare Initial Hands to Determine Winner

1. Aim for a playable game. The essence of blackjack requires:
   1. Two players - a player and a dealer *(computer).*
   2. A deck of cards.
   3. A starting hand of 2 cards for each player.
   4. Comparing both hands and determining a winner. The possible scenarios are:
      * A tie. When both the player and dealer have the same total hand values - or if both draw Blackjack
      * A Blackjack win. When either player or dealer draw Blackjack.
      * A normal win. When neither draw Blackjack, the winner is decided by whomever has the higher hand total.
2. Return appropriate messages. For example:

   ```markdown
   Player hand: Ace of Hearts, King of Spades
   Dealer hand: 8 of Clubs, 8 of Spades
   Player wins by black jack!
   ```
3. Test your code.

#### Second Version: Add Player Hit or Stand

1. The player hitting or standing is different from the dealer hitting or standing. The rules state that the dealer hits or stands after all players are done, so let's work on the players hitting or standing first.
2. The player hitting or standing is a new mode in the game that allows the player to enter their choice. Add the logic for when the player busts *(has a total score of >21)*.
3. Refactor your logic to wait until the player is done to evaluate the game-winning condition.
   * The player should not immediately lose if he busts - there is a possibility he will tie with the dealer if the dealer also busts.
4. Test your code.

#### Third Version: Add Dealer Hit or Stand

1. The rules state that the dealer hits after the player is done. After the player confirms they are done, add the logic for the dealer adding cards to their hand. This should happen before the winning condition.
2. Test your code.

#### Fourth Version: Add Variable Ace Values

1. Add logic to determine whether Aces should have value of 1 or 11 for a given hand.
   * For example, if a player draws cards in the following order:

     1. "Ace" and "2" *(total 13)*
     2. "4" *(total 17)*
     3. "Ace". *(total 18)*

     The total hand value should be 18, as only ONE of the aces will be counted as 11.
2. Test your code.

## Walkthrough

If you are still unsure how to start, or find yourself stuck for too long, Bryan can walk you through how to get to the Base solution. Please try to attempt the project once yourself before referencing the walkthrough, and do note that the video uses template code straight from [10.2: Card Deck Generation](/9-javascript-objects/9.2-card-deck-generation-with-loops). If you would like to follow along exactly, you can start with the [base code](https://github.com/rocketacademy/basics-blackjack/tree/walkthrough-base) used in the walkthrough.

{% embed url="<https://www.youtube.com/watch?v=SccCe9_qU2Q>" %}
Blackjack Base Walkthrough
{% endembed %}

The completed base version as per the walkthrough can be viewed [here](https://github.com/rocketacademy/basics-blackjack/blob/walkthrough-base/script.js)!

## Comfortable

### Interface

Improve the look and feel of your game - if you did not attempt the Comfortable version of *Beat That!,* you can use the[ instructions there](/projects/project-2-beat-that#comfortable) as a quick-start guide. If you have, feel free to move on, and add your own creative touches.

#### User Instructions

Make the game intuitive and fun to use by adding explicit instructions for each step of the game. "*Wow, you're at 14 right now! Do you want to hit or stand? Type h for hit or s for stand.*"

#### Starting Instructions

Add instructions on how to start the game by editing the `index.html`.\
\
Simply add your instructions into [line 134](https://github.com/rocketacademy/basics-blackjack/blob/main/index.html#L134). These instructions will appear when the game loads and will be erased as soon as the user clicks the submit button.

```javascript
<div id="output-div">
  Welcome to Kai's Cards! Click the submit button to get started!
</div>
```

#### Emoji

Use emoji for the card suits ♣️♠️♦️♥️and for the card names 2️⃣. Use more emoji in your game instructions and results. Get creative!

#### Images

You can add images to your game by including an HTML image tag in `myOutputValue`.

```javascript
var myImage = '<img src="https://c.tenor.com/Hj2-u4VELREAAAAi/655.gif"/>';
myOutputValue = myOutputValue + myImage; // will display an image in the grey box
```

Image variable template: Fill in the `COPIED_URL_OF_IMAGE` with any image URL you find.

```javascript
var myImage = '<img src="COPIED_URL_OF_IMAGE"/>';
```

#### Using images

1. Go to a site like [tenor.com](https://tenor.com) for gifs (although *any* website with images will work)
2. Right-click on an image and copy the url by selecting "Copy Image Address".
3. Paste this value into your code as shown above.

![How to Copy a website Image Address](/files/-MjFEDygfWqYFR0zSKrw)

#### Using your own images

Place an image file in your Git repository. Commit the image file and push your image to your GitHub repository.

For example you added an image called `my-image.jpeg` into your repository directory. Refer to it like the following:

```javascript
var myImage = '<img src="/my-image.jpeg" />';
myOutputValue = myOutputValue + myImage; // will display an image in the grey box
```

Image variable template: Fill in the `COPIED_RELATIVE_IMAGE_PATH` with the image file name you uploaded to your repo.

```javascript
var myImage = '<img src="/COPIED_RELATIVE_IMAGE_PATH"/>';
```

#### Colors

Set your own custom colors in the CSS. Find the color values in `index.html` and change them. Use this tool to find the colors you want: <https://www.w3schools.com/colors/colors_picker.asp>

Find matching color sets using this design tool: <https://color.adobe.com/create/color-wheel>

#### Fonts

Set your own custom fonts: <https://www.w3schools.com/css/css_font_google.asp>

## More Comfortable

### Hide Dealer's First Card

In most casinos, all cards are face-up except the dealer's first card. This injects a dimension of strategy into the game, as the player does not have perfect information to begin with. Edit your game logic such that the player is only told one of the dealer's first two cards.

### Additional HTML Elements

Look ahead to [12.1 Browser Application with DOM](/10-advanced/10.3-browser-applications-with-dom) to see how additional HTML elements can be referenced and manipulated; add a button for 'Hit' and 'Stand'.

### Additional Game Logic

Try adding one or more additional game features *(you can also have different versions with different features if implementing all features in one version is too complicated)*:

#### Betting

The player starts with 100 points. Each round the player wagers a number of points before their hand is dealt. Keep track of the player's points throughout the game.

#### Multiplayer

Enable multiple players to play against the dealer, where players can take turns. The game hides and shows relevant hand according to the turn.

#### Splits

Add hand-splitting functionality to the game. If the player has two of the same kind of card, they can choose to split and get dealt 2 new cards. Full splitting rules [here](https://en.wikipedia.org/wiki/Aces_and_eights_\(blackjack\)#Splitting). Dealer is not allowed to split.

## Submit

1. [Push](/8-github/8.2-github-fork-and-clone#git-push) the commits in your local repo to GitHub.
2. [Create a pull request](/8-github/8.2-github-fork-and-clone#github-pull-request) to submit your assignment.
3. Please leave your name and ***section number*** in the ***title*** of the pull request.
4. Please fill in the questionnaire in the pull request comments when you submit.

## Sharing

The cloned BlackJack repo has built-in sharing code. When you share your project with friends on major platforms it will have a nice looking share image.

![Twitter Sharing Example](/files/-MjF9jjfe9HGsVjB3hhN)

### Setting the Share Link

Edit the index.html to match the GitHub Pages URL you created in the instructions above.

To have your share link properly link to your page, find your GitHub Pages URL:

![](/files/-MkQX0w7km5VzVOfh4Nx)

Replace the url in the URL section of the meta tags in index.html:

Facebook Share URL: line [30](https://github.com/rocketacademy/basics-blackjack/blob/main/index.html#L30)

```
<meta property="og:url" content="<PUT YOUR URL HERE>index.html">
```

Twitter Share URL: line [37](https://github.com/rocketacademy/basics-blackjack/blob/main/index.html#L37)

```
<meta name="twitter:url" content="<PUT YOUR URL HERE>index.html">
```

#### Sharing text: Put your name and some fun text in the share!

For Facebook / Slack / Whatsapp / Discord / Disco LMS Shares: edit lines [31 & 32](https://github.com/rocketacademy/basics-blackjack/blob/main/index.html#L31-L32) in the index.html

```
<meta property="og:title" content="YOURNAME's BlackJack Game!">
<meta property="og:description" content="A fun card game I made myself! 😄💪🌈">
```

For Twitter Shares: edit lines [38-42](https://github.com/rocketacademy/basics-blackjack/blob/main/index.html#L38-L42) in the index.html

```
<meta name="twitter:title" content="YOURNAME's BlackJack Game!">
<meta name="twitter:description" content="A fun card game I made myself! 😄💪🌈">
<meta name="twitter:image" content="https://ra-web-files.s3.ap-southeast-1.amazonaws.com/basics/basics-blackjack-share-small.jpeg">
<meta name="twitter:site" content="@rocketacademyco">
<meta name="twitter:creator" content="@rocketacademyco">
```

## Reference Solution

Please only refer to the reference solution after you have attempted the project. Note that there are many ways to implement the project and the reference solution is only 1 way.

1. [Base](https://github.com/rocketacademy/basics-blackjack/tree/base)
2. [Multiplayer](https://github.com/rocketacademy/basics-blackjack/tree/moreComfortable-Multiplayer)

{% hint style="danger" %}
**Rocket Academy does not endorse gambling.** We chose Blackjack as a project because of its complex rules that help facilitate coding instruction.
{% endhint %}


# Drawing With Emojis

Use loops to create an app that draws emojis into the grey box.

Begin the app by **forking** this repo: <https://github.com/rocketacademy/basics-drawing>

## Number of Characters

The user will enter a number of characters to display on the screen.

For example, if the user enters 4 they will see this:

![](/files/-MFaZY2jQ-gtQN6dSzMR)

## Square

The user will enter the dimensions of a square to display on the screen.

Use a loop within a loop and the `<br>` newline HTML tag in your output to create the square.

For example, if the user enters 4 they will see this:

![](/files/-MFaZs6SHcL2uPWDNwFt)

## Triangle

The user will enter the dimensions of a triangle to display on the screen.‌

Use a loop within a loop, a conditional and the `<br>` newline HTML tag in your output to create the triangle.

For example, if the user enters 4 they will see this:

![](/files/-MFa_4dzFATYUaHIUhSP)

## Modes

Add modes to the program so that the user can create any shape- first the user will enter the shape they want, (this is a shape entering mode), e.g., square, triangle, etc. Then the user will enter the dimensions they want.

## More Comfortable

### Upside down Triangle

The user will enter the dimensions of a triangle to display on the screen.

For example, if the user enters 4 they will see this:

![](/files/-MFaaQkNGCzVB_cxvIJN)

### Outline Square

The user will enter the dimensions of a square to display on the screen. The square is outlined by a different character.

For example, if the user enters 4 they will see this:

![](/files/-MFaaeuGuRVPdtE7JTPc)

### Center Square

The user will enter the dimensions of a square to display on the screen. The square is outlined by a different character and there is another different character in the center. The app doesn't allow dimensions that will not allow the center character.

For example, if the user enters 5 they will see this:

![](/files/-MFab4_PWJVownX9ljUx)

### Rings

The user will enter the dimensions of a square to display on the screen. The characters in the square alternate, creating concentric rings.

## Submit

[Push](/8-github/8.2-github-fork-and-clone#git-push) the commits in your local repo to GitHub. [Create a pull request](/8-github/8.2-github-fork-and-clone#github-pull-request) to submit your assignment. Please fill in the questionnaire in the pull request comments when you submit.

## Reference Solution

Please find a reference solution [here](https://github.com/rocketacademy/basics-drawing/pull/9/files). Note that there are many ways to code solutions to these problems and the reference solution is only 1 way.


# Guess the Word

This is a game where the player must guess a secret word.‌

Begin the app by **forking** this repo: <https://github.com/rocketacademy/basics-guess-the-word>​‌

For each wrong guess the program adds to the figure: (凸 ಠ 益 ಠ)凸 ‌

The player can only guess wrong 7 times before the game ends. (the number of characters in the figure)‌

Before you start read through the advice on how to start and the more comfortable sections to see what the basic and advanced versions of the game include.‌

## How to Start <a href="#how-to-start" id="how-to-start"></a>

The first version of this game you can have a single, hard-coded secret word- `cat`.‌

The data structure you need to represent the game that guesses each individual letter in a word is an array of individual letters.‌

This will allow you to guess letters and find each letter guessed and the position of those letters in the word.‌

A word array would look like this: `var word = ['c','a','t'];`.‌

### Game Play <a href="#game-play" id="game-play"></a>

When the user guesses a letter, you have to have the program look through the word array and determine if the user guessed correctly. "Looking through" means looping over the word array and comparing it to the letter the user has inputted.

When the user guesses there are two possibilities:‌

1. The user guesses incorrectly. Add a character to the figure that marks when they lose the game.
2. The user guesses correctly, add the letter to the word they are trying to complete.

(In the first version you can just do basic output like how many guesses the user has left, and how many letters they have correct.)‌

After verifying the user guess, check for the state of the entire game:‌

If the user has guessed all the letters in the word, tell them they have won.‌

If the user has completed the figure tell them they lost.‌

## More Comfortable <a href="#more-comfortable" id="more-comfortable"></a>

### Output Formatting <a href="#output-formatting" id="output-formatting"></a>

When the user types a correct guess show the correct guess in the location of the secret word. Show the number of letters in the secret word.‌

### Easier / Harder Mode <a href="#easier-harder-mode" id="easier-harder-mode"></a>

Add different modes to the game. Change the secret word to a word with the same letter more than once.‌

The easy mode is when the word is like "guess" and the user guesses 's', then the game fills in both 's'.‌

The hard mode is where the user has to guess each letter.‌

### Name <a href="#name" id="name"></a>

Let the user enter their name at the beginning of the game.‌

### More words <a href="#more-words" id="more-words"></a>

Add a list of words to the game. When it starts the game selects one random word.‌

### Continue Play <a href="#continue-play" id="continue-play"></a>

When the user has played one game with one word, allow them to continue playing with another word.‌

## Reference Solution <a href="#reference-solution" id="reference-solution"></a>

Please only refer to the reference solution after you have attempted the project. Thank you!‌

Note that there are many ways to implement the project and the reference solution is only 1 way.‌

​<https://github.com/rocketacademy/basics-guess-the-word/pull/5/files>​


