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)