JavaScript

JavaScript is a programming language made to change the appearance or behaviour of a web site. Code is stored in plain text files with the file ending .js or included into an HTML file with the <script> tag. For the latter it’s recommended to insert the script at the bottom of the page, above the closing </body> tag.

JavaScript is executed through the browser. You can test code snippets through the inspector tool or with a sandbox like JSFiddle.

index.html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        #object {
            width: 40vw;
            height: 40vw;
            background-color: rgb(235, 132, 66);
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        #object:hover {
            cursor: pointer;
        }
    </style>
</head>
<body>

    <div id="object" onclick="change_color();"></div>

    <script>
        function change_color() {
            // Return random colors.
            var r = Math.floor(Math.random() * 255);
            var g = Math.floor(Math.random() * 255);
            var b = Math.floor(Math.random() * 255);
            // Create a string with the variables r, g and b.
            var color = `rgb(${r}, ${g}, ${b})`;
            // Change the background color.
            document.getElementById("object").style.background = color;
        }
    </script>

</body>
</html>

js_random_color

Functions

On click onto the colored square it’s color will be changed. The function is called through onclick="change_color();". The function is defined through function change_color() { ... }. The word function is a reserved keyword, the name of the function itself is of your choice. Everything inside the {} will be executed when the function is called.

// Syntax
function my_function() {
    // Code of the function.
    // Code of the function.
}

The block of code to be executed inside the function is indent by a tab. This is done for (human) readability only. It’s possible to place all the code in one line.

Variables

The next keyword var defines a variable. A variable can store data (and functions) and this data can change over time. With the help of the built-in random function (Math.floor(Math.random() * 255);) a number between 0 and 255 is generated and assigned to the variables r, g and b.

This values are inserted into a string (text), stored in the variable color. The string follows the CSS command for an rgb value.

With document.getElementById("object").style.background = color; this rgb values will be assigned to the HTML element with the id “object”.

Task: Modify the code. Add an alpha channel to the color of the square. Consider adding text as well to see the effect.

js_random_color_alpha

/* Function with alpha channel */
function change_color() {
    // Return random colors.
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    var a = Math.random();
    // Create a string with the variables r, g, b and a.
    var color = `rgba(${r}, ${g}, ${b}, ${a})`;
    // Change the background color.
    document.getElementById("object").style.background = color;
}

Primitive Datatypes

We’ve seen numbers and text data types in the example above. Here is a full list of primitive datatypes:

  • Number var n = 1

  • String var text = 'some text'

  • Boolean (true or false) var clicked = false

  • Undefined

  • Null

  • Symbol

var a = 1;
var b = 2;
var c = a+b;
console.log(c); // 3
var a = 'some text';
console.log(a); // some text
var b = 'some text';
var texts_identical = (a === b); // true
console.log(texts_identical);
var e;
console.log(e); // undefined

Number

var a = 0;
a++; // Increment by 1. a = 1
a += 4; // a + 4 = 5
var b = a / 2; // b = 2.5
var c = 4 * 3; // c = 12
c = c / 2; // c = 6
c = 6 % 2; // c = 0
c = 5 % 2; // c = 1
c--; //c =  0

String

var fox = 'The quick brown fox'; // Declaration with single quotes
var dog = " jumps over the lazy dog."; // Declaration with double quotes
var text = fox + dog;
var len = text.length; // 44
var dog_at_end = text.endsWith('dog.'); // true
var dog_at_start = text.startsWith('dog.'); // false
var number = 13; // 13
var number_toString = number.toString(); // "13"

More on Strings

For booleans see Comparison.

Array

An array is a list of items (variables, objects, functions). It’s defined through [] and comma separated values. Commonly arrays are declared with the const keyword (See Scope & var, let, const).

const rgb = [235, 132, 66];
const word_list_1 = ['creative', 'uncreative', 'experimental', 'boring', 'open'];
const word_list_2 = ['code', 'algorithms', 'processes', 'machines'];

