Client side programming

Lecture #7 - Exam prep

slides.com/jkohlin/js7/live

statements

-Changes something

-Ends with semicolon ; (usually)

// the variable buttonLabel is changed
buttonLabel = "Switch to Bright mode";


// the HTML is changed
document.querySelector("button").innerHTML = buttonLabel;

expressions

-Are values

or something that

-Resolve to values

              // This is a literal string expression 
buttonLabel = "Switch to Bright mode";

                // This is a variable expression
btn.innerHTML = buttonLabel
var b = 20;
var c = 3;

var a = b * 2 + Math.round( c / 2 ) ;

ALL EXPRESSIONS MUST FIRST RESOLVE TO A VALUE before assigned

-start from the left (if possible)

expressions

var b = 20;
var c = 3;

var a = b * 2 + Math.round( c / 2 ) ;

variable expression

var b = 20;
var c = 3;

var a = 20 * 2 + Math.round( c / 2 ) ;

arithmetic expression

Math chip

var b = 20;
var c = 3;

var a =   40  + Math.round( c / 2 ) ;

litteral number expression

 

var b = 20;
var c = 3;

var a =   40  + Math.round( c / 2 ) ;

function call expression

var b = 20;
var c = 3;

var a =   40  + Math.round( c / 2 ) ;

arithmetic expression

var b = 20;
var c = 3;

var a =   40  + Math.round( c / 2 ) ;

variable expression

var b = 20;
var c = 3;

var a =   40  + Math.round( 3 / 2 ) ;

litteral number expression

var b = 20;
var c = 3;

var a =   40  + Math.round( 3 / 2 ) ;

arithmetic expression

var b = 20;
var c = 3;

var a =   40  + Math.round(  1.5  ) ;

litteral number expression

var b = 20;
var c = 3;

var a =   40  + Math.round(  1.5  ) ;

function call expression

var b = 20;
var c = 3;

var a =   40  +          2          ;

litteral number expression

 

var b = 20;
var c = 3;

var a =   40  +  2 ;

arithmetic expression

var b = 20;
var c = 3;

var a =      42    ;

litteral number expression

