Smart {Code};

Array Methods That Every JavaScript Developer Must Know

Arrays are one of the most common things that you’re going to use as a programmer. In this article, I’m going to be covering important JavaScript array methods that are going to make your life as a developer so much easier. As an example, I am going to use a student array of student objects for all of these different array methods

. . .

const students = [
        {name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

filter()

So let’s assume that we want to get all of the students in this list whose ages are less than or equal to 24. All we would need to use is the filter method to filter out every student that’s not under 24.


const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

/*

this filter method just takes a single function, 
which is going to have one parameter of student which 
is every student/item in the array. we'd need to 
return a true or false statement on whether or 
not we want to include them in the new array

*/

const filteredStudents = students.filter((students) => {
	return students.age <= 24        
})

/* 

This line basically stashes all of the students 
whose ages are less than a 24 in the new 
filteredStudents array 

*/

console.log(filteredStudents)

This filtered array method is super easy to use. All you do is return true or false for each item. If it’s true, it is added into the new array, and if it’s false, it is not. The great thing about the filter method and all the other methods in this article is that they actually don’t change the underlying object that you’re filtering over so we can log the students array and it will still have all its items. This is very convenient because we don’t have to worry about changing the old array when we use these new array method to create new arrays.

. . .

map()

map() allows you to take one array and convert it into a new array. In this one, all the items in the new array are going to look slightly different. So let’s just say, we want to get the name of every student. we can get an array of the names by using map().


const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

/*
the method takes a single function, with the 
students/items as a parameter here we just 
return what we want in the new array
*/
const studentNames = students.map((students) => {
        return students.name
})

console.log(studentNames)

/*
If we print out these student names, console.log(studentNames)
we get a new array that is just full of all the different
names of the students.
*/
     

This can be done with anything within the array. The method is very useful when you want to take an object for example, and just get the names or a single key, or take one array and convert it into another array. This method is one of the most popular ones in JavaScript arrays.

. . .

find()

This method allows you to find a single object in an array. This is straight forward. Say we want to find a student with the name john,


const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

const singleStudent = students.find((students) => {
return students.name === 'john'
})

console.log(singleStudent)
/*
  console.log(singleStudent) will give the everything 
  associated with john in this example, I.e

   Object {
    age: 25,
    name: "john",
    score: 86
  }
  

*/

In this method, the logic is that there is a true or false statement, and it’s going to return the very first array item that evaluates to true.

. . .

forEach()

Unlike these other methods, forEach() does not actually return anything, hence no need for a return statement. Let’s say we need to print out all the names of the students within the student array, we would go about it as:


const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

students.forEach((students) => {
  console.log(students.name)
})

/*
  the result is the name property printed out on the 
  console line after line like so

  "sam"
  "john"
  "dean"
  "timothy"
  "frank"

 */

this is going to work very similarly to a for-loop, but it’s going to take a function instead. So, for every single array item, it’s going to do execute the block of code within the function. This approach just makes working with arrays where you need to loop over items so much easier since you don’t have to write out the clunky long for loop syntax as you’d normally have to.

. . .

some()

This method is a bit different than most of our other functions in that, instead of returning a brand new array, it’s actually going to return true or false. So we can check if some of the students in this array are underage,

const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

const hasUnderageStudents = students.some((students) => {
   return students.age < 18
})

console.log(hasUnderageStudents)
/*
  this will return false because there is no 
  underage student in the array.
*/

So if any student item has an age value below 18, the function will return true. The method just checks to see if anything in the array returns true and if it does, the entire thing returns true.

. . .

every()

This method is very similar to some() except for instead checking for at least one item to evaluate to true or false, it checks to make sure every single item falls under a given condition.
if I use the same code used in the some() code example,

const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 

const hasUnderageStudents = students.every((students) => {
return students.age < 18
})

console.log(hasUnderageStudents)
// this returns false because there are no ages below 18

If I am to change the condition to one which every item evaluates to true, the whole thing returns true

const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 
const hasUnderageStudents = students.every((students) => {
  return students.age < 40
})

console.log(hasUnderageStudents)
// this will return true because every single age property is below 40

. . .

reduce()

This method is quite different than all the other methods because it is actually doing some operation on the array and returning a combination of all those different operations. Let’s say I wanted the total scores for all the items in the student array, normally one would go for a for loop and add the score every single time, and at the end of the loop, you would print out the total score. To avoid the long process, you can use the reduce() method to do this.


The syntax for the reduced method differs from the other methods. Instead of taking the array itself, it takes an array and a property for what we want to reduce everything into and in our example, score. it also takes a second parameter aside from the function, which is going to be your starting point, and in our case, we want to start our total at zero.


const students = [
	{name: "sam", age: 26, score: 80},
	{name: "john", age: 25, score: 86},
	{name: "dean", age: 20, score: 78},
	{name: "timothy", age: 18, score: 95},
	{name: "frank", age: 21, score: 67}
] 
const totalScore = students.reduce((currentTotal, students) => {
  return students.score + currentTotal
}, 0)

console.log(totalScore)
  • As the code reads, we have the reduce() method, which runs a function on every single item inside the array.
  • The first parameter of that function is going to be whatever the previous iteration of this array returned and the second parameter is the actual item in the array.
  • The currentTotal is going to start on the very first iteration with whatever we pass in as the second parameter of the reduce() method which is zero in our case.
  • The first time this reduce() method runs, so we get zero and the ‘sam’ item. So it just does 80 plus zero and returns that, which is 80.
  • The second time the method runs, that return value of 80 becomes the current total, and our next item is ‘john’, so it does 86 plus our current total of 80, which is 166, and puts that back in for the current total. It does that until we get to the very last item in the array, which will output as the total in the totalScore variable.

This method is a bit more confusing, but it is incredibly useful when you need to do some kind of operation cumulatively to all the items in an array, such as grabbing the total price for all the items, daily stock prices e.t.c

. . .

includes()

This method doesn’t take a function as an argument. It takes a single argument. It is usually used in simple arrays that don’t need a lot of heavy operations. Let’s say you have an array of fruits, const fruits = [ ‘mango’, ‘apple’, ‘orange’, ‘pineapple’, ‘lemon’]. a simple way of showing the implementation of the includes() method would be to check if a certain fruit is in the array.


const fruits = [ 'mango', 'apple', 'orange', 'pineapple', 'lemon']

const includesApple = fruits.includes('apple')

console.log(includesApple) 
/* 
this will return true because 'apple' is 
one of the items inside the array. 
*/

. . .

In my opinion, these methods are a must-know for any JavaScript developer because arrays are one of the data structures that are most commonly used for organization. Having a good grasp of these methods will greatly improve your skills and problem-solving ability when it comes to arrays.

Should You Learn TypeScript?

I have been putting writing this article off for a while now, but I thought it would be nice to share my thoughts on TypeScript as something that you might want to add onto your belt. TypeScript is a fairly new programming language. Since 2012, the language has become massively popular to the point of taking over front-end development, especially in large applications. Simply put, it is an enhanced version of JavaScript.


The relationship between TypeScript and JavaScript is similar to that of C and C++. The nice thing about TypeScript is that it is interchangeable with JavaScript. Any TypeScript code can be transpiled and translated into native JavaScript. You can therefore use the JavaScript that you already know inside of TypeScript. Most developers are adopting the use of TypeScript because you can use all its features, then translate into a native JavaScript file when you need to run it. Doing this may seem redundant at first because you can do a lot with plain old JavaScript, but TypeScript has better features.


TypeScript shines when it comes to large scale projects and enterprise-level applications. The use of TS should be judicial though because it would be a little bit of an overkill to use it for small side projects or an application where you merely have one or two JS files. I think one should reserve its use when you get to a point where you have a lot of structure involved in your program.

If you know JavaScript, you pretty much already know TypeScript, anything you can write in native JavaScript, you can write in TypeScript almost line for line. The core features it adds is the ability to add static typing to JavaScript. This feature does not change the fact that JavaScript is a dynamically typed language, nor does it change anything during runtime. It just means that when you are writing TypeScript code, you have type enforcement and you can choose if you want to declare the type of variables, method, parameters, return types, whatever it may be. The reason static typing is so important is that it comes with so many different advantages.


When you have static typing, and you have type reinforcement, the first thing that is a big deal is that catching errors becomes a lot easier. In dynamically typed languages like Python or JavaScript, almost all your errors are happening at runtime. That raises a lot of issues because you have to figure out what the problem is at runtime, which is more complicated than before, at compile time. There are also chances that you may miss errors because they just have not run yet. Take Python as an example, you can write some random code that makes no sense, but it will still run. Unless you hit that line of error-prone code, you may never know that that error exists, which is the same as in JavaScript.


When you have TypeScript, about 90% of the errors that you are commonly getting in a dynamically typed language, will be eliminated. How? In TS, the errors will be visible to you before you can even execute the program. You are going to have to fix the errors even before running your code. Without TS, you are going to have to debug your code at runtime that will require the use of a debugger which you might not have access to. This becomes hard for the most part when you are dealing with a large scale software, that is going out to millions of people. You want to make sure that you are catching all those bugs, especially any detrimental ones, and that you are getting them in your IDE before you go to the software. The idea is to give your IDE more information about your code so that it can do more work for you. Think about it this way. If you can have your IDE carry a lot of the weight, you will be saving yourself time and probably a bit of money too, especially if you are paying employers to code.


TypeScript comes with a bunch of other great features too, but the one I wanted to dial in on here is “typing”. Some people might think that it is going to be hard because you have to declare the types. It is not very difficult. The thing to take home here is that using this technology is entirely optional. If you are in a situation where it does not make sense to use it, you do not have to. In my opinion, TypeScript is a great language. It is an easy language to pick up specifically if you already know JavaScript. It just makes things way more powerful.


I have seen people online saying that it takes a little bit longer to write because you have to put the types. It is true, but I think that that is a marginal difference. I believe the types are just way more beneficial than they are harmful, and I would encourage all of you to look into TypeScript. Do not be intimidated by it. If the doubt comes along, just remember that TypeScript is just JavaScript on steroids. It is a great language to add to your resume because it shows that you are keeping up with trends. If you are already familiar with JavaScript, why not?

Skills You Should Have Before Learning A JavaScript Framework

How much JavaScript should you know to move on to a framework? I get this question a lot from beginners in the field of web development. This article is just a simple guide on the skills that I recommend learning before jumping into a framework like React, Angular, or Vue. These frameworks are all different, but certain things are used in every single one of them, and if you learn these skills beforehand, you will have much less trouble grasping the concepts of a particular framework.


First of all, every beginner should have the fundamentals of JavaScript before moving to a framework. They include basic syntax variables, arrays, objects, functions, loops, all the other concepts that you would learn when you’re starting to learn the language. With most frameworks, you do not directly touch the DOM. However, I would still recommend learning how to manipulate it if you ever want to build something in pure vanilla JavaScript.
One problem I have seen is that people want to jump right into a framework after learning the fundamentals. I think that is a big mistake because not only are they attempting to learn the concepts of the framework, they are also learning all of ES6 at the same time. Things like classes, arrow functions, destructuring. The problem with this approach is that they will not be able to identify what is part of the framework and what what is JavaScript.

. . .

Modules

Modules are used in every framework because they are used to import files into other files or to import packages. Without modules, there would not be any framework because modules allow everything to work together instead of having isolated code files. There are different types of modules, but you want to focus on ES6, which is the “import-from” syntax. Angular uses TypeScript, which has many of the same features that ES6 has including modules. So if you learn ES6 modules, you will be fine with TypeScript.


Modules are not supported in browsers directly, therefore, you have to use some kind of tooling, like Parcel or Webpack with Babble if you want to be able to compile modules. I am not going to say that you have to learn how to do that before moving to a framework, but I would suggest at least reading about modules a little bit, looking at the syntax, maybe watching a tutorial before you move on to learning a framework.

. . .

Classes

Classes are introduced in ES6. Classes are used in many languages and you may even be familiar with classes from another OOP language. Classes are more commonly used in React and Angular. Vue uses object literal types. I would suggest learning classes, even if you are learning Vue. Learn how to structure them, learn about constructors, methods and properties, instantiation, as well as extending classes and inheritance.

. . .

Arrow functions

Arrow functions will make your code much more compact and clean, even though there are many situations where you will not need to use arrow functions. In my experience, they are the norm when it comes to building applications with these frameworks. It is cleaner, requires fewer lines of code, and there can also be advantages within scope because it uses something called a lexical this, so you want to look more into that.

. . .

Promises

ES6 introduced promises as an alternative to using callbacks for asynchronous code. If we make a request to a server or anything that could take a while, we want to do it asynchronously so that we can move on with our application and not have to stop and wait for a response. This is achieved through the use of promises. In simple terms, they make a promise and then fulfil it when the task is done.


When a promise completes, you want to use .then() to catch the response and get the data back and then .catch() to catch any possible errors. You may also want to look into Async/Await syntax, but I do not think it is necessary to be able to use a framework. You will also need to learn how to use the fetch API to make HTTP requests. There are other tools like Axios that you can use, but it is good to know how to do this with vanilla JavaScript.

. . .

Destructuring

Destructuring is a powerful way unpack values and assign variables from objects and arrays. It makes your code cleaner. Most developers prefer using it in applications built with said frameworks. Keep in mind that destructuring is part of ES6 and is not compatible with every browser. I recommend using Babel, Typescript, or anything that will compile your code into ES5 to ensure full compatibility for every user.

. . .

Components and State

When you first learn basic HTML, CSS, JavaScript, you are taught about separation of concerns. You have your HTML markup, your CSS styling and your JavaScript for any dynamic type functionality. So you select elements from the DOM and manipulate them in a monolithic way. With frameworks, it is a little different in terms of how you think of the mechanics of your application. You want to think of pieces of your user interface as components. View the menu bar, search bar, the main content, whatever it may be, as encapsulated entities that include both the markup and the functionality, and in some cases, the styling.


Each component has its own state, which is usually the data that is associated with it along with the just its state of being. So for example, you might have a menu component that has a state of open and the state of close so that if you click it, maybe it opens up and closes if you click it again. You will have that in your state. That is how you should start thinking in terms of your UI when you’re dealing with frameworks. In a lot of cases, you are going to want to share data or share state. That is when you look into things like Redux in case of React for state level management.

. . .

Spread Operator (…)

This is important, especially when dealing with State. State is usually immutable, which means it can not be directly changed. What usually happens is you have to make a copy of it and add what you want, and then send it down to the application or the component. The spread operator allows us to do that. So here’s a really simple example. So let’s say we have this user state that just has one property of name it is equal to Samuel, and we want to add an age property to this user state.


const userState = {
name: ‘Samuel’
}


What we could do is create a new user state, and we can use the spread operator, which is just three dots and put in user state, and it will give us whatever is original user state. It will make a copy of the original, and then we can add the age property to it like so,

const newUserState = {
…userState,
age: 26
}

. . .

Higher-order array functions

There are a plethora of such functions in JavaScript. Some of the common ones include forEach(), map(), and filter(). A higher-order function is a function that takes another function as a parameter, but these all have to do with arrays, iterating through them and manipulating data. forEach() is probably the most basic. It is used for iteration like a for-loop return. It loops through an array and you can do what you want with the array items.


map() is heavily used in React, and it is used to create an array from another array. You may have an array of user objects and let’s say there is an age property, among others. If you want to create an array of just their ages, you can do that with map(). filter() which will, as the name suggests, filter items out based on a condition. It is mostly used in reducers and state management.

. . .

I think once you get a good grasp of those things, you will be ready to learn any front end framework. You will also be able to pick up a second or third faster. In JavaScript, it is never about how many frameworks you can use. Some developers actually prefer pure vanilla JavaScript. Take your time understanding these concepts. Don’t just gloss over them, practice using them on some side projects. You will get better in no time and you will be ready to jump, headfirst, into a framework of your choice