2.18 JavaScript specials
code structure
alert('Hello'); alert('World');
alert('Hello')
alert('World')
alert("There will be an error after this message")
[1, 2].forEach(alert)
function f() {}
for (;;) {}
Strict mode
'use strict';
Variables
let
const
: constant, can’t be changed
var
: old style
- data types
number
: for both floating-point and integer numbers
bigint
: for integer numbers of arbitrary length,
string
: for strings,
boolean
: for logical value: true/false
null
- a type with a single value undefined
,
undefined
: a type with a single value undefined
, meaning
”not assigned”,
object
and symbol
: for complex data structures and unique identifiers, we haven’t learnt them yet.
- The
typeof
opertor returns the type for a value, with two exceptions:
typeoff null == "object"
typeof function() {} == "function"
Interaction
prompt(quesion, [default]);
confirm(question);
alert(message);
operators
- Arithmetical:
* + - / % **
- Assignments:
=
- Bitwise: 32-bit integers at the lowest (
| & ^
…)
- conditional
check ? A : B
- Logical operators
&& || !
- Nullish coalescing operator
a ?? b
- Comparisons
==
strict equality operator ===
alert( 0 == falsee );
alert( 0 == '');
Loops
while (condition) {
...
}
do {
...
}while ();
for (let i = 0; i < 10 ; i++) {
...
}
The “switch” construct
let age = prompt('Your age?', 18);
switch (age) {
case 18:
alert("Won't work");
break;
case "18":
alert("This works!");
break;
default:
alert("Any value not equal to one above");
}
Functions
function sum(a, b) {
let result = a + b;
return
}
let sum = function(a, b) {
let result = a + b;
return result;
};
let sum = (a, b) => a + b;
let sum = (a, b) => {
return a + b;
}
let sayHi = () => alert("Hello");
let double = n => n * 2;