(can't be resolved further)

var b = 20;
var c = 3;

var a = 42 ;

assignment expression

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body>
  <h1>Hello, world!</h1>  

  <script>
  alert("Hey JavaScript!");  
  </script>
</body>
</html>

Where to put the code 

Alternative 1: write code in the HTML-document

Variables

named memory cells

var ≈ name a memory cell

var height; 

In programming terms:

Declare the variable height

What is actually happening:

Reserve space in RAM for a future value and refer to it as height

Save a value to a variable

height = 187;

In programming terms:

Assign the value 187 to the variable height

What is actually happening:

Write 187 to the Memory at the position referred to as height

Declare and assign

var height = 187;

This is a shorthand.

It first declares the variable height

Then assigns the value 187 to it.

Declaring variables

ES6 style

let and const

  • are not hoisted
  • are block scoped
  • const cannot be re-assigned

 

 

 

Use them if you want to, but understand the difference from var

const yearOne = 1970

if (previousYear == 2018) {
	let year = previousYear + 1     
}
  
var previousYear = 2018 // var is hoisted

// the following will produce errors
yearOne = 1 // cannot re-assign a constant
console.log( year ) // year is forgotten

naming Variables

RESTRICTIONS

animal = "cat";
zip    = 90210;
_underscore = true;
$dollar     = 500;

or _

or $

The first letter must be:
a-z

subsequent characters can also be numbers

var _ÅÄÖüñ_ = "Happy"

These are not allowed

// start with a number
var 4ever = Infinity;

// no spaces in variable names
var my number = 42;

// no dashes (minus)
var zip-code = 90210

Avoid these characters

e1337 = 1337;

Operators

usually go between two values

Mathematical operators

arithmetic operators, to be nerdy

40 + 2 // 42

44 - 2 // 42

21 * 2 // 42

84 / 2 // 42

Arithmetic expressions

Assignment operator

the right side is assigned to the left side

cat = "tiger"

Relational operators

results in a boolean; true or false

42 == "42"  // true

44 < 2      // false

21 >= 2     // true

84 != 2     // true

"42" === 42 // false

Logical operators

results in a boolean; true or false

42 == "42" &&  Math.PI > 3 // true
42 === "42" || Math.PI > 3 // true

Both must be true for the expression to be true

Only one needs to be true for the expression to be true

Group Logical operators

 

var nmd = prompt("What year?")
var overall = confirm("Overall on?")
var vip = prompt("pass phrase?")

if ( overall == true && (vip =="42" || nmd == 1)  )

Conditional statement

AKA the if-statement

The if statement

if (true == true) {
  /* Code in this block
   * Will only run if 
   * the test is true. */
}

A test (boolean expression)

The else if statement

Can only follow an if-statement

if ( extra ) {
  points = points + 1 // only if extra is true
  
  
} else if (points == 0){
    
  alert ("Can't get any lower") 
  /* only if extra is false 
   * and points is 0 */
} else {
  points = points -1
}

OK, well, what about...

Otherwise

while

var fruits = ["kiwi", "mango", "orange", "banana", "apple"];

var index = 0;

while (index < fruits.length) {

    console.log( fruits[index] );
    index++;

}

...as you know

break;  //to exit

for

is a compressed form of while

functions

run-later codeblocks

<body>
  <button onclick="headsOrTails()">flip</button>
</body>

Functions let you run the code later, and again

function headsOrTails() {
    coin = Math.round(Math.random())
	if (coin == 0) {
        coin = "HEADS"
    } else {
        coin = "TAILS"
    }
  	console.log(coin)
}

functions

can have preferences

function area(width, height) {
  alert( width * height )
}
area(45, 20) // 900
area(10, 5) // 50

A value's journey from 

 arguments / PARAMETERS and variables

see page 90

A function is a value

var headsOrTails = function(bet) {
  var coin = Math.round(Math.random())
  if (coin === bet) {
    console.log("you won!")
  } else {
    console.log("you lost.")
  }
};

The entire function body is saved to memory

This is an alternative way to declare a function. 

This means

…you can pass it along

function scream(message) {
  console.log( message.toUpperCase() );
}

var yell = scream;

yell("excuse me") // EXCUSE ME
var c = 4;
function half(num) {
  return num/2;
  alert('boo hoo, I will not popup');
}
var a = half( c * 3 ) ;

return...

also quits the function.

return works like break in a loop. It will return a value and then stop reading the rest of the code in the function

see page 98-108


var gName = "Jane";

function printer() {  
  var name = "Tarzan";
  verb = " loves "  
  console.log(name + verb + gName);
}

console.log(gName);

LOCAL

GLOBAL

If you forget the var keyword inside functions,

the variable will be declared in the global scope

Arrays

Objects

Functions

Numbers

Strings

Booleans

typeof

typeof 1337 // number
typeof "42" // string
typeof true // boolean

/* Put parentheses 
 * around expressions
 */
typeof ("20"+1)   // string
typeof ("2" == 2) // boolean

Test the type of a value or expression

Numbers

think math

  • can be integers like 1 or 2 or 42
  • can be floats (decimal) like 3.14156

It's a dot .

not a comma , 

Strings

think text

  • If you put quotation around a value
    you got yourself a string. 
  • Pay attention when copying: Quotations from word might have typographical marks like ”Invalid” or ’error’. Must be straight ' "
  • A string could be as small as "a" or an entire book
  • It's just a string of characters.
    "55" or "👍" or "{a:42}" or "deoxyribonucleic acid" or even "           "

Concatenate strings

(That means join)

var firstName = "John "
var lastName = "Doe"

var fullName = firstName + lastName 

console.log(fullName) // "John Doe"

use + between strings to join them

String surprise #1

var age = "20"

console.log(age + 1)

What's the result? 

Why do you think?

Try different numbers

Convert strings

If a string contains only numbers
it can be converted to the type number

var age = "20"
age  = Number(age)
console.log(age + 1) // 21

String methods

var flower = "Chrysanthemum"

flower.length // 13 (characters)

flower.indexOf("y") // 3 (position)

flower.charAt(0) // "C" 

flower.toUpperCase() // "CHRYSANTHEMUM"

flower.toLowerCase() // "chrysanthemum"

Arrays

An array is a list of values

Billboard

0. Someone You Loved
1. Truth Hurts
2. Senorita
3. Circles
4. No Guidance
5. Panini
6. HIGHEST IN THE ROOM
7. Ran$om
8. Bad Guy
9. 10,000 Hours

var billboard = [ 
  'Someone You Loved',
  'Truth Hurts',
  'Senorita',
  'Circles',
  'No Guidance',
  'Panini',
  'HIGHEST IN THE ROOM',
  'Ran$om',
  'Bad Guy',
  '10,000 Hours' 
];
billboard[3] // 'Circles'

But in javaScript 1'st place is 0

how to populate an array

1.

2.

3.

//populate it from the start:
var circles = ['green', 'green', 'green', 'green'];
// Built in method push, adds to the end of the array
circles.push('red');
// unshift, adds to the beginning of the array
circles.unshift('red');

4.

//Specify a position 
circles[4] = 'red';

how to remove from an array

1.

2.

3.

// pop removes the last element
circles.pop();
// shift, removes the first element
circles.shift();
// weird quirk
circles.length --

4.

// remove 1 at position 3
circles.splice(3,1); 

More built in functions

Sort alphabetically

fruits.sort(); // ["apple", "banana", "cherry"];

Search for an item #1

fruits.includes('cherry'); // true

Search for an item #2

fruits.indexOf('cherry'); // 0
var fruits = ["cherry", "banana", "apple"];

splice()

 changes an array by removing items

/******************************
  Array.splice(2,1) means:
  Go to index 2, 
  remove 1 item 
  and return it (as an array).
******************************/

var fishes = ["shark", "salmon", "dolphin", "cod"];
var mammals = fishes.splice(2, 1);

/******************************
  fishes: ['shark', 'salmon', 'cod']
  mammal: ['dolphin']
******************************/

Objects

Two ways to set properties

literal syntax

var friend = {
    name:     "Jane Doe",
    phone:    "555-12345",
    email:    "jane@doe.com",
    bff:      true
};
var friend = {};

friend.name = "Jane Doe";
friend.phone = "555-12345";
friend.email = "jane@doe.com";
friend.bff = true;

dot notation

A.K.A. JavaScript Object Notation or JSON

Two ways to get properties

brackets notation

alert( friend["name"] );
alert( friend.name );

dot notation

this

a keyword that refers to itself

var fruit = {
    kind: "apple",
    color: "red",
    print: function() {
        console.log( this.kind );
    }
}

fruit.print();

this always refer to the object the function was called from. In this case print is called from fruit

The object constructor

function Gingerbread (text) {
  this.decoration = text;
}

var cookie = 

new

Gingerbread("Daniel");

{decoration:"Daniel"}

"Daniel", is passed to Gingerbread and assigned to the property decoration of the this new object

A function made to create new objects

The object constructor

function Gingerbread (text) {
  this.decoration = text;
}

var cookie = 

{decoration:"Daniel"}

The constructor call expression is resolved to a new object with a decoration property set to "Daniel"

and saved to the variable cookie

The object constructor

function Gingerbread (text) {
  this.decoration = text;
}
var cookie = new Gingerbread("Daniel");

"Daniel"

cookie.decoration

The Prototype object

function Car (color, brand) {
  this.color = color;
  this.brand = brand;
  this.fuel = "diesel";
}

Car.prototype.present = function () {
  console.log("This is a " + this.color + " " + this.brand)
}

var micra = new Car("white", "Nissan")
var m3 = new Car("black", "BMW")

micra.present() // This is a white Nissan
m3.present() // This is a black BMW
  • available in the Constructor functions
  • accessible from all objects created with the constructor

Exam prep

By Johan Kohlin

Exam prep

Repetition for the exam

  • 969