JS Notes (2) EN
Published: 2024-04-10 05:57:45


# JavaScript Syntax

- After getting a programming task, you can break it down and list out the steps.
- JavaScript code is added inside the `<script>` element at the bottom of the HTML.

```html
<script>
// JS code goes here
</script>
```

## 1. Add [variables] to store data

- Variables are declared with `let`

```jsx
let randomNumber = Math.floor(Math.random() * 100) + 1;
```

- Constants are declared with `const`

```jsx
const guesses = document.querySelector(".guesses");
```

1. Remember to add semicolons
2. `let` vs `var`:
Both `let` and `var` can be used to declare variables. `var` was introduced earlier than `let`. It's recommended to use `let` more often because:

This will cause an error:

```jsx
let myName = "Chris";
let myName = "Bob";
```

This won't cause an error:

```jsx
var myName = "Chris";
var myName = "Bob";
```

But this will lead to confusion in management. The correct way:

```jsx
let myName = "Chris";
myName = "Bob";
```

### 1.1 Variable naming conventions:

```jsx
//good
age
myAge
init
initialColor
finalOutputValue
audio1
audio2

// not good
1
a
_12
myage
MYAGE
var
Document
skjfndskjfnbdskjfb
thisisareallylongstupidvariablenameman
```

### 1.2 Variable types

```jsx
//Number
let myAge = 17;

// String
let dolphinGoodbye = "So long and thanks for all the fish";

//Boolean
let iAmAlive = true;
let test = 6 < 3;

//Array
let myNameArray = ["Chris", "Bob", "Jim"];
let myNumberArray = [10, 15, 40];

myNameArray[0]; // should return 'Chris'
myNumberArray[2]; // should return 40

//Object
let dog = { name: "Spot", breed: "Dalmatian" };
dog.name;
```

Unlike Java or C, JavaScript is a dynamic language. This means you don't need to specify what type of data a variable will contain (e.g., number or string). For instance, if you declare a variable and give it a quoted value, the browser will know it's a string.

## 2. Function

- Functions are useful because once you write them, you can run them repeatedly, saving a lot of repetitive code.

```jsx
function checkGuess() {
  alert("I am a placeholder");
}
```

## 3. Operators

```jsx
+ --> 6+9
- --> 20 - 15
* --> 3 * 7
/ --> 10 / 5

//Comparison operators
=== --> 5 === 2 + 4 // false
!== --> 5!== 2 + 4 // true
<
>
```

## 4. Comments

```jsx
// this is a comment

/*
these are comments
1
2
*/
```

## 5. Conditional Statements

```jsx
let randomNumber = Math.floor(Math.random() * 100) + 1;

const guesses = document.querySelector(".guesses");
const lastResult = document.querySelector(".lastResult");
const lowOrHi = document.querySelector(".lowOrHi");

const guessSubmit = document.querySelector(".guessSubmit");
const guessField = document.querySelector(".guessField");

let guessCount = 1;
let resetButton;
guessField.focus();

function checkGuess() {
/* claim userGuess var 
1. set the userGuess var as the value get from the input
2. use Number() to check it is a number
3. as we did not change the value of the var, we set it as `const`
*/
  const userGuess = Number(guessField.value);
  if (guessCount === 1) {
    guesses.textContent = "Previous guesses: ";
  }
  // add useGuess to the end oof guesses paragram, add a blankbetween two values
  guesses.textContent += `${userGuess} `;

  if (userGuess === randomNumber) {
    lastResult.textContent = "Congratulations! You got it right!";
    lastResult.style.backgroundColor = "green";
    lowOrHi.textContent = "";
    setGameOver();
  } else if (guessCount === 10) {
    lastResult.textContent = "!!!GAME OVER!!!";
    lowOrHi.textContent = "";
    setGameOver();
  } else {
    lastResult.textContent = "Wrong!";
    lastResult.style.backgroundColor = "red";
    if (userGuess < randomNumber) {
      lowOrHi.textContent = "Last guess was too low!";
    } else if (userGuess > randomNumber) {
      lowOrHi.textContent = "Last guess was too high!";
    }
  }

  guessCount++;
  guessField.value = "";
  guessField.focus();
}

guessSubmit.addEventListener("click", checkGuess);

function setGameOver() {
  guessField.disabled = true;
  guessSubmit.disabled = true;
  resetButton = document.createElement("button");
  resetButton.textContent = "Start new game";
  document.body.append(resetButton);
  resetButton.addEventListener("click", resetGame);
}
```

