JS Notes (2) EN

emmelinexu

Emmmeline

Posted on April 10, 2024

JS Notes (2) EN

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.
<script>
// JS code goes here
</script>
Enter fullscreen mode Exit fullscreen mode

1. Add [variables] to store data

  • Variables are declared with let
let randomNumber = Math.floor(Math.random() * 100) + 1;
Enter fullscreen mode Exit fullscreen mode
  • Constants are declared with const
const guesses = document.querySelector(".guesses");
Enter fullscreen mode Exit fullscreen mode
  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:

let myName = "Chris";
let myName = "Bob";
Enter fullscreen mode Exit fullscreen mode

This won't cause an error:

var myName = "Chris";
var myName = "Bob";
Enter fullscreen mode Exit fullscreen mode

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

let myName = "Chris";
myName = "Bob";
Enter fullscreen mode Exit fullscreen mode

1.1 Variable naming conventions:

//good
age
myAge
init
initialColor
finalOutputValue
audio1
audio2

// not good
1
a
_12
myage
MYAGE
var
Document
skjfndskjfnbdskjfb
thisisareallylongstupidvariablenameman
Enter fullscreen mode Exit fullscreen mode

1.2 Variable types

//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;
Enter fullscreen mode Exit fullscreen mode

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.
function checkGuess() {
  alert("I am a placeholder");
}
Enter fullscreen mode Exit fullscreen mode

3. Operators

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

//Comparison operators
=== --> 5 === 2 + 4 // false
!== --> 5!== 2 + 4 // true
<
>
Enter fullscreen mode Exit fullscreen mode

4. Comments

// this is a comment

/*
these are comments
1
2
*/
Enter fullscreen mode Exit fullscreen mode

5. Conditional Statements

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);
}
Enter fullscreen mode Exit fullscreen mode

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.
  2. Events are things that happen in the browser, like clicking a button, loading a page, or playing a video.
  3. We can call code in response to events.
  4. The structure that listens for events to happen is called an Event Listener.
  5. The code that runs in response to an event trigger is called an Event Handler.
guessSubmit.addEventListener("click", checkGuess);
Enter fullscreen mode Exit fullscreen mode

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

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);
}
Enter fullscreen mode Exit fullscreen mode
  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

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;
}
Enter fullscreen mode Exit fullscreen mode

7. Loops

Example 1

const fruits = ["apples", "bananas", "cherries"];
for (const fruit of fruits) {
  console.log(fruit);
}
Enter fullscreen mode Exit fullscreen mode
  1. for (const fruit of fruits) means:
  2. Get the first element from fruits.
  3. Set the fruit variable to that element, then run the code between {}.
  4. Get the next element from fruits, then repeat step 2 until the end of fruits.

Example 2

const resetParas = document.querySelectorAll(".resultParas p");
for (const resetPara of resetParas) {
  resetPara.textContent = "";
}
Enter fullscreen mode Exit fullscreen mode

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:

guessField.focus();
Enter fullscreen mode Exit fullscreen mode
  • 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).

+= --> x = x + 4
-= --> x = x - 3
*= --> x = x * 3
/= --> x /= 5 --> x = x / 5
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
emmelinexu
Emmmeline

Posted on April 10, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related