1. Natively convert arrays to objects in JavaScript
JavaScript has a native function Object.fromEntries that can be used to convert any input array to an object.
1 .const anArray = [ 1 .
2. ['firstname', 'Paul'],
3. ['surname', 'Knulst'],
4. ['address', 'worldwide'],
5. ['role', 'Senior Engineer'],
6. ['followers', 'not much'],
7.];
8.
9.
10.const anObj = Object.fromEntries(anArray);
11.console.log(anObj);
12.// {
13.// firstname: 'Paul',
14.// surname: 'Knulst',
15.// address: 'worldwide',
16.// role: 'Senior Engineer',
17.// followers: 'not much'
18.// }
2. Recursively get the Fibonacci of a number
Recursion is a concept every software developer must know!
This JavaScript snippet shows the Fibonacci function implemented recursively.
1.const getFibonacci = (n, memo = {}) =>
2. memo[n] ||
3. (n <= 2
4. ? 1
5. : (memo[n] = getFibonacci(n - 1, memo) + getFibonacci(n - 2, memo)));
6.
7.
8.console.log(getFibonacci(4)); // 3
9.console.log(getFibonacci(8)); // 21
3. Check if your date is on the weekend
This JavaScript snippet shows how easy it is to check whether each Date object is a weekend.
You can change the week number (6 and 0) and replace it with any other weekday number to check for different days.
1.const isWeekend = (date) => date.getDay() === 6 || date.getDay() === 0;
2.
3.
4.console.log(isWeekend(new Date())); // false
5.console.log(isWeekend(new Date('2022-10-28'))); // false
6.console.log(isWeekend(new Date('2022-10-29'))); // true
4. Convert the 24-hour time format to am/pm
Working with different time formats is a pain.
This simple JavaScript snippet shows a function that converts any 24-hour time to am/pm time.
1.const toAMPMFormat = (h) =>
2. `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? ' am.' : ' pm.'}`;
3.
4.
5.console.log(toAMPMFormat(12)); // 12 pm.
6.console.log(toAMPMFormat(21)); // 9 pm.
7.console.log(toAMPMFormat(8)); // 8 am.
8.console.log(toAMPMFormat(16)); // 4 pm
5. Check if the property exists in the object
Sometimes you want to check whether attributes exist before printing or using them.
Instead of doing if property !== undefined before using it, JavaScript has a built-in function to do it.
1.const developer = {
2. name: 'Paul Knulst',
3. role: 'Tech Lead',
4. extra: 'Loves DevOps',
5. company: 'Realcore',
6. os: 'Windows',
7.};
8.
9.
10.const laptop = {
11. os: 'Windows',
12. buydate: '27.10.2022',
13. extra: 'looks cool',
14.};
15.console.log('name' in developer); // true
16.console.log('extra' in developer); // true
17.
18.
19.console.log('name' in laptop); // false
20.console.log('extra' in laptop); // true