Johan Kohlin
Lecturer at School of engineering, Jönköping University.
minus loops
Code is just text in a plain text file.
Just Like HTML and CSS
for short
ECMAScript is the standard upon which JavaScript is based, and it’s often abbreviated to ES.
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;
<!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>
-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;
-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
Don't worry,
We'll get back to that soon
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
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>
Alternative 1: write code in the HTML-document
<!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
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>
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.
Named memory slots
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
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
var height = 187;
This is a shorthand.
It first declares the variable height
Then assigns the value 187 to it.
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"
I will remember this as flower
"Chrysanthemum"
var flower = "Chrysathemum";
variable name
JS keyword:
-Define new variable
A value
work like placeholders or shortcuts to values
alert(flower);
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
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;
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:
A value can be of a certain type
In real life you could see these values.
What types are they?
99:-
In JavaScript you could see these values.
What types are they?
104
"Hello World"
false
[1,2,3,4]
true
{age:4, height: 99}
3.14159
1337
42
"anything within double quotes"
'or single quotes'
"42" // even this is a string
// either
true
// or..
false
(primitive)
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
Arrays (subtype of object)
Objects
Functions
var car = {brand:"Chevy", color:"red"};
var fruits = ["apple", "banana", "cherry"];
function varName() {
console.log("Hello");
alert("world!")
}
think math
It's a dot .
not a comma ,
arithmetic operators, to be nerdy
40 + 2 // 42 44 - 2 // 42 21 * 2 // 42 84 / 2 // 42
Arithmetic expressions
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
think text
(That means join)
var firstName = "John "
var lastName = "Doe"
var fullName = firstName + lastName
console.log(fullName) // "John Doe"
use + between strings to join them
var age = "20"
console.log(age + 1)
What's the result?
Why do you think?
Try different numbers
var age = 20
console.log("Next year you will be " + age + 1)
Why are we still not getting the expected results?
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
var flower = "Chrysanthemum"
var letters = flower.length
console.log(letters)
add .length right after the variable name
true or false
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
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 opposite
var theTruth = false != false // false
theTruth = !theTruth // true
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
alert("Good morning! \nToday is the first day\nof the rest of your life")
This also works for confirm() and prompt() of course
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");
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)
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
if (destination == "Råslätt") {
"Take the left path"
} else {
"Take the right path"
}
if (true == true) {
/* Code in this block
* Will only run if
* the test is true. */
}
A test (boolean expression)
after the script has run
var points = 0
var skill = 3
if (skill > 3) {
points = points + 1
}
console.log("Your current score is " + points)
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
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
read about loops in Chapter 1
read Chapter 2
By Johan Kohlin
Variables and types