Full explanations on: https://www.w3schools.com/js/js_let.asp Cheat Sheet: https://htmlcheatsheet.com/js/

Demo JavaScript in Head

Placing scripts at the bottom of the <body> element improves the display speed, because script interpretation slows down the display.

This text will change at the click of a button!

When you use quotes inside quotes, they need to be different from each other, ie. ’ and “.

Images and how to change them

JavaScript can change HTML attribute values.

In this case JavaScript changes the value of the src (source) attribute of an image.

External scripts

External scripts are practical when the same code is used in many different web pages. src=“myScript.js" Those scripts can’t contain the script-tag.

JS Output

JavaScript can “display” data in different ways:

The window keyword for displaying stuff is optional, so window.alert and alert will procude the same result.

JS Code

JavaScript statements can be grouped together in code blocks, inside curly brackets {…}. Code Blocks are executed together, like in a function

Important distinction: var creates a variable to be used immediately. let creates a variable that is available globally.

JS operators

The operators are basically the same as in R. With +=, you can assign an added value. So if x and y are numbers, then x += y; stores their sum in x. Analagously, *= assigns a product. It is also an easy way to concatenate text like this: text += cars[i] + “
”;

JS Objects

objects are assigned with eg. const and live in curly brackets. They are later accessed with a . instead of the $ in R.

Arrays are assigned like const cars = [“Saab”, “Volvo”, “BMW”];.
CAVE: javaScript begins arrays at element 0.

JS conditionals

There is apparently no ifelse in JS. Instead, notation for the conditional/ ternary operator is as follows:

var variable = (condition) ? “If true” : “If false”;

== checks equal value, === checks equal value and equal type The ?? operator returns the first argument if it is not nullish (null or undefined). Otherwise it returns the second.

HTML Dom

getElementById changes the properties (like text) of a paragraph with a specific Id. document.getElementsByTagName(“p”)[0].innerHTML would change the first element with a

tag document.getElementsByClassName(“test”)[0].innerHTML changes the first element of class “test” document.getElementById(“demo”).style.color = “red”; changes the fontcolor of the text in paragraoh with id “demo”

Sets and Maps

new Set() Creates a new Set
add() Adds a new element to the Set
delete() Removes an element from a Set
has() Returns true if a value exists in the Set
forEach() Invokes a callback for each element in the Set
values() Returns an iterator with all the values in a Set
size Returns the number of elements in a Set (property)

JS Operators

You can check the constructor property to find out if an object is an Array (contains the word “Array”).