Primitives
JavaScript provides eight basic data types:
- Boolean represents truth values:
true
orfalse
. - Number represents integer numbers or a floating-point number.
- BigInt represents integers beyond the integer limit.
- Null indicates the absence of an object.
- String represents textual data.
- Symbol represents an immutable and unique primitive value.
- Undefined indicates the absence of a value.
- Object, the non-primitive, complex data type.
All types except Object
define immutable values represented directly at the lowest level of the language.
We refer to values of these types as primitive values.
Boolean
console.log(58 > 42) // true
console.log(true && false) // false
console.log(!false) // true
Number
console.log(58 + 42) // 100
console.log(5 * 4.8) // 24
BigInt
A BigInt is created by appending n to the end of an integer or by calling the BigInt()
function.
// BigInt
const x = BigInt(Number.MAX_SAFE_INTEGER); // 9007199254740991n
console.log(x + 1n === x + 2n);
// false because 9007199254740992n and 9007199254740993n are unequal
// Number
console.log(Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2);
// true because both are 9007199254740992
Null
The null
value represents the intentional absence of any object value.
function getVowels(str) {
// `/[aeiou]/gi` is a regex
const m = str.match(/[aeiou]/gi);
// `m` can be an object or `null`
if (m === null) {
return 0;
}
return m.length;
}
console.log(getVowels('sky'));
// Expected output: 0
String
The String
type represents textual data and is encoded as a sequence of 16-bit unsigned integer values representing UTF-16 code units.
let a = 'Hello'
let b = "Literank"
console.log(a) // Hello
console.log(a + " " + b) // Hello Literank
const c = "foo";
const d = "foo";
console.log(c === d); // true
console.log("foo" === "foo"); // true
Symbol
A Symbol
is a unique and immutable primitive value and may be used as the key of an Object
property.
const sym1 = Symbol();
const sym2 = Symbol("foo");
const sym3 = Symbol("foo");
console.log(sym2 === sym3); // false
console.log(Symbol("foo") === Symbol("foo")); // false
Undefined
JavaScript usually defaults to undefined
when something is devoid of a value.
function test(t) {
if (t === undefined) {
return 'Undefined value!';
}
return t;
}
let x;
console.log(test(x)); // Undefined value!
Code Challenge
Write a function
checkUndefined
that takes an array of values as input and returns a new array containing only the elements that are notundefined
.Don't worry about the
array
now, it will be introduced later.