Assignment Series #A7 – Exercises

4.1 Tooling
4.1.1 Integrated Development Environment (IDE)
Create a new file (e.g. ide.js), copy the following code over and run it
console.log ("Welcome to learning JavaScript!");

Comments in Javascipt:
//console.log ("Welcome to learning JavaScript!");
//console.log ("No /* comments */ in strings " /*+ " but outside "*/);
// an example
4.1.2 Browser
Run the same code directly from your browser’s console. In most browsers’ consol
type your input expression without even having to put it within console.log. Try
navigator.platform to see what OS you’re running on according to your browser!

4.1.3 Debugging
I’ve skipped the node js debuging part in IDE, but followed the tutorial howto debug a js application with help of the developer tools inside the browser.
https://developers.google.com/web/tools/chrome-devtools/javascript

4.2 Syntax
4.2.1 Data Types
• Evaluate the types of the examples given to make sure the information in the concept book is correct!
• Have a look at the operators you can use on strings. Can you output all the types for the example in one
call to console.log?
String
String is used to store text. In JavaScript, strings are surrounded by quotes:
Single quotes: ‚Hello‘
Double quotes: „Hello“
Backticks: Hello
//strings example const name = 'john';
const name1 = "doe";
const result = `The names are ${name} and ${name1}`;
Number
Number represents integer and floating numbers (decimals and exponentials). For example:
const number1 = 3; const number2 = 3.433; const number3 = 3e5 // 3 * 10^5
BigInt
In JavaScript, Number type can only represent numbers less than (253 - 1) and more than -(253 - 1). However, if you need to use a larger number than that, you can use the BigInt data type.
A BigInt number is created by appending n to the end of an integer. For example,
// BigInt value const value1 = 900719925124740998n; // Adding two big integers const result1 = value1 + 1n; console.log(result1); // returns "900719925124740999n" const value2 = 900719925124740998n;
Note: You can’t mix BigInt and other types
Example below will produce error:
// Error! BitInt and number cannot be added const result2 = value2 + 1; console.log(result2);
Boolean
This data type represents logical entities. Boolean represents one of two values: true or false. It is easier to think of it as a yes/no switch. For example,
const dataChecked = true; const valueCounted = false;
Undefiend
The undefined data type represents value that is not assigned. If a variable is declared but the value is not assigned, then the value of that variable will be undefined. For example,
let name; console.log(name); // returns undefined
null
In JavaScript, null is a special value that represents empty or unknown value. For example,
const number = null;
The code above suggests that the number variable is empty.
symbol
A value having the data type Symbol can be referred to as a symbol value. Symbol is an immutable primitive value that is unique. For example,
const value1 = Symbol('hello');
const value2 = Symbol('hello');
Though value1 and value2 both contain 'hello', they are different as they are of the Symbol type.
object
An object is a complex data type that allows us to store collections of data. For example,
const student = {
firstName: 'john',
lastName: null,
class: 10
};
Operators summary
let x = 5;
let y = 3;
// addition
console.log('x + y = ', x + y); //8
// subtraction
console.log('x - y = ', x - y); //2
// multiplication
console.log('x * y = ', x * y); //15
// division
console.log('x / y = ', x / y); //1.6666666666666667
// remainder
console.log('x % y = ', x % y); //2
// increment
console.log('++x = ', ++x); // x is now 6
console.log('x++ = ', x++); // x returns 6 and then increases by 1
console.log('x = ', x); //7
// decrement
console.log('--x = ', --x); // x is now 6
console.log('x-- = ', x--); // x returns 6 and then increases by 1
console.log('x = ', x); //5
//exponentiation
console.log('x ** y =', x ** y); //125
Comparision operators summary
// equal operator
console.log(2 == 2); // true
console.log(2 == '2'); // true
// not equal operator
console.log(3 != 2); // true
console.log('hello' != 'Hello'); // true
// strict equal operator
console.log(2 === 2); // true
console.log(2 === '2'); // false
// strict not equal operator
console.log(2 !== '2'); // true
console.log(2 !== '2'); // false
4.2.2 Data Structures
4.2.2.1 Constant and variables
Declare both a constant and a variable each with types string and number assigned (four declarations
in total).
• Try to assign a new value to all of these. What happens when you try to assign to the constants?
• Can you assign a string to a variable that was previously assgined a number?
let x = "hi"; let y = 5; console.log(x); // hi console.log(y); // 5
const x = "hi"; const y = 5; console.log(x); // hi console.log(y); // 5
Once a constant is initialized, we can’t change it’s value
const x = 5; x = 10; // Error! constant cannot be changed. console.log(x)
4.2.2.2 Objects
Put down an object in JSON that describes yourself (e.g. age, family, pets, hobbies)
Javascript:
const student = {
name : "Daniel",
age: 35,
hobbies : [
{1. : "tabletennis and squash"},
{2. : "information technology and cybersecurity"},
{3. : "psychology"},
],
}
JSON:
{
"name": "Daniel",
"age": 35,
"hobbies": [
{
"1": "tabletennis and squash"
},
{
"2": "information technology and cybersecurity"
},
{
"3": "psychology"
}
]
}
4.2.2.3 Arrays & Maps
Create two arrays, one holding your favorite passwords (just kidding, use arbitrary ones, of course) and
another one holding the URLs of sites these belong to. Because you’re clever, you won’t put them in the
same order so that Eve doesn’t know which one to use :smirk:. Now, create a map that links the indexes
of the ULR array to the one holding the passwords.
// array containing my secret passwords
const passwordArray = [ 'Dagobert5', 'Donald2', 'Mikeymouse3', 'Goofy6'];
// array containing my secret websites
const URLArray = [ 'http://endless.horse/', 'http://onemillionlols.com/', 'https://thatsthefinger.com/', 'https://ghost.earth/'];
const map = {'http://endless.horse/':1, 'http://onemillionlols.com/':0, 'https://thatsthefinger.com/':3, 'https://ghost.earth/':2 };
4.2.3 Control Structures
4.2.3.1 Conditions
Output “fits” if all of the following conditions are true:
variables x and y are both smaller than 10
x multiplied by y is greater than 50
output “uncomfortable” if x multiplied by y is smaller than 50
output “out of bounds” if either x or y are greater than 10
// let x = 9
// let y = 6
// Enter value1 and value2
const number1 = prompt("Enter a value for x: ");
const number2 = prompt("Enter a value for y: ");
// check if number1 is smaler than 10
if (number1 <10 && number2 < 10 && number1 * number2 >50) {
console.log("fits");
}
if (number1 * number2 <50) {
console.log("unconfortable");
}
if (number1 >10 || number2 >10) {
console.log("out of bonds");
}
4.2.3.2 Case Matching
You have a variable x, which has been assigned an arbitrary value. Based on that value, you need to output
both value and type with some additional information based on type, e.g. “number: 5; my favorite number
is 21”
let x = 5;
let type = typeof x;
if (type == 'number'){
console.log("my favorite number is 42");
}
else if (type == 'boolean'){
console.log("my answer could be true or false");
}
4.2.3.3 Loop
Let’s implement a small sorting algorithm. We will get an array of numbers as in
for now) and at the end want that array to be sorted. While the algorithm is
each intermediate step to the console (e.g. Step 3: [1, 4, 9, 3, 26])
const numbers = [1, 4, 9, 3, 26];
let i;
let j;
let smalest_number;
let smalest_number_index;
// Anzahl Durchläufe für ein kleinstes Element suchen
for (i=0; i<numbers.length; i=i+1){
// Kleinste Zahl wird erstes Element von Subarray
smalest_number=numbers[i];
smalest_number_index=i;
// Durchsuchen des Subarrays für das kleinste Element
for (j=i; j<numbers.length; j=j+1){
// Vergleichen des jetzigen Elements mit dem bisherigen kleinsten Element im Subarray
if (numbers[j] < smalest_number) {
smalest_number=numbers[j];
smalest_number_index=j;
}
}
// Vertauschen des ersten Elements im Subarray mit dem kleinsten Element im Subarray
let temp=numbers[i];
numbers [i]= smalest_number;
numbers[smalest_number_index]=temp;
// Ausgabe der Zwischenschritte
console.log("Step "+ numbers);
}
//Ausgabe Sortiert
console.log(numbers);
4.2.4 Program structures
4.2.4.1 Methods
code comes here...
4.2.5 Language Features
4.2.5.1 Template Strings & Spread Operator
const me = JSON.parse(
{
"forename": "Daniel",
"surname": "Müller",
"alias": "Cybercop",
"age": 35,
"hobbies": [
{
"1.": "tabletennis and squash"
},
{
"2.": "information technology and security"
},
{
"3.": "psychology"
}
]
}
)
const meNow = {
currentActivity:"Learning JS",
currentStateOfMind:"tired"
};
console.log(JSON.stringify ({ ... me , ... meNow }));
4.2.5.2 Variable as Property Key
code comes here...
4.2.6 Algorithms
4.2.6.1 Searching
The filter() method is like the find() method, in that it requires a function passed and a condition for what will be returned. The main difference is, filter() always returns an array, even if there is only one matching element. But it will return all the matching elements, whereas find() only returns the first matching.
const alligator = ["thick scales", 80, "4 foot tail", "rounded snout", 80]; alligator.filter(el => el === 80); //returns [80, 80]
Reference: https://www.digitalocean.com/community/tutorials/js-array-search-methods
4.2.6.2 Sorting
var animals = [
'cat', 'dog', 'elephant', 'bee', 'ant'
];
animals.sort();
console.log(animals);
// ["ant", "bee", "cat", "dog", "elephant"]
Example with numbers:
var numbers = [1, 5, 12, 3, 7, 15, 9];
// Sorting the numbers array simply using the sort method
numbers.sort(); // Sorts numbers array
alert(numbers); // Outputs: 1,12,15,3,5,7,9
/* Sorting the numbers array numerically in ascending order
using the sort method and a compare function */
numbers.sort(function(a, b){
return a - b;
});
alert(numbers); // Outputs: 1,3,5,7,9,12,15
4.2.6.3 Mapping
code comes here...
4.2.6.4 Aggregating
function objectify (names) {
return names.reduce ((previous,current ) => ({ ... previous , [ current ]:
current.length }) , {}) ;
}
console.log (objectify(["an", "apple", "must", "be", "red"]));
// => { "an": 2, "apple": 5, "must": 4, "be": 2, "red":3}

