Introduction to Javascript

Redi School Munich - Spring 2021

Javascript...

...is not Java 😁

...was created in ten days.

...is the most commonly used programming language in the world.

Let's play a game

Recap: Button

MDN: <button>

Not very spectacular yet

Let's give it some action

Look, mum, no hands!


                <!DOCTYPE html>
                <html>
                  <head>
                    <title>Button</title>
                    <script>
                      alert("I appear upon page load");
                    </script>
                  </head>
                  <body>
                    <h1>Javascript</h1>
                  </body>
                </html>
              

External scripts

index.html

                  <!DOCTYPE html>
                  <html>
                    <head>
                      <title>Button</title>
                      <script src="script.js"></script>
                    </head>
                    <body>
                      <h1>Javascript</h1>
                    </body>
                  </html>
                
script.js

                  alert("Hello World");
                

Preferred method, because this keeps markup and logic separate

Recap: Developer Tools

Keyboard shortcut: F12

Developer Console

Developer Console

Language Basics:

Variables

Variables

MDN: Declarations

              // Variable declaration:
              let question;

              // Variable assignment:
              question = "What's the answer to the ultimate question of life, "
                       + "the universe and everything?";

              // Declaration and assignment
              let answer = 42;
            

Two (or three) different ways of declaring variables


              let myVariable = "I can be changed";
              myVariable = "New value"; // Works fine

              const myConstant = "I cannot be changed";
              myConstant = "New value"; // Throws an error!
            
The old way of declaring variables:

                var myVariable = "This is a variable";
                myVariable = "newValue";
              

Logging

MDN: console.log()

console.log() can be used to print any value into the developer console.


              let person1 = "Alice";
              let person2 = "Bob";

              console.log(person1);
              console.log("The name of the second person is " + person2);
            
Console Log

Primitive Data Types

MDN: Primitive Data Types
String

                  let myString = "Bob";
                
Number

                  let myNumber = 12.5;
                
Boolean

                  let myBoolean = true; // two possible values: true / false
                
Undefined

                  let myUndefined = undefined; // only possible value
                

Furthermore, there are Object, Function, BigInt and Symbol.

The typeof Operator

MDN: typeof

Returns the data type of an expression.


              const myString = "Charlie";
              const myBoolean = false;

              console.log(typeof myString);  // ==> string
              console.log(typeof myBoolean); // ==> boolean
              console.log(typeof 123);       // ==> number
            

Language Basics:

Comments

Comments

  • Purely informational for the developer
  • Two types: single-line and block comments

              // This is a single-line comment

              /*
                Everything in between
                is a comment
              */
            

Language Basics:

Operators

Operators

MDN: Expressions and Operators

Symbols that produce a result based on one or more input values.
A small selection:


              // Addition (numbers): +
              console.log(6 + 9);                // ==> 15

              // Concatenation (strings): +
              console.log("Hello " + "world");   // ==> "Hello World"

              // Subtraction, Multiplication, Division: - * /
              console.log(9 - 3);                // ==> 6
              console.log(8 * 2);                // ==> 16
              console.log(9 / 3);                // ==> 3
            

Implicit Type Conversion

MDN: Type conversion

If the types of two values used for an operator mismatch, or the types don't match the operator's expectation, Javascript guesses which type to use.


              // string + number = string
              console.log("4" + 2);        // ==> "42"

              // string * number = number
              console.log("4" * 2);        // ==> 8

              // boolean + boolean = number
              console.log(true + false);   // ==> 1

              // boolean + string = string
              console.log(true + "false"); // ==> "truefalse"
            

👉 Make sure your variables have the right type. Use typeof if you don't know their type.

Explicit Type Conversion

If you need to convert a variable from one type to another, you can use a Primitive Wrapper


              let age = prompt("How old are you? Type a number");

              console.log(age);           // ==> "30"
              console.log(typeof age);    // ==> string

              age = Number(age);     // converting to number

              console.log(age);           // ==> 30
              console.log(typeof age);    // ==> number

              age = String(age);     // converting back to string

              console.log(age);           // ==> "30"
              console.log(typeof age);    // ==> string
            

