Tips and Tricks
Skipping in a loop
You can use continue to skip to the next iteration of a loop at any point. For example:
let settings = [];
for (let i = 1; i < 10; i++) {
let x = Cfg.get('script.str' + JSON.stringify(i));
if (x === "") {
continue;
// Execution will jump to next iteration if x is an empty string
}
settings.push(x);
}
Breaking out of a loop
You can use break to exit a loop early. For example:
let settings = [];
for (let i = 1; i < 10; i++) {
let x = Cfg.get('script.str' + JSON.stringify(i));
if (x === "") {
break;
// The loop will stop entirely when the first empty string is encountered
}
settings.push(x);
}
Joining two arrays
There is no built-in method to concatenate two arrays, but you can do it manually with a loop. For example:
let x = ['a', 'b'];
let y = ['c', 'd'];
for (let i = 0; i < y.length; i++) {
x.push(y[i]);
}
// 'x' is now ['a', 'b', 'c', 'd']
Default behaviour by using || and &&
Instead of using if statements for defaults, you can use logical operators:
let name = userInput || "Default Name";
If userInput is false-like (“”, null, undefined, 0, false), name defaults to “Default Name”.
Similarly, && can be used to execute a function only if a condition is true:
isLoggedIn && showDashboard();
If isLoggedIn is true, it calls showDashboard()
Ternary Operator for smaller conditionals
The Ternary operator can replace simple if-else statements: result = (condition) ? expressionIfTrue : expressionIfFalse;
Instead of:
let status;
if (value > 10) {
status = "High";
} else {
status = "Low";
}
Use:
let status = value > 10 ? "High" : "Low";
Dynamically referencing an element in an object
let i = 5;
let x = obj["hourmeter" + JSON.stringify(i) + "_hrs"];
is equivalent to:
let x = obj.hourmeter5_hrs;