25. Oct. 2022, 17:00-18:30
Introductory reference guide @ MDN web docs: Looping code
var i = 0;
while (i < 100) {
// doing some stuff here
console.log(i);
// increasing the loop condition
i++;
}
var i = 0;
do {
// doing some stuff here
console.log(i);
// increasing the loop condition
i++;
} while (i < 100);
for (var i=0; i<100; i++) {
// doing some stuff here
console.log(i);
}
var myArr = ['This', 'is', 'an', 'array', 'full', 'of', 'words'];
for (var i = 0; i < myArr.length; i++) {
console.log( i, myArr[i] );
}
var answer;
do {
answer = prompt('Tell me a little more about you.');
} while (!answer || answer.toLowerCase() !== 'no');
break
ing out of a loop
for (var i=0; i<50; i++) {
// doing some stuff here
console.log(i);
// check for a condition to end the loop
if (i > 0 && i % 42 === 0) {
break;
}
}
continue
ing the loop iteration
for (var i=0; i<50; i++) {
// only do stuff every other time
if (i % 2) continue;
// doing some stuff here
console.log(i);
}
try out what you've learned so far
3 types of scope in JS, which determine the visibility/accessibility of variables
var
var x = 23; // global scope
function doSomething () {
// a function always has access to parent scope
console.log('doing something with x:', x); // 23
}
function doSomeMore () {
var x = 'WTF?!?'; // function scope masks the parent/global scope
var y = 42; // function scope
console.log('x inside something:', x); // 'WTF?!?'
console.log('y inside something:', y); // 42
}
doSomething();
doSomeMore();
console.log('x in global scope:', x); // 23
console.log('y in global scope:', y); // throws error, existed only in doSomeMore()
if ( true ) {
var x = 'block23'; // no block scope available with var -> global scope
var z = 'mimimi'; // no block scope available with var -> global scope
}
console.log('x after assignment in block:', x); // 'block23'
console.log('z outside of scoped block:', z); // 'mimimi'
let
let x = 23; // global scope
// doSomething() and doSomeMore() work similar with let than in the var example
// only let does not let you redeclare a variable if it was already
// declared once, in the scope (var would let you do that)
// but now for the block scope thingy
if ( true ) {
let x = 'block23'; // block scope
let z = 'mimimi'; // block scope
}
console.log('x after assignment in block:', x); // 23, the 'block23'-x only existed in block
console.log('z outside of scoped block:', z); // throws error, existed only in block
Add the following functionality to the page developed in session 3: