21 Tricks Every Coder Should Master!
1. Handling Truthy/Falsy Values: Beginners vs Pros
Beginners:
let name = "";
if (!name) {
name = "stranger";
}
Noobs might use if (!variable) to handle falsy values, but it might not cover all edge cases.
Pros:
let name = "";
name ||= "stranger";
Pros leverage the logical nullish assignment operator ( | =) for concise and safer handling of falsy values. |
2. Enhancing Object Creation: Beginners vs Pros
Beginners:
const name = "Osman";
const age = 25;
const user = {
name: name,
age: age,
};
Novice developers might use explicit property assignment for object creation, which is verbose.
Pros:
const name = "Osman";
const age = 25;
const user = { name, age };
Pros utilize property shorthand for object creation, improving readability and reducing redundancy.
3. Dealing with Null or Undefined: Beginners vs Pros
Beginners:
let result;
if (variable !== null && variable !== undefined) {
result = variable;
} else {
result = "Default";
}
Noobs might use explicit checks for null or undefined values.
Pros:
const result = variable ?? "Default";
Pros leverage the nullish coalescing operator (??) for concise null or undefined checks and default value assignments.
4. Ensuring Unique Elements in Arrays: Beginners vs Pros
Beginners:
const numbers = [1, 2, 3, 4, 5];
const uniqueNumbers = Array.from(new Set(numbers));
Beginners might use a combination of Set and Array.from to ensure unique elements.
Pros:
const numbers = [1, 2, 3, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
Pros use the spread operator directly with Set for a more concise and elegant way to get unique array elements.
5. Simplifying Exponentiation: Beginners vs Pros
Beginners:
const squared = Math.pow(2, 2);
Noobs might use Math.pow() for exponentiation.
Pros:
const squared = 2 ** 2;
Pros use the exponentiation operator (**) for clearer and more concise exponentiation syntax.
6. Handling Floating-Point Math: Beginners vs Pros
Beginners:
const result = (0.2 + 0.5).toFixed(2);
Beginners might use toFixed() for precise floating-point arithmetic.
Pros:
const result = Number((0.2 + 0.5).toFixed(2));
Pros use Number() to convert the fixed number back to a numerical value for more accuracy.
7. Simplified Object Assignments: Beginners vs Pros
Beginners:
const defaults = {
type: "default",
size: "medium",
};
const options = {
type: default.type,
size: default.size,
color: "red",
};
Noobs might manually assign default properties.
Pros:
const defaults = {
type: "default",
size: "medium",
};
const options = { ...defaults, color: "red" };
Pros use the spread operator to merge objects and apply additional properties concisely.
8. Enhanced Error Handling: Beginners vs Pros
Beginners:
try {
// Code block
} catch (error) {
console.log("Error:", error.message);
}
Noobs might only log the error message in the catch block.
Pros:
try {
// Code block
} catch (error) {
console.log("Error:", error);
}
Pros might log the entire error object for better debugging and detailed error information.
9. Toggling Boolean Values: Beginners vs Pros
Beginners:
let isActive = true;
isActive = !isActive;
Noobs might use the logical NOT operator to toggle boolean values.
Pros:
let isActive = true;
isActive ^= true;
Pros use bitwise XOR (^=) for toggling boolean values, which can be more performant and concise in certain contexts.
10. Managing Strings: Beginners vs Pros
Beginners:
const name = "Osman";
const formattedName = "Hello, " + name + "!";
Novices might concatenate strings using +.
Pros:
const name = "Osman";
const formattedName = `Hello, ${name}!`;
Pros use template literals for string interpolation due to their readability and ease of use.
11. Using Short-Circuit Evaluation: Beginners vs Pros
Beginners:
let user;
if (userData) {
user = userData;
} else {
user = "Guest";
}
Noobs might use an if-else statement for assigning default values.
Pros:
const user = userData || "Guest";
Pros leverage short-circuit evaluation ( | ) for a more concise and elegant way of assigning default values. |
12. Simplified Array Cloning: Beginners vs Pros
Beginners:
const clone = originalArray.slice();
Beginners might use slice() to clone an array.
Pros:
const clone = [...originalArray];
Pros use the spread operator for a more concise and readable way to clone arrays.
13. Using Optional Chaining for Object Properties: Beginners vs Pros
Beginners:
let street;
if (user && user.address && user.address.street) {
street = user.address.street;
}
Noobs might use multiple conditional checks for nested object properties.
Pros:
const street = user?.address?.street;
Pros use optional chaining (?.) for concise and safe access to deeply nested object properties.
14. Simplifying Object Property Assignment: Beginners vs Pros
Beginners:
const person = { name: "Osman", age: 25 };
const updatedPerson = Object.assign({}, person, { age: 26 });
Noobs might use Object.assign() for updating object properties.
Pros:
const person = { name: "Osman", age: 25 };
const updatedPerson = { ...person, age: 26 };
Pros use the spread operator for a more concise and clearer way to update object properties.
15. Leveraging BigInt for Large Numbers: Beginners vs Pros
Beginners:
const largeNumber = 9007199254740991;
Beginners might need help with large numbers using standard JavaScript.
Pros:
const largeNumber = 9007199254740991n;
Pros use BigInt by appending n to the end of a number for handling larger integer values.
16. Simplifying Array Filtering: Beginners vs Pros
Beginners:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
Noobs might use filter() for array filtering.
Pros:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((num) => !(num % 2));
Pros leverage the truthiness of 0 in JavaScript for more concise filtering.
17. Utilizing Logical AND for Short-Circuit Evaluation: Beginners vs Pros
Beginners:
if (condition === true) {
performAction();
}
Noobs might explicitly check for true in conditions.
Pros:
if (condition) {
performAction();
}
Pros leverage the truthy nature of conditions for concise code.
18. Simplifying Array Operations with find: Beginners vs Pros
Beginners:
const numbers = [10, 20, 30, 40, 50];
let found = false;
let foundNumber;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 30) {
found = true;
foundNumber = numbers[i];
break;
}
}
Noobs might use traditional loops to find elements in an array.
Pros:
const numbers = [10, 20, 30, 40, 50];
const foundNumber = numbers.find((num) => num === 30);
Pros utilize the find() method for a more expressive and readable way to search arrays.
19. Using startsWith and endsWith for String Checks: Beginners vs Pros
Beginners:
const str = "Hello, world!";
const startsWithH = str.indexOf("Hello") === 0;
const endsWithWorld = str.indexOf("world!") === str.length - 6;
Noobs might use indexOf() for string checks.
Pros:
const str = "Hello, world!";
const startsWithH = str.startsWith("Hello");
const endsWithWorld = str.endsWith("world");
Pros use startsWith() and endsWith() for clearer and more direct string checks.
20. Simplifying Conditional Assignments: Beginners vs Pros
Beginners:
let value;
if (condition) {
value = "Yes";
} else {
value = "No";
}
Noobs might use if-else statements for conditional assignments.
Pros:
const value = condition ? "Yes" : "No";
Pros leverage the ternary operator for concise conditional assignments.
21. Using Array.includes() for Membership Checks: Beginners vs Pros
Beginners:
const numbers = [1, 2, 3, 4, 5];
let found = false;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 3) {
found = true;
break;
}
}
Noobs might use traditional loops for membership checks.
Pros:
const numbers = [1, 2, 3, 4, 5];
let found = numbers.includes(3);
Pros use the includes() method for cleaner and more expressive membership checks in arrays. Conclusion
JavaScript offers numerous ways to achieve similar results, but leveraging certain tricks and practices can significantly enhance your code’s readability, maintainability, and efficiency.Transitioning from beginner-level approaches to more professional techniques can improve not only your code quality but also your overall development skills.Experiment with these methods in your projects and continue exploring new ways to optimize and write cleaner JavaScript code.