Javascript Tips and Tricks
Tips and Tricks for new javascript developers.
Here are many lessons I've learned as a javascript developer. These are all oriented towards new developers.
Embracing ES6 Features
- Arrow Functions
Arrow functions provide a concise syntax for writing functions in JavaScript. Let's compare traditional function expressions with arrow functions:
// Traditional Function Expression
const add = function (a, b) {
return a + b;
};
// Arrow Function
const add = (a, b) => a + b;
Arrow functions are particularly useful for code readability. Just remember, you need to define them before calling them!
- Template Literals
Template literals are far better than string concatenation. They allow you to embed expressions inside string literals, improving readability and simplifying complex string constructions:
const name = "John";
// Do This
const greetingLiteral = `Hello, ${name}`;
//Not This
const greetingConcat = "Hello, " + name;
Arrays and Objects
- Map, Filter, Reduce
ES6 introduced powerful array methods that simplify common operations. Let's look at three of them:
- Map: Transforms each element of an array.
- Filter: Creates a new array with elements that pass a test.
- Reduce: Reduces an array to a single value (e.g., summing all elements).
const numbers = [1, 2, 3, 4, 5, 6];
// Get a new array of the same size
const doubled = numbers.map((num) => num * 2);
// Get a new, filtered array
const evenNumbers = numbers.filter((num) => num % 2 === 0);
// Reduce can return any data type, determined by how you initialize it (the second argument)
const sum = numbers.reduce(
(accumulator, nextNumber) => accumulator + nextNumber,
0
);
- Destructuring
I remember this topic being the most novel of all the ES6 features, and it may be the most commonly used in my experience.
Destructuring simplifies variable assignment and extraction from arrays and objects:
// Array Destructuring
const [first, second] = [1, 2];
// Object Destructuring
const { name, age } = { name: "Alice", age: 30 };
// Commonly seen in function props:
const myFunction = ({ prop1, prop2 }) => {
// Code here...
};
myFunction({ prop1: value1, prop2: value2 });
Asynchronous Javascript
- Use Promise Methods
Instead of awaiting different sets of data synchronously:
const user = await fetchUser();
const tasks = await fetchTasks();
We can effectively cut this in half with Promise.all:
const [user, tasks] = await Promise.all([fetchUser(), fetchTasks()]);
However, the better option is Promise.allSettled due to better error handling:
const results = await Promise.allSettled([fetchUser(), fetchTasks()]);
const [user, tasks] = handle(results);
- Handle errors
The handle function above handles errors:
const handle = ([userResults, tasksResults]) => {
let data = [];
if (userResults.status.rejected) {
//handle error, using userResults.reason
data.push({});
} else {
data.push(userResults.value);
}
//same for tasks
return data;
};
Code Organization
- Modular Code
Organizing your code into reusable modules is essential for maintaining a clean and manageable codebase.
Reducing file size, increasing readability, and reusing duplicated code are all benefits to modular code - but at what point should you extract code?
- Dry vs Wet
In programming, "DRY" stands for "Don't Repeat Yourself." Avoid duplicating code when similar functionality is required. Instead, create reusable functions or modules to keep your code DRY and maintainable.
However, "WET" stands for "Write everything twice." This means it is typically not worth extracting a reusable component for code that is only used twice.
Remember, when you do extract a reusable component, make that component as generic as possible!
Conclusion
Remember embrace all the new ES6 features. Have clean, organized, effective and updated code will make a world of difference in your projects.
Happy Coding!