Client side programming

This weeks Read: Chapter 1

minus loops

html

Code is just text in a plain text file. 

Just Like HTML and CSS

c

c#

javascript

java

javascript

Jay-Ess 

for short

JavaScript versions

ECMAScript is the standard upon which JavaScript is based, and it’s often abbreviated to ES.

  • For compatibility reasons many still stick to ES5
  • ES6 was a big update in 2015.
    A lot of the new stuff are at a more advanced level though.
  • The latest stable version today is ES9

Let's have a look at the code

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="first-look.css">
</head>
<body>
    <h1>Welcome to my dynamic website</h1>
    <button>Switch to Dark mode</button>
</body>
</html>
var mode = "dark";
var buttonLabel = "Switch to Bright mode";
var linkTag = document.querySelector("link");

if (mode == "dark") {
    linkTag.href = "first-look-bright.css";
    mode = "bright";
    buttonLabel = "Switch to Dark mode";
} 

document.querySelector("button").innerHTML = buttonLabel;

Can you figure out what is going on?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="first-look.css">
    <title>A first look at JavaScript</title>
</head>
<body>
    <h1>Welcome to my dynamic website</h1>
    <button>Switch to Dark mode</button>

    <script>
    var darkMode = false;
    var buttonLabel = "Switch to Bright mode";
    var linkTag = document.querySelector("link");

    function switchModes() {
        if (darkMode) {
            // if we got here, the page was Dark when the user clicked. Let's wwitch to bright mode. 
            linkTag.href = "first-look.css";
            darkMode = false;
            buttonLabel = "Switch to Dark mode";
        } else {
            // the variable darkMode was false when the button was clicked, so lets toggle the mode to dark.
            linkTag.href = "first-look-dark.css";
            darkMode = true;
            buttonLabel = "Switch to Bright mode";
        }
        document.querySelector("button").innerHTML = buttonLabel;
    }
    
    document.querySelector("button").onclick = switchModes;

    </script>
</body>
</html>

Basic terminology

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

! important

remember !

Expressions are always resolved

to a single value

Don't worry,

We'll get back to that soon

Let's try it out a little

  1. Open Chrome
  2. Open the web inspector
  3. Switch to the Console tab
  4. Type the following (not the comments):
var msg = prompt()
// Press Return to run the script.
// Type something in the box and click OK, 
// then type the following:
console.log(msg)
//Explain to your neighbour what just happened

The Console

Next to the browsers web inspector

Mac: CMD + J 

Win: Ctrl+ Shift + J

<!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

Position of the script tag

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

  <script src="lab2_kojo.js"></script>
</body>
</html>
var msg1 = "Put the script tag ";
var msg2 = "just before </body>"
alert(msg1 + msg2);

lab2_kojo.js

Where to put the code

Alternative2: import an external file

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
  
  <script src="lab2_kojo.js" defer></script>
  
</head>
<body>
  <h1>Hello, world!</h1>  
</body>
</html>

Where to put the code

Alternative placement: in the header

! IMPORTANT

The defer attribute puts the script on hold until all HTML has loaded. This is important when we later on manipulate the HTML.

Variables

Named memory slots

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

You need to learn some more to fully understand the difference from var

const variables are constant. They cannot be changed later on.

 

Use them if you want to, but understand that they are block scoped.

let year = 2019    
const planet = "earth"

Variables

I will remember this as flower

"Chrysanthemum"
var flower = "Chrysathemum";

variable name

JS keyword:
-Define new variable

A value

Variables

work like placeholders or shortcuts to values

alert(flower);

naming Variables

RESTRICTIONS

break         case          catch
class         const         continue
debugger      default       delete
do            else          export
extends       finally       for
function      if            import
in            instanceof    new
return        super         switch
this          throw         try
typeof        var           void
while         with          yield

JavaScript keywords

-do not use

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;

style CONVENTIONS

how most people style their JavaScript variables

start with a lowercase letter

var running = false;
var games = 0;

camelCase not dashes

var myTextVar = "my text var";
var currentGuess = 0;
var playerScore = 0;

More conventions here:

 

 

