Javascript tips

Start With The Basics

When you are learning JavaScript - or any other programming language - it's very important to pace yourself at the beginning. Although you might find initial concepts quite simple and straightforward, you need to spend time on the basics so that you have a full understanding of the language you are trying to learn.

Understand Every Line Of Your Code

Sometimes when you are learning JavaScript, it can be easy to write code that you don't fully understand. This is especially true when you are trying to master JavaScript free through online courses which give you comprehensive directions. A lot of people fall into the trap of simply following the directions, writing some code in their code editor, and troubleshooting until it does what it needs to. However, these people don't always understand what they are writing. As a learning programmer, it is extremely important to make sure that you understand every single line of code that you write, what it does, and how it impacts the rest of your program. The difference between the words "to master" and "to learn JavaScript" is gigantic. Every time you write a program, you need to sit down for a few minutes and make sure that you know what every little bit of code does. If you are unsure about something or don't understand it, go back over your notes, have a look in a language reference guide (more on this in a minute), or ask someone for help.

Converting to numbers

JavaScript is a loosely typed language, meaning we don’t have to explicitly specify types of variables. JavaScript also freely type-converts values into a type depending on the context of their use. Converting values to numbers, especially strings to numbers, is a common requirement and many methods can be used.

Bonus trick

If we want to add a new item to an array without mutation (which we usually want to avoid), we can create a new array using the ES6 spread operator and slice:

Dynamic property names

ES6 brought us computed property names that allow property keys of object literals to use expressions. By surrounding the key with brackets [], we can use variables as property keys: This is useful in a situation where you want the key to be created on the fly. We can access the value with bracket notation:

item[type];   // "kiwi"item["fruit"] // "kiwi"

Or with dot notation:

item.fruit; // "kiwi"

Remove array duplicates

The Set object type introduced in ES6 lets you store unique values. Together with the spread operator (…), we can use it to create a new array with only the unique values:

const uniqueArray = [ Set(array)]

We create a Set from an array and because each value in the Set has to be unique we remove all duplicates. We then convert the Set back to a new array using the spread operator.

Random number from interval

There are times when we need a random number to be generated within a range. The Math.random() function helps us generate a random number, and then we can transform it to the range we want:

const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max — min + 1) + min);

There’s another trick baked into this one if you look at how the function is constructed.

Setting defaults

We have all seen them. The endless if statements checking if the values have been set. What if I said there was a better way? Well, that’s exactly what I’m saying, default values.

Swapping two variables

Using what we learned in the last trick makes swapping variables as easy as:

let me = "happy", you = "sad";[me, you] = [you, me];// me = "sad", you = "happy"

The above code creates an array of [you, me] and immediately destructures them into the opposite variables. No need for temp variables anymore!

Managing objects

Destructuring is a huge part of ES6 and something you’re probably going to be using often. It allows us to extract data from objects, and assigning the extracted data into variables:

const rectangle = { h: 100, w: 200 };const { h, w } = rectangle;

We can rename the variables if we want to:

const { h: height, w: width} = rectangle;console.log(height); // 100

Another handy thing we could do is to destructure the returned object by a function and pick and choose what values we want to use: So, with destructuring, we can return multiple values from a function by returning an object and choosing the pieces we want to be returned. Removing a property in an immutable way requires a little trick provided by spread’s counterpart, the rest operator, which is written with three dots (…) like spread. However, in this case, we spread the remaining properties into a new object.

const { age:_ , …person } = getPerson();console.log(person); // {firstName: “Max”, lastName: “Best”}

Now the person object holds all properties from the original person object except age.