Javascript primitives and types
"Whenever there is a divergence between what your brain thinks and what is actually happening in the computer, that's where bugs enter the code."
(Kyle Simpsons)
"everything in JS is an object"
"everything in JS is an object"
- undefined
- null
- boolean
- number
- string
- bigint
- symbol
"everything in JS is an object"
- undefined
- null
- boolean
- number
- string
typeof
typeof
typeof true; // "boolean"
typeof 42; // "number"
typeof 'kiskutya'; // "string"
typeof null; // "null"
typeof undefined; // "undefined"
Non-objects?
Non-objects?
myName = "Kyle";
myName.nickname = "getify";
console.log(myName.nickname) // undefinedNon-objects?
'use strict'
myName = "Attila";
myName.nickname = "Csati";
console.log(myName.nickname)
// TypeError: Cannot create property 'nickname'
// on string 'Attila'Empty Values
Empty Values
- undefined
- null
Null'ish
function joinTexts(...args) {
return args.filter((arg) => arg != null).join(' ');
}Null'ish
who = myName ?? "User";Null'ish
record = {
shippingAddress: {
street: "123 JS Lane",
city: "Browserville",
state: "XY"
}
};
console.log( record?.shippingAddress?.street );
console.log( record?.billingAddress?.street );
Null'ish
(Please don't use it like this)
someFunc?.(42);„non-null assertion operator”
aka (! postfix)

Difference
function greet(msg = "Hello") {
console.log(msg);
}
greet();
greet(undefined);
greet("Hi");
greet(null);Bonus
undefined - undeclared - uninitialized
Boolean
// isLoggedIn = 1;
isLoggedIn = true;
isComplete = 0;
// isComplete = false;
// how to use it:
if (isLoggedIn) {
// do something
}
while (!isComplete) {
// keep going
}
console.log(isLoggedIn === true)
console.log(isComplete == false)Number
Number
Number.isInteger(42);
Number.isInteger(42.0);
Number.isInteger(42.000000);
Number.isInteger(42.0000001);Number.isInteger(num);
Number
Parsing vs Coercion
Number
Parsing
parseInt(someNumericText,10)
parseFloat(someNumericText)
someNumericText = "123.456";
parseInt(someNumericText,10); // 123
parseFloat(someNumericText); // 123.456
parseInt("42",10) === parseFloat("42"); // true
parseInt("512px"); // 512Number
Coercive
Number(num)
someNumericText = "123.456";
Number(someNumericText); // 123.456
+someNumericText; // 123.456
Number("512px"); // NaN
+"512px"; // NaNlet num1 = "10";
let num2 = 5;
let result = num1 + num2;NaN
typeof NaNNaN
NaN === NaN;
NaN
politicianIQ = "nothing" / Infinity;
Number.isNaN(politicianIQ); // true
Object.is(NaN,politicianIQ); // true
[ NaN ].includes(politicianIQ); // trueways to check if the value is NaN
String
Skipped parts
-
JS Character Encodings, Multi-Character Escapes...
- Other Numeric Representations, Bitwise Binary Representations
Javascript primitives and types
By Mutti Tutti
Javascript primitives and types
- 32