8.1 Pseudorandom Numbers
Sometimes a programmer encounters seemingly simple tasks: "pick a random movie for the evening from a specific list", "select a lottery winner", "shuffle a playlist when shaking a smartphone", "choose a random number for encrypting a message", and each time they face a very reasonable question: how do you get that random number, anyway?
Actually, if you need a "true random number," it's pretty tough to get one. To the point where they even build special mathematical coprocessors into computers that can generate such numbers, meeting all the requirements for "true randomness".
So programmers came up with their own solution — pseudorandom numbers. Pseudorandom numbers are a sequence of numbers that seem random at first glance, but upon closer inspection by an expert, certain patterns can be found. They're not suitable for encrypting confidential documents, but they're perfect for simulating dice rolls in a game.
There are lots of algorithms for generating a sequence of pseudorandom numbers, and almost all of them generate the next random number based on the previous one and some other auxiliary numbers.
For example, this program will print 1000 unique numbers:
let a = 41;
let c = 11119;
let m = 11113;
let seed = 1;
function getNextRandom() {
seed = (a * seed + c) % m;
return seed;
}
for (let t = 0; t < 1000; t++) {
let x = getNextRandom();
console.log(x);
}
By the way, we're not talking about pseudorandom numbers, but specifically about a sequence of such numbers, because by looking at a single number, you can't tell if it's random or not.
There are different ways to get a random number:
function getNextRandom() {
return 4; # definitely a random number (I rolled dice)
}
8.2 The switch Operator
The switch statement is used to execute one of several blocks of code depending on the value of an expression. It's especially useful when you need to compare one value against several possible options.
Syntax:
switch(expression) {
case value1:
// code that executes if expression === value1
break;
case value2:
// code that executes if expression === value2
break;
// ...
default:
// code that executes if no values match
}
Example:
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName); // "Wednesday"
8.3 The ?? Operator
The ?? operator, or nullish coalescing operator, is used to assign a default value if the left operand is null or undefined. It prevents the application of a default value for other falsy values like 0, false, or an empty string ("").
Syntax:
let result = value1 ?? value2;
If value1 is not null or undefined, result will be value1. Otherwise, result will be value2.
Examples:
let foo = null ?? 'default';
console.log(foo); // 'default'
let bar = 0 ?? 'default';
console.log(bar); // 0 (0 is neither null nor undefined)
let baz = undefined ?? 'default';
console.log(baz); // 'default'
Difference from Logical OR (||)
The || operator can also be used to set a default value, but it returns the right operand for any falsy values such as 0, "", or NaN.
Comparison Example:
let value = 0 || 'default';
console.log(value); // 'default' (because 0 is a falsy value)
let value2 = 0 ?? 'default';
console.log(value2); // 0 (because 0 is neither null nor undefined)
Usage
The ?? operator is useful in situations where you need to set a default value only for null or undefined, while preserving falsy values like 0 or "".
Real-world Usage Examples
Example 1. Default values in configuration objects:
function configure(settings) {
settings = settings ?? {};
let timeout = settings.timeout ?? 1000;
let color = settings.color ?? 'blue';
// remaining configuration logic
}
Example 2. Default parameters for functions:
function printMessage(message) {
message = message ?? 'No message provided';
console.log(message);
}
printMessage(null); // 'No message provided'
printMessage('Hello'); // 'Hello'
Using the ?? operator allows for cleaner and more predictable code, especially in situations where only the absence of a value (null or undefined) is important.
GO TO FULL VERSION