Web Applications

JavaScript Introduction

Objectives

  • JavaScript Introduction
  • Exercise: Rectangle
  • Demonstration: Objects
  • Exercise: Linked list

"Secret" tip for JS Assignment : Rectangles.

JavaScript Introduction

JavaScript is interpreted language, like Python or PHP. JavaScript files can utilize .js extension. You can run JavaScript script file using node ./file-to-run.js

You can install NodeJs locally, use your browser (F12, console), or online sandbox ( playcode.io (size limit), jsfiddle.net, .. ).
NodeJs is available at lab computers.

Variables

Tutorials often declare using "var" instead of "let" and "const". Unless you know JavaScript avoid using "var".


let n = 3; // number

let b = true; // boolean

let s = "a" + "b" + "c"; // string addition,

const TOKEN = 'abc'; // constant string

let u; // undefined

let n = null;
    

Use better property names. All of the above are BAD!

Functions


// We can redeclare function multiple times.
function myFunction1(argument) {
  return 42;
}

// We can change function after declaration.
// Use of name after function is optional.
let myFunction1 = function(argument) {
  return 42;
}
    

Nested functions

Function can be nested. Since functions are first class citizens, we can store them in variables. As a result, we can easily parametrize algorithm's behaviour.


function createAdditionByAmount(amount) {
  // Inner function have access to local variables.
  return function(value) { return amount + value; }
}

// First argument would be a function.
function apply(fnc, value) {
  // We call the function using given argument.
  return fnc(value);
}

// We store function inside a variable.
const addTwo = createAdditionByAmount(2);

apply(addTwo, 1);
    

This is one of the core concepts of JavaScript.

Control structures


if (expression) stmt; else stmt;

while (expression) stmt;

for (let index = 0; index < 3; index++) stmt;

// Iterate using index/key.
for (let index in value) stmt;

// Iterate values, since ES6.
for (let item of value) stmt;

...
    

There are functional-like alternatives to iterating over items in an array or object.

Do not forget to use "let" in for-loops, this is not PHP!

Array

Array can mix value just like PHP. Keys are always integers.


const myArray = [ "a", "b", "c", 4 ];

myArray[0];
myArray.length;

myArray[0] = "A";

// Add at the end.
myArray.push(1);

// We can add array into array.
myArray.push([]);
    

Objects

Objects are the second core concept of JavaScript. They are used not only to store data, but also as classes,


// Declare object with object initializer.
let myObject = { key1: "value1", "key2": "value2" };

// Access object,
myObject.key1;
myObject["key1"];

// Redefine object.
myObject = {};
myObject.key1 = "value1";
myObject["key2"] = "value2";

JSON.stringify(myObject);
console.log(myObject);
    

Use of object initializer is only one way to create an object.
More about objects later.

Array vs. Objects


// This is an array.
const left = ["a", "b"];

// This is an object.
const right = { 0: "a", 1: "b" };

// You can not tell the difference here!
left[0] == right[0] // First items are the same.
    

Output

Depends on a runtime environment of choice:

  • NodeJs: process.stdout.write("")
  • Browser: interaction with DOM

We can utilize console.log in both. It is designed as a log function and performs formatting. There are other log levels: console.warn, console.error, ...

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
"5" === 5;   // false

null == undefined // true
null === undefined // false
    

It is better to not rely on automatic type conversion.

Controlling conversions


const five = "5";

Number(five) + 2;         // 7

parseInt(five, 10) + 2;   // 7

parseFloat(five) + 2;     // 7

const number = 2;
number.toString(10);      // "2"
    

Keep it boring!


const five = "5";

five + 2;                 // "52"
+five + 2;                // 7
    

Exercise: Rectangle

Create a function that given size of a rectangle computes and print perimeter, and area. In addition this function renders the rectangle to output using ASCII art, see example bellow. Test the functions by calling it several times and properly handle different inputs.
Mind code decomposition!
Do NOT read from standard input, hard-code values in your code!

Example output for values: 5 3

  Perimeter: 16
  Area: 15

  *---*
  |...|
  *---*  
  

Make sure you properly handle edge-cases, like size 0, 1, and 2.

Bonus: try different environments (Browser, NodeJs, online tool).

Exercise: Linked List


// 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(array) { }

/**
* 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) { }

/**
* Call callback with each item in the list.
*/
function forEach(list, callback) { }

// TESTS, DO NOT MODIFY !!!

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 threeItemsList = {value:1, rest: {value:2, rest:{value: 3, rest: null}}};
test(prepend(1, {value: 2, rest: {value: 3, rest: null}}), threeItemsList);
test(arrayToList([1, 2, 3]), threeItemsList);
test(nth(threeItemsList, 1), 2);
test(listToArray(threeItemsList), [1, 2, 3]);

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

let sum = 0;
forEach(arrayToList([1,2,3,4]), function (item) { sum += item; });
test(sum, 10);

  

Demonstration: Objects

Object consist of key:value pairs. Value can be a function. Key, also called "property name", is always a string.
We can omit quotes for some keys.


let obj = {
  // Same as "myValue": 42,
  myValue: 42,
  "myFunction": function() { console.log("myFunction called"); },
  // ES6, shorthand "myFunction2": function myFunction2() ...
  myFunction2() { console.log("called"); },
  // Primer: using this, more on this later.
  "printValue": function () { console.log(this.myValue); }
};

obj.myValue;
obj.myFunction();
  

Exercise: Bonus

Update first assignment to use objects and methods. Define object with width, height and functions to calculate area, perimeter and print the rectangle.

How are we doing?

  • JavaScript Introduction
  • Exercise: Rectangle
  • Demonstration: Objects
  • Exercise: Linked list

Leave an anonymous feedback.

Questions, ideas, or any other feedback?

Please feel free to use the anonymous feedback form.