5 Primitive Datatypes in JavaScript

Numbers
4
9.3
-10


Strings
"Hello World"
"43"
"i can't stop eating candy"
"she said \"goodbye!\""
"To see a backslash \\"


Booleans
true
false


null and undefined
null
undefined

Numbers

//Numbers

4
9.3
-10

//We can do some math
4 + 10 //14
1/5 //0.2

//Modulo - remainder operator
10 % 3 //1
24 % 2 //0
15 % 11 //4

Strings

//Single or Double quotes OK

"hello world"
'hello world'

//Concatenation
"charlie" + "brown" //"charliebrown"

//Escape Characters start with "\"
"Singin \"Do wah diddy, diddy, dum diddy do\" "
"This is a backslash: \\"

//Strings have a length property
"hello world".length //11

//Access individual characters using [] and an index
"hello"[0] //"h"
"hello"[4] //"o"

Manipulating style with JS

const div = document.createElement('div');
div.className = 'foo';

// our starting state:

console.log(div.outerHTML);
// use the classList API to remove and add classes
div.classList.remove("foo");
div.classList.add("anotherclass");

//

console.log(div.outerHTML);

// if visible is set remove it, otherwise add it
div.classList.toggle("visible");

// add/remove visible, depending on test conditional, i less than 10
div.classList.toggle("visible", i < 10 );

console.log(div.classList.contains("foo"));

// add or remove multiple classes
div.classList.add("foo", "bar", "baz");
div.classList.remove("foo", "bar", "baz");
// add or remove multiple classes using spread syntax
const cls = ["foo", "bar"];
div.classList.add(...cls);
div.classList.remove(...cls);

// replace class "foo" with class "bar"
div.classList.replace("foo", "bar");

Spread syntax

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.


function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
console.log(sum.apply(null, numbers));
// expected output: 6