values & types

A value can be of a certain type

values & types

In real life you could see these values.

What types are they?

99:-

values & types

In JavaScript you could see these values.

What types are they?

104

"Hello World"

false

[1,2,3,4]

true

{age:4, height: 99}

types in JavaScript

3.14159
1337
42
"anything within double quotes"
'or single quotes'
"42" // even this is a string
// either
true
// or.. 
false

(primitive)

weird Primitive types

Two "nothing"-types

var nothing = null;

null

undefined

var nothingYet; // undefined

The value is null,

and the type is null

The value is undefined,

and the type is undefined

complex types

Arrays (subtype of object)

Objects

Functions

var car = {brand:"Chevy", color:"red"};
var fruits = ["apple", "banana", "cherry"];
function varName() {
    console.log("Hello");
    alert("world!")
}

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 , 

Mathematical operators

arithmetic operators, to be nerdy

40 + 2 // 42

44 - 2 // 42

21 * 2 // 42

84 / 2 // 42

Arithmetic expressions

Some Math functions

var pie = Math.PI // 3.1415926

var roundPie = Math.round(pie) // 3

var hiPie = Math.ceil(pie)     // 4

var lowPie = Math.floor(pie)   // 3

Three ways to round a number

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

What do you get when you combine a string with a number?

A strumber ...not

You get a string!

"4" + 2 is "42"

"U" + 2 is "U2"

String surprise #2

var age = 20

console.log("Next year you will be " + age + 1)

Why are we still not getting the expected results?

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

Count the characters

var flower = "Chrysanthemum"
var letters = flower.length

console.log(letters)

add .length right after the variable name

Booleans

true or false

Boolean

as a result of a comparison

42 == "Answer to everything"

== is a comparison* operator

This expression claims that 42 is equal to "Answer to everything"

The resolved value of this expression is

the boolean value false

* Actually the term is relational operator

Boolean expressions

Using different comparison operators

console.log( "cat" == "cat" ) // true
console.log( 5 < 10 )         // true
console.log( Math.PI > 4 )    // false
var myAge = 16
var oldEnough = myAge >= 18
console.log(oldEnough) // false

The not! operator

the opposite

var theTruth =  false != false // false
theTruth = !theTruth // true

Operators

COMMUNICATING

Using the browser's built in dialog windows

alert("This is an alert!")

prompt("What's your name")

returns the value as a string

confirm("Do you want to continue?")

returns true or false

Line breaks in alert 

alert("Good morning! \nToday is the first day\nof the rest of your life")

This also works for confirm() and prompt() of course

COMMUNICATING

Using the browser's built in developer console

var msg = "log your variables to console.log() to see their value here";
console.log(msg);
console.error("If your game isn't working you can see why in the console");

COMMUNICATING

By writing directly to the HTML

<body>
    <h1>Welcome!</h1>
    <script>
    document.write('<p>To this dynamic web page</p>');
    </script>
</body>
<body>
    <h1>Welcome!</h1>
    <p>To this dynamic web page</p>
</body>

write on the HTML page where the script tag is

using document.write(htmlCode)

COMMUNICATING

By manipulating the HTML

var myHtmlRef = document.querySelector('h1');

myHtmlRef.innerHTML = 'Hello, <b>world!</b>';
<body>
    <h1> <- Everything between these are innerHTML -> </h1>
</body>
<body>
    <h1>Hello, <b>world!</b></h1>
</body>

but more on this later

Conditional statements

if (destination == "Råslätt") {
  
    "Take the left path"
  
} else {
  
    "Take the right path"
  
}

The if statement

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

A test (boolean expression)

What is the value of points?

after the script has run

var points = 0
var skill = 3

if (skill > 3) {
  points = points + 1
}

console.log("Your current score is " + points)

The else statement

Can only follow an if-statement

var points = 0
var extra = confirm('want a point?') 

if ( extra ) {
  points = points + 1 // only if extra is true
  
} else {
    
  points  = points - 1 // only if extra is false
}

Otherwise

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

Till next time

  • read about loops in Chapter 1

  • read Chapter 2