Skip to content

JavaScript for a Scratcher

Sean edited this page Feb 16, 2019 · 4 revisions

JavaScript for a Scratcher (more specifically my brother)

basics

// this is a comment; you can use it to explain your code

/*
this type of comment works across multiple lines

sheep
*/

console.log('posts stuff into the console; no one can see it but you though');

alert('displays stuff in a pop-up; kind of annoying though');

JavaScript usually doesn't care if you forget a semicolon, but you should use them just in case.

Numbers and maths

console.log(1);
console.log(1 + 1); // 2
console.log(1 - 1); // 0
console.log(2 * 3); // 6
console.log(10 / 4); // 2.5

// order of operations (PEMDAS) applies
console.log(1 + 2 * 3); // 7 (distinctly NOT 9)

// remainder of dividing 10 by 4 (called "modulo")
console.log(10 % 4); // 2
// in terms of order of operations, it's done with multiplication and division

console.log(1 / 0); // Infinity
console.log(0 / 0); // NaN
// JavaScript doesn't care about division by zero errors, which can actually get rather troublesome. Be careful!

console.log(Math.sqrt(2)); // 1.4142135623730951
console.log(Math.floor(Math.PI)); // 3
console.log(Math.ceil(Math.PI)); // 4

console.log(Math.random()); // a random number from 0 to 1, including 0 but not including 1
console.log(Math.floor(Math.random() * 100)); // a random integer from 0 to 99

variables

Variable names can use letters, numbers, underscores, dashes, and dollar signs. You can probably also use other characters that aren't on your keyboard like Chinese, but why? Variable names can't start with a digit.

let variable; // making a new variable
// you can only make a variable once

variable = 'something'; // setting a variable

console.log(variable); // using a variable's value

variable = 2;
console.log(variable); // 2
variable = variable + 1;
console.log(variable); // 3
variable++; // same as doing variable = variable + 1
console.log(variable); // 4

variable--; // same as doing variable = variable - 1
// there is no such thing as variable**

variable = 0;
console.log(variable); // 0
variable += 0.1; // same as doing variable = variable + 0.1
console.log(variable); // 0.1
variable += 0.1;
console.log(variable); // 0.2
variable += 0.1;
console.log(variable); // 0.30000000000000004
// because numbers are stored in binary, decimals get all funky when you try to do exact maths with them
// this happens on Scratch as well
// this will annoy you one day
// be careful!

variable -= 3;
variable *= 6;
variable /= 1.2;

lists

Arrays start at 0, so the first item would be array[0], second is array[1], and so on.

let array = []; // a new, empty array
array.push(1); // add new item to array
console.log(array[0]); // 1

let arr2 = [1, 2, 3, 4, 5]; // you can put items in the array from the start
arr2.splice(2, 1); // deletes 1 item at position 2 (third item)
console.log(arr2); // [1, 2, 4, 5]
arr2.splice(2, 0, 'new item'); // inserts new item at position 2
console.log(arr2); // [1, 2, 'new item', 4, 5]

console.log(arr2.length); // 5
console.log(arr2.includes(2)); // true
console.log(arr2.indexOf(2)); // 1
console.log(arr2.indexOf(3456)); // -1

.indexOf() returns the position of the first occurence of an item in an array. It returns -1 if the array doesn't have the item.

strings

Strings are like arrays of characters.

let str = 'sheep';
console.log(str); // 'sheep'
console.log(str.length); // 5
console.log(str[1]); // 'h'
console.log(str[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]); // 's'

.slice(a, b) takes a portion of the string from position a up to before position b so that it includes the character at position a but not position b.

console.log(str.slice(1, 3)); // he

You can "add" strings together like this:

console.log('string' + 'sheep'); // 'stringsheep'

Be careful! If you try to add two numbers but one of them happens to be a string...

console.log(1 + '1'); // 11

You can convert strings to numbers like this:

console.log(+'1'); // 1

if _ then _, if _ then _ else _

if (condition) {
  code1
}

if (condition) {
  code1
} else {
  code2
}

if (cond1) {
  code1
} else if (cond2) {
  code2
} else if (cond3) {
  code3
} else {
  code4
}

logic

let a = 3, b = 4;
console.log(a < b); // true
console.log(a > 3); // false
console.log(a >= 3); // true
console.log(4 === b); // true
console.log(2 !== a); // true