// Mixed type arrays are possible.
const arr = [235, 'creative', false, rgb];
console.log(arr); // [235, "creative", false, [235, 132, 66]]

// Override a value.
arr[1] = '(un)creative'; // Arrays start with index 0.
console.log(arr); // [235, "(un)creative", false, [235, 132, 66]]

// Access the first item:
var first = arr[0]; // 235
// Access the last item:
var last = arr[arr.length - 1]; // [235, 132, 66]
// Add an item:
arr.push('new item');
// Sort the array:
arr.sort(); // ["(un)creative", 235, [235, 132, 66], false]

Objects

Objects are structured like a dictionary. They contain (multiple) key:value pairs (properties), enclosed by {}.

const headline = {word:'creative', rgb:[235, 132, 66]};

// Access properties:
console.log(headline.word); // 'creative'
console.log(headline.rgb); // [235, 132, 66]

// Or:
console.log(headline['word']); // 'creative'

Scope & var, let, const

Scope is the area in which data or a function is available. In general there are three different scopes: global, local and block.

Everything declared outside of a function is global, everything inside local, with one exception: Variables inside a function that are declared without the var keyword.

var a = 'global'; // global variable

function x() {
    b = 'global inside function'; // global variable
    var c = 'local inside function'; // local variable
}


x(); // execute x

{
    let d = 'local inside block';
    var e = 'global inside block';
}

console.log('a:' + a) // global
console.log('b:' + b) // global inside function
console.log('c:' + c) // Error: c is not defined
console.log('d:' + d) // Error: d is not defined
console.log('e:' + e) // global inside block
// Variables with var can be redeclared:
var a = 1;
var a = 'word';

// Variables with let not:
let a = 1;
let a = 'word'; // Error

// Variables with const can not be redeclared, but properties of const Arrays or Objects can change.
const a = 1;
const a = 2; // Error

const word_list_1 = ['creative', 'open'];
// Add a value
word_list_1.push('boring');
// Change a value
word_list_1[0] = '(un)creative';
console.log(word_list_1); // ["(un)creative", "open", "boring"]

if

// Syntax
if (condition) {
	// do this
} else if (condition) {
	// do that
} else {
	// otherwise do that
}

Comparison

1 == '1'; // true
1 === '1'; // false
1 != 1; // false
1 > 0; // true
1 < 0; // false
1 >= 0; // true
1 <= 0; // false

=== checks the value and the type (like number and string above)

== casts the type if necessary and compares then

!- true if not equal

See more

Loops

For

// Syntax
for (initializer; condition; incrementor) {
    // do something for each iteration
}
// Example
for (let i=0; i < 5; i++) {
    console.log(i);
}
// Result
0
1
2
3
4

For In

Loop over an object.

const headline = {word:'creative', rgb:[235, 132, 66]};

for (let key in headline) {
    // get value for key
    console.log(headline[key]);
}
// creative
// [ 235, 132, 66]

Loop over an array.

let word_list_2 = ['code', 'algorithms', 'processes', 'machines'];

for (let i in word_list_2) {
    console.log(word_list_2[i]);
}
// code
// algorithms
// processes
// machines

For Of

Loops through elements of an array or string.

let word_list_2 = ['code', 'algorithms', 'processes', 'machines'];

for (let item of word_list_2) {
    console.log(item);
}
// code
// algorithms
// processes
// machines

for (let character of word_list_2[0]) {
    console.log(character);
}
// c
// o
// d
// e

Functions – return

// Insert data via arguments.
function sum(a, b) {
    var res = a+b;
    // Return the result.
    return res
}
r = sum(2, 7);
console.log(r); // 9
Task: Write a function which changes the size of the object. Call it from within change_position().

Resources

Crash Course by Sumner Evans and Sam Sartor

W3 Schools Tutorial

Mozilla Developer Docs