Language Basics:

Conditionals

Conditionals

Syntax:


              if ( /* condition */ ) {
                /* code that runs when condition is true */
              }
            

The condition can be any expression which returns a boolean.


              if (true) {
                console.log("I always run");
              }

              if (false) {
                console.log("I never run");
              }
            

Conditionals


              const passwordEntry = prompt("What is the password?");

              if (passwordEntry === "hunter2") {
                alert("You now have access to my super secret area!");
              }
            

=== is the strict equality operator. It returns true, if both arguments are matching types and values.


                console.log(5 === 5);      // ==> true
                console.log(8 === 2 * 4);  // ==> true
                console.log("5" === 5);    // ==> false
              

By contrast, the loose equality operator == allows for implicit type conversion before comparing values


                console.log(5 == 5);       // ==> true
                console.log("5" == 5);     // ==> true  (different types, but same value after type conversion)
                console.log("3" == 5);     // ==> false (different types and values)
              

Negative Case: else

Syntax:


              if ( /* condition */ ){
                /* code that runs when condition is true */
              } else {
                /* code that runs when condition is false */
              }
            

Negative Case: else


              const pizzaTopping = prompt("What do you like on your pizza: 🍕");

              if (pizzaTopping !== "pineapples") {
                alert("Yum! I love pizza with " + pizzaTopping);
              } else {
                alert("Eeew how could you?");
              }
            

!== is the strict inequality operator. It does the opposite of ===


                console.log(5 !== 5);            // ==> false
                console.log("Alice" !== "Bob");  // ==> true
                console.log("20" !== 20);        // ==> true
              

Conditionals with more than two branches


              const input = prompt("Ask me about what the names of some coding languages mean");

              if (input === "html") {
                alert("HTML stands for HyperText Markup Language");
              } else if (input === "css") {
                alert("CSS stands for Cascading Style Sheets");
              } else if (input === "javascript") {
                alert("Javascript is just Javascript");
              } else {
                alert("I don't know the language " + input);
              }
            

Some more operators

All of these can be used as conditions for if statements

Language Basics:

Functions

Functions

MDN: Functions

  • Reusable sub-routines that are stored with a name
  • Javascript comes with many built-in functions

Syntax for calling a function:


              name_of_the_function( /* 0 - n comma-separated arguments */ );
            

Some functions that we already saw:


                alert(message);
                console.log(value);
                prompt(question);
              

Return values

Functions may return a value, which we can then process further


              let answer = prompt("Question");
            

Making our own functions

Function declaration syntax:


              function myFunction(firstArgument, secondArgument) {
                /* function logic */
              }
            

Making our own functions


              function multiply(num1, num2) {
                let result = num1 * num2;
                return result;
              }
            

The return statement passes on a value to the caller.
The function stops at this point.


              console.log(multiply(3, 5));  // ==> 15

              const product = multiply(4, 4);
              console.log(product);         // ==> 16
            

Making our own functions


              function multiply(num1, num2) {
                let result = num1 * num2;
                return result;
              }
            

All other variables declared inside the function are discarded.


              console.log(multiply(6, 3));  // ==> 18
              console.log(result);          // ==> ReferenceError: result is not defined
              console.log(num1);            // ==> ReferenceError: num1 is not defined
              console.log(num2);            // ==> ReferenceError: num2 is not defined
            

Making our own functions

The return statement is optional. Both of these examples are valid and return nothing:


              // Assuming someOtherFunction() exists
              function myFunction1() {
                someOtherFunction();

                return;
              }

              function myFunction2() {
                someOtherFunction();
              }
            

              console.log(myFunction1());  // ==> undefined
            

Document Object Model

Javascript's interface for interacting with HTML

MDN: Document Object Model

Query Selector

MDN: Document.querySelector()

Select an HTML element using CSS-selectors in Javascript

query-selectors.html

                      <!DOCTYPE html>
                      <html>
                        <head>
                          <title>Query Seletctors</title>
                          <script src="query-selectors.js" defer>
                          </script>
                        </head>
                        <body>
                          <h1>Query Selectors</h1>
                        </body>
                      </html>
                    
