![]() |
VOOZH | about |
We’re so glad you’re here. You can expect all the best TNS content to arrive Monday through Friday to keep you on top of the news and at the top of your game.
Check your inbox for a confirmation email where you can adjust your preferences and even join additional groups.
Follow TNS on your favorite social media networks.
Become a TNS follower on LinkedIn.
Check out the latest featured and trending stories while you wait for your first TNS newsletter.
Console.log Techniques: Logging Like a Proconst student = { name: 'Ray', age: 20 };
const tutor = { name: 'Peter', age: 40 };
console.log(student); console.log(tutor);While this works, it’s harder to distinguish between the logs, especially when dealing with multiple variables. Now, let’s explore cleaner alternatives.
console.log({ student, tutor });
//This prints
{ student: { name: 'Ray', age: 20 }, tutor: { name: 'Peter', age: 40 } }
Now the log is self-explanatory, clear and easier to inspect — perfect for debugging or reviewing nested data structures.
console.log('%c student', 'color: orange; font-weight: bold');
This is especially useful in large applications where you need to visually separate logs from one another, such as highlighting warnings, steps or critical state updates.
console.table([student, tutor]);This logs a structured table with rows and columns, making it easy to scan and compare values. It’s ideal when you’re working with datasets like API responses, lists of users or status objects.
console.time('loop');
let i = 0;
while (i < 1000000) {
i++;
}
console.timeEnd('loop');
//This will print something like
loop: 5.384ms
This gives you insight into how long your logic takes to execute, helping with optimization decisions or detecting bottlenecks in your code.
By mastering these enhanced logging techniques, you’re not just printing data — you’re communicating intent, improving readability and debugging smarter. These tools are part of your JavaScript utility belt, helping you become more efficient, organized and effective in your development workflow.
//Basic String Interpolation
const name = 'Ray';
const age = 20;
console.log(`My name is ${name} and I am ${age} years old.`);
Instead of writing:
'My name is ' + name + ' and I am ' + age + ' years old.'
Template literals let you inject variables directly into your string using `${}`. This not only reduces clutter but also boosts readability and maintainability.
// Multiline Strings (No \n Needed!) const message = `Hello, This is a multiline message, Neatly written with template literals.`; console.log(message);Previously, you’d have to use `\n` or concatenate lines awkwardly. With backticks, you just write across lines naturally.
//Expressions and Function Calls Inside Template Literals
const price = 100;
const discount = 0.2;
console.log(`Final price after discount: ${price - (price * discount)} UGX`);
You can even call functions inside:
function greet(name) {
return `Hello, ${name.toUpperCase()}!`;
}
console.log(`${greet('ray')}`);
Template literals make your code more expressive and cleaner, especially in scenarios involving dynamic data, API responses or logging. Whether you’re crafting UI messages, generating reports or debugging output, this feature adds elegance and power to your strings.
// Bad Code – Using forEach() for Totals
const cart = [
{ item: 'Book', price: 15 },
{ item: 'Pen', price: 5 },
{ item: 'Notebook', price: 10 },
];
let total = 0;
cart.forEach(product => {
total += product.price;
});
console.log(`Total price: ${total} UGX`);
This approach works, but it’s verbose, especially in large codebases. You’re manually managing the total, which can lead to errors and side effects.
const cart = [
{ item: 'Book', price: 15 },
{ item: 'Pen', price: 5 },
{ item: 'Notebook', price: 10 },
];
const total = cart.reduce((acc, curr) => acc + curr.price, 0);
console.log(`Total price: ${total} UGX`);
Here’s why `reduce()` is superior:
const total = cart.reduce((sum, { price }) => sum + price, 0);
This version uses destructuring to directly access the price of each item, making the code more readable.
So next time you’re summing values in an array, ditch the loop and reach for `reduce()`. It’s the functional way to write logic that’s not just correct, but clean and powerful.
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6];Here’s the old-school approach using `concat()`:
const merged = arr1.concat(arr2); console.log(merged); // [1, 2, 3, 4, 5, 6]This works, but it’s a bit verbose and less readable compared to modern syntax. And here’s the modern approach using the spread operator:
const merged = [...arr1, ...arr2]; console.log(merged); // [1, 2, 3, 4, 5, 6]The new method is much cleaner, more expressive and easier to understand. You’re literally just saying: “Spread the values of arr1 and arr2 into one new array.” In case of duplicates, merge with
Set and the spread operator.
Let’s assume the arrays have duplicate values:
const arr1 = [1, 2, 3, 3]; const arr2 = [3, 4, 5, 6, 6];If we merge them directly:
const merged = [...arr1, ...arr2]; console.log(merged); // [1, 2, 3, 3, 3, 4, 5, 6, 6]We now have duplicate values. In many cases (like IDs, tags, etc.), we want unique values. So to remove the duplicate values, we can use
Set and the spread operator.
const uniqueMerge = [...new Set([...arr1, ...arr2])]; console.log(uniqueMerge); // [1, 2, 3, 4, 5, 6]To give you context, `Set` is a built-in object that only stores unique values. We first use […] to merge the arrays. We then wrap it with `new Set(…)` to filter out duplicates, and finally, we spread that back into a new array.
const original = [10, 20, 30]; const copy = [...original]; copy.push(40); console.log(original); // [10, 20, 30] ✅ Unchanged console.log(copy); // [10, 20, 30, 40]
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(5, 10, 15, 20)); // 50
Explanation:
const colors = ['red', 'green', 'blue', 'yellow']; const [primary, secondary, ...others] = colors; console.log(primary); // red console.log(secondary); // green console.log(others); // ['blue', 'yellow']Explanation:
const user = {
id: 1,
name: 'Ray',
age: 25,
role: 'developer'
};
const { name, ...rest } = user;
console.log(name); // 'Ray'
console.log(rest); // { id: 1, age: 25, role: 'developer' }
const me = {
name: 'Ray',
age: 20,
likes: ['football', 'racing']
};
Traditional Way (Less Elegant)
If you want to access values, you’d typically do:
console.log(me.age); // 20 console.log(me.likes[0]); // 'football'While this works just fine, it can become verbose or repetitive, especially when you need to reference the same property multiple times. Now Let’s Use Destructuring for Cleaner Code Instead of repeatedly writing `me.age`, you can destructure like this:
const { age } = me;
console.log(age); // 20
You can also extract multiple properties at once:
const { name, likes } = me;
console.log(name); // 'Ray'
console.log(likes); // ['football', 'racing']
const { likes: [first, second] } = me;
console.log(first); // 'football'
console.log(second); // 'racing'
Notice how we used an alias. We didn’t extract the `likes` array itself, but instead unpacked its elements directly into `first` and `second`.
const age = 0; const result = age || 18; console.log(result); // 18 ❌ (0 is falsy, so it falls back)With nullish coalescing:
const age = 0; const result = age ?? 18; console.log(result); // 0 ✅Explanation:
const numStr = '42'; const num = parseInt(numStr); console.log(num); // 42Shorthand using +:
const numStr = '42'; const num = +numStr; console.log(num); // 42This is a quick and readable trick when you’re sure the string contains a valid number. If it doesn’t, the result will be `NaN`. See the code below:
console.log(+'hello'); // NaN
const user = {};
console.log(user.profile.name); // ❌ Error: Cannot read property 'name' of undefined
With optional chaining:
const user = {};
console.log(user.profile?.name); // ✅ undefined
You can also use it with functions:
user.sayHi?.(); // Only calls sayHi if it existsThis is great for handling data from APIs** where some fields may be missing.
condition ? valueIfTrue : valueIfFalse;To give you context, see the code below:
const age = 20; const canVote = age >= 18 ? 'Yes' : 'No'; console.log(canVote); // "Yes"This is equivalent to:
let canVote;
if (age >= 18) {
canVote = 'Yes';
} else {
canVote = 'No';
}
}
const name = userInput || 'Guest'; If `userInput` is falsy (like `null`, `undefined`, or `''`), `name` will be `'Guest'`.
const isLoggedIn = true;
isLoggedIn && console.log('User is logged in');
It only prints if `isLoggedIn is true`. Equivalent to:
if (isLoggedIn) {
console.log('User is logged in');
}