Johan Kohlin
Lecturer at School of engineering, Jönköping University.
-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
var b = 20;
var c = 3;
var a = b * 2 + Math.round( c / 2 ) ;
ALL EXPRESSIONS MUST FIRST RESOLVE TO A VALUE before assigned
-start from the left (if possible)
var b = 20;
var c = 3;
var a = b * 2 + Math.round( c / 2 ) ;
variable expression
var b = 20;
var c = 3;
var a = 20 * 2 + Math.round( c / 2 ) ;
arithmetic expression
Math chip
var b = 20;
var c = 3;
var a = 40 + Math.round( c / 2 ) ;
litteral number expression
var b = 20;
var c = 3;
var a = 40 + Math.round( c / 2 ) ;
function call expression
var b = 20;
var c = 3;
var a = 40 + Math.round( c / 2 ) ;
arithmetic expression
var b = 20;
var c = 3;
var a = 40 + Math.round( c / 2 ) ;
variable expression
var b = 20;
var c = 3;
var a = 40 + Math.round( 3 / 2 ) ;
litteral number expression
var b = 20;
var c = 3;
var a = 40 + Math.round( 3 / 2 ) ;
arithmetic expression
var b = 20;
var c = 3;
var a = 40 + Math.round( 1.5 ) ;
litteral number expression
var b = 20;
var c = 3;
var a = 40 + Math.round( 1.5 ) ;
function call expression
var b = 20;
var c = 3;
var a = 40 + 2 ;
litteral number expression
var b = 20;
var c = 3;
var a = 40 + 2 ;
arithmetic expression
var b = 20;
var c = 3;
var a = 42 ;
litteral number expression
(can't be resolved further)
var b = 20;
var c = 3;
var a = 42 ;
assignment expression
<!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
named memory cells
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
let and const
Use them if you want to, but understand the difference from var
const yearOne = 1970
if (previousYear == 2018) {
let year = previousYear + 1
}
var previousYear = 2018 // var is hoisted
// the following will produce errors
yearOne = 1 // cannot re-assign a constant
console.log( year ) // year is forgotten
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;
usually go between two values
arithmetic operators, to be nerdy
40 + 2 // 42 44 - 2 // 42 21 * 2 // 42 84 / 2 // 42
Arithmetic expressions
the right side is assigned to the left side
cat = "tiger"
results in a boolean; true or false
42 == "42" // true 44 < 2 // false 21 >= 2 // true 84 != 2 // true "42" === 42 // false
results in a boolean; true or false
42 == "42" && Math.PI > 3 // true
42 === "42" || Math.PI > 3 // true
Both must be true for the expression to be true
Only one needs to be true for the expression to be true
var nmd = prompt("What year?")
var overall = confirm("Overall on?")
var vip = prompt("pass phrase?")
if ( overall == true && (vip =="42" || nmd == 1) )
AKA the if-statement
if (true == true) {
/* Code in this block
* Will only run if
* the test is true. */
}
A test (boolean expression)
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
var fruits = ["kiwi", "mango", "orange", "banana", "apple"];
var index = 0;
while (index < fruits.length) {
console.log( fruits[index] );
index++;
}
...as you know
break; //to exit
is a compressed form of while
run-later codeblocks
<body>
<button onclick="headsOrTails()">flip</button>
</body>
function headsOrTails() {
coin = Math.round(Math.random())
if (coin == 0) {
coin = "HEADS"
} else {
coin = "TAILS"
}
console.log(coin)
}
function area(width, height) { alert( width * height ) }
area(45, 20) // 900 area(10, 5) // 50
see page 90
var headsOrTails = function(bet) { var coin = Math.round(Math.random()) if (coin === bet) { console.log("you won!") } else { console.log("you lost.") } };
The entire function body is saved to memory
This is an alternative way to declare a function.
function scream(message) {
console.log( message.toUpperCase() );
}
var yell = scream;
yell("excuse me") // EXCUSE ME
var c = 4;
function half(num) {
return num/2;
alert('boo hoo, I will not popup');
}
var a = half( c * 3 ) ;
also quits the function.
return works like break in a loop. It will return a value and then stop reading the rest of the code in the function
see page 98-108
var gName = "Jane";
function printer() {
var name = "Tarzan";
verb = " loves "
console.log(name + verb + gName);
}
console.log(gName);
LOCAL
GLOBAL
If you forget the var keyword inside functions,
the variable will be declared in the global scope
Arrays
Objects
Functions
Numbers
Strings
Booleans
typeof 1337 // number
typeof "42" // string
typeof true // boolean
/* Put parentheses
* around expressions
*/
typeof ("20"+1) // string
typeof ("2" == 2) // boolean
Test the type of a value or expression
think math
It's a dot .
not a comma ,
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
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"
flower.length // 13 (characters)
flower.indexOf("y") // 3 (position)
flower.charAt(0) // "C"
flower.toUpperCase() // "CHRYSANTHEMUM"
flower.toLowerCase() // "chrysanthemum"
Billboard
0. Someone You Loved
1. Truth Hurts
2. Senorita
3. Circles
4. No Guidance
5. Panini
6. HIGHEST IN THE ROOM
7. Ran$om
8. Bad Guy
9. 10,000 Hours
var billboard = [
'Someone You Loved',
'Truth Hurts',
'Senorita',
'Circles',
'No Guidance',
'Panini',
'HIGHEST IN THE ROOM',
'Ran$om',
'Bad Guy',
'10,000 Hours'
];
billboard[3] // 'Circles'
But in javaScript 1'st place is 0
//populate it from the start:
var circles = ['green', 'green', 'green', 'green'];
// Built in method push, adds to the end of the array
circles.push('red');
// unshift, adds to the beginning of the array
circles.unshift('red');
//Specify a position
circles[4] = 'red';
// pop removes the last element
circles.pop();
// shift, removes the first element
circles.shift();
// weird quirk
circles.length --
// remove 1 at position 3
circles.splice(3,1);
fruits.sort(); // ["apple", "banana", "cherry"];
fruits.includes('cherry'); // true
fruits.indexOf('cherry'); // 0
var fruits = ["cherry", "banana", "apple"];
/******************************
Array.splice(2,1) means:
Go to index 2,
remove 1 item
and return it (as an array).
******************************/
var fishes = ["shark", "salmon", "dolphin", "cod"];
var mammals = fishes.splice(2, 1);
/******************************
fishes: ['shark', 'salmon', 'cod']
mammal: ['dolphin']
******************************/
literal syntax
var friend = {
name: "Jane Doe",
phone: "555-12345",
email: "jane@doe.com",
bff: true
};
var friend = {};
friend.name = "Jane Doe";
friend.phone = "555-12345";
friend.email = "jane@doe.com";
friend.bff = true;
dot notation
A.K.A. JavaScript Object Notation or JSON
brackets notation
alert( friend["name"] );
alert( friend.name );
dot notation
a keyword that refers to itself
var fruit = {
kind: "apple",
color: "red",
print: function() {
console.log( this.kind );
}
}
fruit.print();
this always refer to the object the function was called from. In this case print is called from fruit
function Gingerbread (text) {
this.decoration = text;
}
var cookie =
new
Gingerbread("Daniel");
{decoration:"Daniel"}
"Daniel", is passed to Gingerbread and assigned to the property decoration of the this new object
A function made to create new objects
function Gingerbread (text) {
this.decoration = text;
}
var cookie =
{decoration:"Daniel"}
The constructor call expression is resolved to a new object with a decoration property set to "Daniel"
and saved to the variable cookie
function Gingerbread (text) {
this.decoration = text;
}
var cookie = new Gingerbread("Daniel");
"Daniel"
cookie.decoration
function Car (color, brand) {
this.color = color;
this.brand = brand;
this.fuel = "diesel";
}
Car.prototype.present = function () {
console.log("This is a " + this.color + " " + this.brand)
}
var micra = new Car("white", "Nissan")
var m3 = new Car("black", "BMW")
micra.present() // This is a white Nissan
m3.present() // This is a black BMW
By Johan Kohlin
Repetition for the exam