query-selectors.js

                      let heading = document.querySelector("h1");

                      heading.innerHTML = "Changed";

                      console.log(heading);
                    

Element.innerHTML lets us access and change the element's content.

Putting all of it together


                <script>
                  function changeImage() {
                    const imgElement = document.querySelector("#catImage");

                    if (imgElement.attributes.src.value === "images/cat1.jpg") {
                      imgElement.attributes.src.value = "images/cat2.jpg";
                    } else if (imgElement.attributes.src.value === "images/cat2.jpg") {
                      imgElement.attributes.src.value = "images/cat3.jpg";
                    } else {
                      imgElement.attributes.src.value = "images/cat1.jpg";
                    }
                  }
                </script>

                <!-- ... -->

                <button type="button" onClick="changeImage()">Change Image</button>
                <img src="images/cat1.jpg" id="catImage" alt="Cat"/>
              

Debugging Code

Debugger

Meet the Debugger

Two ways of starting the debugger:

Breakpoints
Breakpoint in the debugger
The debugger keyword
debugger;

allows you to pause any script and execute it step by step.

Language Basics:

Loops

Loops

Two commonly used types:

  • while
  • for

while

MDN: while

Syntax:


              while ( /* condition */ ) {
                /* code to run repeatedly while condition is true */
              }
            

The syntax of while-loops is similar to that of if-statements:


                if ( /* condition */ ) {
                  /* code to run if condition is true */
                }
              

while

sum += number;

is equivalent to

sum = sum + number;
number++;

is equivalent to

number = number + 1;

The break keyword

Stops the execution of a loop regardless of the condition

for

MDN: for

Syntax:


              for ( /* initialization */; /* condition */; /* final expression */) {
                /* code to be run while condition is true */
              }
            

for

Every for loop can be rewritten as a while loop

Language Basics:

Arrays

Arrays

MDN: Array

  • Variable type that holds multiple values
  • Useful when handling a larger, possibly even unknown amount of similar objects

Array initialization

Empty array


              let myArray = [];
            

Non-empty array


              let myArray = ["first value", "second value", "third value"];
            

Arrays aren't primitive types, therefore the typeof operator returns "object".
To check whether a variable is an array, use Array.isArray().


                let myArray = [1, 2, 3];
                console.log(typeof myArray);         // ==> "object"
                console.log(Array.isArray(myArray)); // ==> true
              

Accessing array elements


              let zooAnimals = ["giraffe", "zebra", "lion"];

              // Array indexes start at 0
              console.log(myArray[0]);  // ==> "giraffe"
              console.log(myArray[1]);  // ==> "zebra"
              console.log(myArray[2]);  // ==> "lion"

              myArray[0] = "tortoise";

              console.log(myArray[0]);  // ==> "tortoise"
            

Adding and removing elements

MDN: push and pop


              let cakeIngredients = ["eggs", "flour", "sugar"];

              cakeIngredients.push("chocolate");

              console.log(cakeIngredients);    // ==> ["eggs", "flour", "sugar", "chocolate"]

              let ingredient = cakeIngredients.pop();

              console.log(ingredient);         // ==> "chocolate";
              console.log(cakeIngredients);    // ==> ["eggs", "flour", "sugar"];
            

Iterating through arrays

Output in both cases:

A practical example

arrays.html

                      <!DOCTYPE html>
                      <html lang="en">
                      <head>
                        <title>Arrays</title>
                        <script src="arrays.js" defer></script>
                      </head>
                      <body>
                        <a href="#">Regular link</a>
                        <a href="https://google.com">External link</a>
                        <a href="otherpage.html">Regular link</a>
                        <a href="https://bing.com">External link</a>
                      </body>
                      </html>
                    
arrays.js

                      const externalAnchors =
                        document.querySelectorAll('a[href^="https://"]');

                      for (let anchor of externalAnchors) {
                        anchor.target = "_blank";
                      }
                    

Questions / Feedback?