Redi School Munich - Spring 2021
...is not Java 😁
...was created in ten days.
...is the most commonly used programming language in the world.
<!DOCTYPE html> <html> <head> <title>Button</title> </head> <body> <button type="button"> Click me! </button> </body> </html>
Not very spectacular yet
<!DOCTYPE html> <html> <head> <title>Button</title> </head> <body> <button type="button" onclick="alert('Hello World!')"> Click me! </button> </body> </html>
alert()
is a functiononclick
is an event handler<!DOCTYPE html> <html> <head> <title>Button</title> <script> alert("I appear upon page load"); </script> </head> <body> <h1>Javascript</h1> </body> </html>
<!DOCTYPE html> <html> <head> <title>Button</title> <script> alert("I appear upon page load"); </script> </head> <body> <h1>Javascript</h1> </body> </html>
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
Keyboard shortcut: F12
Language Basics:
// 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;
// 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;
// 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;
// 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;
let myVariable = "I can be changed"; myVariable = "New value"; // Works fine const myConstant = "I cannot be changed"; myConstant = "New value"; // Throws an error!
let myVariable = "I can be changed"; myVariable = "New value"; // Works fine const myConstant = "I cannot be changed"; myConstant = "New value"; // Throws an error!
let myVariable = "I can be changed"; myVariable = "New value"; // Works fine const myConstant = "I cannot be changed"; myConstant = "New value"; // Throws an error!
let myVariable = "I can be changed"; myVariable = "New value"; // Works fine const myConstant = "I cannot be changed"; myConstant = "New value"; // Throws an error!
var myVariable = "This is a variable"; myVariable = "newValue";
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);
String |
|
Number |
|
Boolean |
|
Undefined |
|
Furthermore, there are Object
, Function
, BigInt
and Symbol
.
typeof
OperatorReturns 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:
// This is a single-line comment
/*
Everything in between
is a comment
*/
Language Basics:
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
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.
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:
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");
}
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)
else
Syntax:
if ( /* condition */ ){
/* code that runs when condition is true */
} else {
/* code that runs when condition is false */
}
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
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);
}
All of these can be used as conditions for if
statements
// Comparison - Greater Than: >
console.log(10 > 8); // ==> true
console.log(8 > 8); // ==> false
// Comparison - Greater Than or Equal: >=
console.log(9 >= 9); // ==> true
console.log(3 >= 9); // ==> false
// Comparison - Less Than: <
console.log(5 < 3); // ==> false
// Comparison - Less Than or Equal: <=
console.log(3 <= 3); // ==> true
Language Basics:
MDN: 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);
Functions may return a value, which we can then process further
let answer = prompt("Question");
Function declaration syntax:
function myFunction(firstArgument, secondArgument) { /* function logic */ }
function myFunction(firstArgument, secondArgument) { /* function logic */ }
function multiply(num1, num2) { let result = num1 * num2; return result; }
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
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
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
Javascript's interface for interacting with HTML
MDN: Document Object ModelSelect 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.
<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"/>
<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"/>
<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"/>
Two ways of starting the debugger:
debugger
keyworddebugger;
allows you to pause any script and execute it step by step.
Language Basics:
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
let sum = 0;
let number = 1;
while (number <= 100) {
sum += number;
number++;
}
console.log(sum); // ==> 5050
sum += number;
is equivalent to
sum = sum + number;
number++;
is equivalent to
number = number + 1;
break
keywordStops the execution of a loop regardless of the condition
let number = 0;
while (number < 10) {
number++;
if (number >= 5) {
break;
}
}
console.log(number); // ==> 5
for
MDN: for
Syntax:
for ( /* initialization */; /* condition */; /* final expression */) {
/* code to be run while condition is true */
}
for
function factorial(number) {
let product = 1;
for (let i = 1; i <= number; i++) {
product *= i;
}
return product;
}
console.log(factorial(5)); // ==> 120
for
loop can be rewritten as a while
loopfor (let i = 1; i <= number; i++) {
product *= i;
}
let i = 1;
while (i <= number) {
product *= i;
i++;
}
Language Basics:
MDN: Array
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
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"
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"];
let myArray = ["foo", "bar", "baz"];
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
// Alternatively:
for (let element of myArray) {
console.log(element);
}
Output in both cases:
"foo"
"bar"
"baz"
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";
}