If you are learning JavaScript, you’ll be happy to know that there are some very simple tricks that can make your code shorter and easier to understand.
Here are 10 beginner-friendly JavaScript tricks with easy examples you can copy and paste.
1. Set a Default Value with ||
let username;
console.log(username || "Guest"); // Guest
👉 If username
is empty, "Guest"
is used instead.
2. Avoid Errors with Optional Chaining ?.
let user = {};
console.log(user?.profile?.age); // undefined (no error)
👉 Safe way to check values without crashing your code.
3. Build Strings Easily with Template Literals
let product = "Laptop";
let price = 50000;
console.log(`The ${product} costs ₹${price}`);
👉 Cleaner than using +
to join strings.
4. Extract Values with Destructuring
let person = { name: "Mourya", age: 25 };
let { name, age } = person;
console.log(name, age); // Mourya 25
👉 Quick way to get values from objects.
5. Copy and Merge with Spread Operator
let arr1 = [1, 2];
let arr2 = [3, 4];
let merged = [...arr1, ...arr2];
console.log(merged); // [1, 2, 3, 4]
👉 Works for arrays and objects.
6. Work with Arrays Using map
and filter
let numbers = [1, 2, 3, 4];
console.log(numbers.map(n => n * 2)); // [2, 4, 6, 8]
console.log(numbers.filter(n => n > 2)); // [3, 4]
👉 map
changes items, filter
picks items.
7. Swap Values in One Line
let a = 5, b = 10;
[a, b] = [b, a];
console.log(a, b); // 10 5
👉 No need for a temporary variable.
8. Flatten Nested Arrays
let arr = [1, [2, [3]]];
console.log(arr.flat(2)); // [1, 2, 3]
👉 Turns deep arrays into a single list.
9. Convert Values to True/False
console.log(!!"hello"); // true
console.log(!!0); // false
👉 Quick way to check if something is “truthy” or “falsy”.
10. Use console.table()
for Better Debugging
console.table([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
]);
👉 Shows data in a clean table in your console.
🎯 Final Note
These JavaScript tricks for beginners are easy to understand and very practical. Start using them in your projects, and your code will look much cleaner!
Happy coding ✨
Top comments (0)