BucksWeb.org JS CheatSheet

Before You Start

Open the Console
Windows / Chromebook: press F12 or Ctrl+Shift+J. Mac: Cmd+Option+J.
console.log() shows up in the Console, not on the page.
These examples build on each other
Make a variable with let only once. To change it later, leave off the let.

Variables & Strings

Make a String (text) variable
let name = "olivia";
Make a Number variable
let age = 20;
Update a variable
age = 30;
Make a variable that never changes
const school = "BCTHS";
Concatenate Two Strings
let firstName = "ash";
let lastName = "ketchum";
let fullName = firstName + " " + lastName;

//This should output "ash ketchum"
console.log(fullName);

Input / Output

Output to the Console
console.log("hello world!");
Create a Pop-up Box (Alert) These can get spammy, use sparingly.
alert("hello world!");
Ask the User (Prompt)
let color = prompt("What is your favorite color?");
console.log("You picked " + color);
Put JS on a Page
In your HTML, put this right before </body>:
<p id="demo"></p>
<script>
  document.getElementById("demo").textContent = "Hello from JavaScript!";
</script>

Loops

Basic While Loop
while (age < 40) {
    //If age doesn't change, you're in an infinite loop!
    age = age + 1;
    console.log(age);
}
Basic For Loop
for (let i = 0; i < 40; i++) {
    //i will start at 0 and "increment" by 1 each loop!
    //This prints 0, 1, 2 ... 39
    console.log(i);
}

Basic Conditionals (IF Statements)

Basic If Statement
if (age > 40) {
    console.log("You're old!");
}
Basic If ... Else Statement
if (age < 40) {
    console.log("You're young!");
} else {
    console.log("You're old!");
}
Else If Statement
if (age < 5) {
    console.log("You're a baby!");
} else if (age < 18) {
    console.log("You're a minor!");
} else {
    console.log("You're an Adult!");
}
Equal
Use three equal signs. "20" == 20 is true, "20" === 20 is false.
if (age === 20) { /* your code here */ }
Less Than
if (age < 20) { /* your code here */ }
Greater Than
if (age > 20) { /* your code here */ }
NOT Equal
if (age !== 20) { /* your code here */ }
Less than OR Equal To
if (age <= 20) { /* your code here */ }
Greater than OR Equal To
if (age >= 20) { /* your code here */ }
OR
if (age === 20 || age === 30) { /* your code here */ }
AND
if (age === 20 && name === 'olivia') { /* your code here */ }

Common Errors

ReferenceError: x is not defined
A typo in a variable name, or you used it before making it. Check the spelling (and capitals!).
SyntaxError: Unexpected token
A missing or extra ( ) { } " or ;. Look at the line number in the Console.
SyntaxError: Identifier 'age' has already been declared
You wrote let age twice. Leave off the let the second time.
TypeError: ... is not a function
A typo in a command, like console.Log instead of console.log.