JavaScript Fundamentals
5. Variables
Variables allow us to store values.
Modern JavaScript mainly uses let and const.
let score = 10;
const name = "Daffa";
Use const when the variable should not be reassigned.
const name = "Daffa";
Use let when the value needs to change.
let score = 0;
score = 10;
score = 20;
For beginners, a simple rule is:
Use
constby default. Useletwhen you know the value needs to change.
6. Basic Data Types
JavaScript has several basic types of values.
String
A string represents text.
const name = "Daffa";
Number
A number represents numeric values.
const age = 20;
const price = 15000;
Boolean
A boolean represents either true or false.
const isStudent = true;
These values are commonly used together when writing program logic.
7. Operators
JavaScript supports common mathematical operators.
10 + 5
10 - 5
10 * 5
10 / 5
There are also comparison operators:
10 > 5
10 < 5
10 >= 5
10 <= 5
10 === 10
10 !== 5
The result of a comparison is a boolean:
10 > 5
returns:
true
while:
10 < 5
returns:
false
These comparisons become especially useful with if statements.
8. Conditions
An if statement allows JavaScript to make decisions.
const score = 80;
if (score >= 50) {
console.log("Pass");
}
We can add another case with else.
const score = 40;
if (score >= 50) {
console.log("Pass");
} else {
console.log("Fail");
}
We can also check multiple conditions:
const score = 80;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else {
console.log("D");
}
This is the basic mechanism we will use to build the game later.
9. Getting User Input
The browser provides a simple function called prompt().
const choice = prompt("Choose rock, paper, or scissors:");
The browser will display an input dialog.
Whatever the user enters is returned by prompt().
For example, if the user enters:
rock
then:
choice
contains:
rock
We can then use that value in our program.
For example:
const name = prompt("What is your name?");
alert("Hello, " + name);
If the user enters Daffa, the browser displays:
Hello, Daffa