let c = true, d = false;

// or operator - only one of the two has to be true
console.log(c || d); // true

// and operator - both have to be true
console.log(c && d); // false

// not operator
console.log(!c); // false

// order of operations, PEMDAS, then equation/comparison signs, then and, then or
console.log(3 + 3 * 2 > 1 || 2 - 4 <= 6 / (2 + 2)); // true

Be careful that you do === not = when checking for equality. This will still work:

if (a = 5) {
  // ...
}

and a = 5 will always be true because JavaScript is weird*. You can avoid this by putting the value first (5 === a or 'string' === a) so when you instead accidentally use = it'll give an error.

*It's setting a to 5, and setting a variable returns the new value, so a = 5 returns 5. Nonzero numbers like 5 are considered true in JavaScript, so the if statement will always run.

Different types are not equal to each other.

console.log(1 === '1'); // false

You have to convert one type to the other beforehand.

console.log(1 + '' === '1'); // true
console.log(1 === +'1'); // true

loops

The while loop is like the repeat until _ block in Scratch, except it's the opposite. It keeps looping while its condition is true until it becomes false.

let n = 0;
while (n < 3) {
  console.log(n);
  n++;
}

and this happens:

(n is less than 3)

0

(n gets incremented to 1)

(n is less than 3)

1

(n gets incremented to 2)

(n is less than 3)

2

(n gets incremented to 3)

(n is not less than 3)

There's a more concise way to write that using a for loop (repeat _ times):

for (let i = 0; i < 3; i++) {
  console.log(i);
}
for (beginning; check; endOfEveryLoop) {
  body
}

The beginning part is always run first; you can use this to make some variables. Then before every loop, it checks if check is true; if so, it'll run body then endOfEveryLoop, and then loop again and run check and so on. When check is false, it'll stop.

In either loop you can use break; to stop the loop.

There's many ways to loop through an array.

let n = 0;
while (n < array.length) {
  console.log(array[n]);
  n++;
}

for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

for (let item of array) {
  console.log(item);
}

array.forEach(item => {
  console.log(item);
});

ask _ and wait / answer

prompt('question')

prompt('question', defaultValue) // defaultValue is optional

prompt outputs whatever the user types, and you can use that value and store it in a variable or something.

let answer = prompt('Type in a word that starts with a:');
while ('a' !== answer[0]) {
  answer = prompt('Actually type in a word that starts with a:', answer);
}

custom blocks

function sayHello(name) {
  console.log('Hello, ' + name + '!');
}
sayHello('Billy'); // Hello, Billy!

Functions can also return values that you can use.

function toKelvin(celsius) {
  return celsius + 273;
}
let temperature = +prompt('Enter a temperature in Celsius');
console.log(temperature + '°C = ' + toKelvin(temperature) + 'K');

time

Date.now() returns the number of milliseconds since some time long ago. You can perform some intense maths to extract the current second/minute/hour from it using % (the remainder operator) and /.

delays

You can wait for some time using setTimeout:

setTimeout(() => {
  console.log('a second has passed!');
}, 1000); // in milliseconds

Note that the rest of the JavaScript not inside the setTimeout will continue running.

console.log('Begin the race!');
setTimeout(() => {
  console.log('Oh no I lost!');
}, 100);
console.log('Ha, I win!');

HTML

You can make a simple web page for your JavaScript. Your JavaScript goes in <script> tags:

<script>
// JavaScript here
</script>

You can get user input using <input> and <button> tags, and set the HTML of some <span> tags to display output. Add id attributes to specify which element to select.

Distance calculator!
<br>
Difference in X: <input id="x">
<br>
Difference in Y: <input id="y">
<br>
<button id="calculate">Calculate!</button>
<br>
<span id="output"></span>

<script>
let xInput = document.getElementById('x'); // gets an HTML element
let yInput = document.getElementById('y');
let calculateBtn = document.getElementById('calculate');
let output = document.getElementById('output');

calculateBtn.onclick = () => { // when user clicks on Calculate! button
  let diffX = +xInput.value; // get input value and convert to number
  let diffY = +yInput.value;
  let distance = Math.sqrt(diffX * diffX + diffY * diffY);
  output.innerHTML = 'The distance is ' + distance;
};
</script>

wow this is a sidebar?!

(I think)

Clone this wiki locally