Web Applications

Lab 08


special thanks to Jan Michelfeit & Martin Kruliš

Motivation

Syntax


var n = 3; // number
var b = true; // boolean
var s = "abc"; // string
var s = 'abc'; // string
var u; // undefined
      

function myFunction1(argument) {
  return 42;
}

var myFunction1 = function(argument) {
  return 42;
}
      

while (true) { /* ... */ }

for (var i = 0; i < 3; i++) { /* ... */ }

for (var i in value) { /* i is index/key */ }
for (var v of value) { /* v is value (ES6) */ }

if (4 == 2) { /* ... */ } else { /* ... */ }
      

var myArray = [ "a", "b", "c" ];
myArray.length;
myArray[0] = "A";
      

var myObject = { key1: "value1", key2: "value2" };

var myObject = new Object();
myObject.key1 = "value1";
myObject["key2"] = "value2;

// Note:
// { "key1": "value1", "key2": "value2" }
// in JSON
      

var a = ["a", "b"];
var b = { 0: "a", 1: "b" };
a[0] == b[0] // true
      

Exercise 1

  • Write a JavaScript function that prints a triangle of # for a given n; e.g., for n = 3:
    #
    ##
    ###
  • Use

Scope

  • Variables declared with var are visible in the entire body of function where they were declared
  • Variables declared outside functions with var are global
  • Variables declared with let (ES6+) are visible in block (statement, expression) where they were declared

var x = 5;

(function () {
    console.log(x);
    var x = 10;
    console.log(x);
})();
      

(function () {
  console.log(x);
  console.log(y);
  var x;
  let y;
})();
      

stackoverflow : What is the scope of variables in JavaScript?

Data types

Type Conversions


"5" + 2

"5" < "10"

"5" == 5
      

Type Conversions


5 + null   // 5       (null is converted to 0)
"5" + null // "5null" (null is converted to "null")
"5" + 2    // 52      (2 is converted to "2")
"5" - 2    // 3       ("5" is converted to 5)
"5" * "2"  // 10      ("5" and "2" are converted to 5 and 2)
"5" == 5   // true
      

Dynamic Typing


function logDate(date) {
    if (typeof date == "string") {
        log(new Date(date));
    } else if (date === undefined) {
        log(new Date());
    } else {
        log(date);
    }
}
logDate("2219-12-09");
logDate(new Date("2119-12-09"));
logDate();
      

Controlling conversions

What to do if I want an explicit conversion?


var five = "5"
Number(five) + 2
parseInt(five, 10) + 2
parseFloat(five) + 2
+five + 2
      

Controlling conversions

What if I don't want a conversion?


"5" === 5 // false
"5" !== 5 // true
      

Objects

  • Basic building blocks of data structures
  • Collections ("bags") of key-value pairs
    (like "hash table" or "dictionary")

Objects


var o = {
    myValue: 42,
    myFunction: function() { log("called"); }

    myFunction2() { log("called"); } // ES6 only
}
o.myValue;
o.myFunction();
      

Objects - extending


var o = {
    myValue: 42,
    myFunction: function(arg) {
        log("called " + arg);
    }
}
o.myValue = 43; // changes value of property myValue
o.mySecondValue = "x"; // adds new property
o.myFunction = function(arg) { // redefines the "method" of object o
    log("changed " + arg);
};
      

for...in


var a = ["a", "b"];
for (var i in a) {
    log(a[i]);
}
var b = { key1: "a", key2: "b" };
for (var i in b) {
    log(b[i]);
}
      

Arrays

Useful methods and properties


myArr.length
myArr.forEach(someFunction)  // call someFunction for each element, passing it as argument to the function
myArr.filter(filterFunction) // filter
myArr.map(mapFunction)       // transform
myArr.some(condition)        // at least one element satisfies condition
myArr.reduce(reduceFunction, initialValue)

myArr.sort() // sorts elements in place
myArr.push() // adds element to array
      

Arrays


var names = [ "Philip Fry", "Turanga Leela" ];
var firstNames = names.map(function(name) {
    return name.split(" ")[0];
});
// [ "Phillip", "Turanga" ]
      

Exercise 2


// TODO: implement functions manipulating a linked list
// An item in the linked list must be represented as an object
// with properties 'value' and 'rest' (see tests below)
// Example: {value:1, rest: {value:2, rest:null}}
// Empty list is 'null'.

/**
 * Insert value at the beginning of the list
 * (and return newly created list).
 */
function prepend(value, list)
{
}

/**
 * Convert an array into a list (empty list is null).
 */
function arrayToList(arr)
{
}

/**
 * Get n-th value from given list. Return undefined
 * if the item does not exist.
 */
function nth(list, n)
{
}

/**
 * Convert a list into an array.
 */
function listToArray(list)
{
}

// TESTS:
// DO NOT MODIFY !!! (read only)
function test(value, expected) {
    const valueStr = JSON.stringify(value);
    const expectedStr = JSON.stringify(expected);
    console.log(valueStr == expectedStr
        ? "Test OK"
        : "Test FAILED: expecting " + expectedStr + ", got " + valueStr);
}

const twoItemsList = {value:1, rest: {value:2, rest:null}};
test(prepend(1, {value: 2, rest: null}), twoItemsList);
test(arrayToList([1, 2]), twoItemsList);
test(nth(twoItemsList, 1), 2);
test(listToArray(twoItemsList), [1, 2]);

test(prepend(1, null), {value:1, rest:null});
test(listToArray(null), []);
test(nth(null, 1), undefined);
      

The end…

Questions?

Feedback