Image for post

Whenever you are learning a new programming language, and no matter if it’s you first or your twentieth, my belief is that understanding how that specific language implements collections is the best place to start.

“If you wanna learn a new programming language, start with collections and work your way from there.” — Lars Mortensen

Because working with collections gets you a long way in most languages. Because no matter how little you have to do, you always have to work with collections and compute or transform on those.

In this article I’ll show you some very useful operations you can do on collections that will make your life easier.


Filter

The first opportunity to improve are often the loop combined with an if. It’s very simple and one of the first things you are thought as a student.

	type Todo = {
	  id: number;
	  title: string;
	  completed: boolean;
	}

	const todos: Todo[] = [
	  { id: 1, title: 'Buy nachos', completed: false },
	  { id: 2, title: 'Buy avocado', completed: true },
	  { id: 3, title: 'Buy ground beef', completed: false },
	];

	let completedTodos: Todo[] = [] as Todo[];

	for (let i = 0; i < todos.length; i++) {
	  if (todos[i].completed) {
	    completedTodos.push(todos[i]);
	  }
	}

	console.log(completedTodos); // [{ id: 2, title: 'Buy avocado', completed: true }]

Looking at this snippet you have quite a few things going on at the same time.

You declared an array at the beginning (L13) where you will push your result to, then you have the for loop it self which looks cryptic to any non programmers and is tough to remember when you just start coding.

The C++ style for loop was one of the most difficult to remember for my self in the beginning of my career. Once you learned that many languages support a more developer friendly version you started utilizing that.

It definitely helps removing stress from the eyes and help concentrate on the actual operation you are trying to perform.

#software-engineering #software-development #technology #javascript #programming

Beginner’s Guide to Working with Collections in JavaScript
1.80 GEEK