# 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 ` ``` ![js_random_color](img/js_random_color.png) ## 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. ```javascript // 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](img/js_random_color_alpha.png) ```javascript /* 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 ```javascript 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 ``` javascript 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 ``` javascript 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](https://www.w3schools.com/jsref/jsref_obj_string.asp) 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 [](variable-types)). ```javascript 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 `{}`. ``` javascript 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' ``` (variable-types)= ## 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. ``` javascript 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 ``` ```javascript // 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 ```javascript // Syntax if (condition) { // do this } else if (condition) { // do that } else { // otherwise do that } ``` (comparison)= ## Comparison ``` javascript 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](https://www.w3schools.com/js/js_comparisons.asp) ## Loops ### For ``` javascript // 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. ``` javascript 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. ``` javascript 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. ``` javascript 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 ``` javascript // 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().
```{admonition} One possible solution. :class: dropdown function change_color() { // Change size. change_size(); // 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; } function change_size() { var w = Math.floor(Math.random() * 100 + 1).toString() + 'vw'; var h = Math.floor(Math.random() * 100 + 1).toString() + 'vh'; document.getElementById('object').style.width = w; document.getElementById('object').style.height = h; } ``` ## Resources [Crash Course](https://raw.githubusercontent.com/sumnerevans/lug-js-crash-course/master/js-crash-course.pdf) by Sumner Evans and Sam Sartor [W3 Schools Tutorial](https://www.w3schools.com/js/default.asp) [Mozilla Developer Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript)