Fun Fact: Operators like +, %, and = are called binary operators because they take two operands. The typeOf operator returns the type of data you call it on.
let s = "This is a string";
console.log(typeof s); // 'string'
let n = 6.28;
console.log(typeof n); // 'number'
let sum = function (a, b) {
return a + b;
};
console.log(typeof sum); // 'function'
let a = [1, 2, 3];
Array.isArray(a); // true
let n = 6.28;
Array.isArray(n); // false
let f = function () {};
Array.isArray(f); // false
The null type has one and only value: null.
The meaning of Null
The absence of a value
function reverseTheSentence(sentence) {
if (typeof sentence !== "string") {
return null;
}
let parts = sentence.split(" ");
parts.reverse();
return parts.join(" ");
}
Undefined is the only value of the undefined data type.
Tools to help handle certain exceptional code situations, such as hardware faults, gracefully.
There are only three ways of handling exceptions right now in pgroamming:
How it works is that when an error occurs, your Javascript interpreter will look for a handler to manage the error.
Try and Catch
function sumArray(array) {
let sum = 0;
try {
for (let i = 0; i < array.length; i += 1) {
sum += array[i];
}
} catch (e) {
console.log(e);
return null;
} finally {
console.log("you will always see this.");
}
return sum;
}
TypeError: Cannot read property 'length' of null
at sumArray (/tmp/file.js:5:31)
at Object.<anonymous> (/tmp/file.js:16:1)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
How can I make my own Errors?
You can create your own “errors” by creating an error object paired with an error message.
throw Error("this happened because I wanted it to");
throw new Error("this happened because I wanted it to");
How do I best use this?
function sumArray(array) {
if (array === null) {
return null;
}
let sum = 0;
for (let i = 0; i < array.length; i += 1) {
sum += array[i];
}
return sum;
}
Fun Fact: If you divide an integer with zero in JS you will output infinity or neg. infinity.
let guestList = ["Leonardo", "Michaelangelo", "Donatello", "Raphael"];
let queue = ["Bobby", "Donatello", "Raphael", "Tom"];
for (let i = 0; i < queue.length; i++) {
let person = queue[i];
try {
if (!guestList.includes(person)) {
throw new Error(person + "wasn't invited");
} else {
console.log("Welcome to the party," + person);
}
} catch (e) {
console.log(e.message);
} finally {
console.log("this always runs");
}
}