## 6. Events

1. Writing a function alone without calling it won't make anything happen. We want to call it when the button is clicked, so we need to use events.
- Events are things that happen in the browser, like clicking a button, loading a page, or playing a video.
- We can call code in response to events.
- The structure that listens for events to happen is called an Event Listener.
- The code that runs in response to an event trigger is called an Event Handler.

```jsx
guessSubmit.addEventListener("click", checkGuess);
```

The above code needs to be noted:

- The `addEventListener()` method takes two arguments (values to input):

1) The type of event to listen for (here it's `click`)

2) The code we want to execute when the event happens (here it's `checkGuess()`)

3) Note that `addEventListener()` has parentheses, but the `checkGuess` function does not have parentheses.

### About the follow-up of this program

### 1. Prevent the game from continuing

```jsx
function setGameOver() {
  guessField.disabled = true;
  guessSubmit.disabled = true;
  resetButton = document.createElement("button");
  resetButton.textContent = "Start new game";
  document.body.append(resetButton);
  resetButton.addEventListener("click", resetGame);
}
```

1. The first two lines disable user input and submission, so after the game ends, the user won't be able to input more values.
2. Reset for a new round of the game.

### 2. Reset the game

```jsx
function resetGame() {
  guessCount = 1;
// select all the text from paragraphs, and delete them by iterating them and replacing them with a blank
  const resetParas = document.querySelectorAll(".resultParas p");
  for (const resetPara of resetParas) {
    resetPara.textContent = "";
  }

// delete reset button
  resetButton.parentNode.removeChild(resetButton);

  guessField.disabled = false;
  guessSubmit.disabled = false;
  guessField.value = "";
  guessField.focus();
// delete background color
  lastResult.style.backgroundColor = "white";
// generate a random number
  randomNumber = Math.floor(Math.random() * 100) + 1;
}
```

## 7. Loops

### Example 1

```jsx
const fruits = ["apples", "bananas", "cherries"];
for (const fruit of fruits) {
  console.log(fruit);
}
```

1. `for (const fruit of fruits)` means:
- Get the first element from `fruits`.
- Set the `fruit` variable to that element, then run the code between `{}`.
- Get the next element from `fruits`, then repeat step 2 until the end of `fruits`.

### Example 2

```jsx
const resetParas = document.querySelectorAll(".resultParas p");
for (const resetPara of resetParas) {
  resetPara.textContent = "";
}
```

This code creates a variable containing all the paragraphs inside `<div class="resultParas">` using the `[querySelectorAll()](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll)` method, and then iterates through them, deleting the text content of each paragraph.

Note that even though `resetParas` is a constant, we can still change its internal properties, such as `textContent`.

## 8. Objects

### 8.1 Provide a better user experience:

Add the following line below `let resetButton;` (at the top of the script), then save the file:

```jsx
guessField.focus();
```

- The `focus()` method automatically places the cursor inside the `<input>` field when the page loads, meaning the player can immediately start their first guess without having to click the input field.

### 8.3 Important understanding of Objects

Everything in JavaScript is an object. An object is a collection of related functionality stored in a single grouping.

## 9. Basic Math in JavaScript

Unlike other programming languages, JavaScript only uses one data type: Number (which includes integers and decimals).

```jsx
+= --> x = x + 4
-= --> x = x - 3
*= --> x = x * 3
/= --> x /= 5 --> x = x / 5
```

## 10. Strings in JavaScript

In JavaScript, you can choose from single quotes (`'`), double quotes (`"`), or backticks (`` ` ```) to wrap strings.

```jsx
const single = 'single quotes';
const double = "double quotes";
const backtick = `backtick`;

console.log(single);
console.log(double);
console.log(backtick);
```

### 10.1 Single quotes and double quotes

Strings declared with single quotes and double quotes are the same.

### 10.2 Backticks `` ` ``

Backticks are a special type of string called a template literal. In most cases, template literals are similar to regular strings, but they have some special properties:

- We can embed JavaScript inside them.
- We can declare multi-line template literals.

### 10.2.1 Embedding JavaScript & Declaring multi-line template literals

Inside a template literal, you can wrap JavaScript variables or expressions inside `${}`, and their results will be embedded in the string:

```jsx
const name = 'Chris';
const greeting = `hello, ${name}`;
console.log(greeting);
```

```jsx
const one = 'Hello';
const two = "How are you?";
const joined = "${one}${two}";

console.log(joined);
```

Joining strings like this is called concatenation.