Ultimate Guide to Tips, Tricks, and JavaScript Features You Should Know!

Daniel Movsesyan
Level Up Coding
Published in
11 min readFeb 19, 2020

--

My main coding language is JavaScript, and I want to talk about some of the really cool features that JavaScript supports.

A little bit overview

JavaScript often abbreviated as JS, is a programming language that conforms to the ECMAScript (latest stable release ES2019, preview release ES2020) specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm. It has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions.

Along with HTML and CSS, JavaScript is one of the core technologies of the World Wide Web. JavaScript enables interactive web pages and is an essential part of web applications. The vast majority of websites use it for client-side page behavior, and all major web browsers have a dedicated JavaScript engine to execute it.

As a multi-paradigm language, JavaScript supports event-driven, functional, and imperative programming styles. It has application programming interfaces (APIs) for working with text, dates, regular expressions, standard data structures, and the Document Object Model (DOM). However, the language itself does not include any input/output (I/O), such as networking, storage, or graphics facilities. The host environment (usually a web browser or Node) provides those APIs.

Originally used only in web browsers, JavaScript engines are also now embedded in server-side website deployments and non-browser applications.

Although there are similarities between JavaScript and Java, including language name, syntax, and respective standard libraries, the two languages are distinct and differ greatly in design.

You can read more on the Wikipedia page about JavaScript.

Every year JavaScript shows us new features and tools to solve different problems more easily. So let me introduce some of them which can help you to write less code in a clearer way.

1. Let and Const variable initializers

Before the ES6 standard, JavaScript had two types of scope: Function scope and Global scope and one type of variable initializer called var. Variables declared outside of the function (Globally) have Global scope and variables declared in a function have a Function scope.

We can access global scope variables from everywhere in the code, but we can access function scope variables inside the function in which that variable declared.

Seems logical, yeah? So let’s see some examples.

I numbered the lines so it’s easier to navigate through

We can see that in the example above there are two scopes we are talking about starting from (line 1 global scope and line 5 function scope). The number variable on line 2 is initialized in the global scope, so we can access it from function twoAdder (line 7) and also from outside of it (line 10).

But on line 6, we have one more variable called increasedNumber which adds 2 to a number value and saves it in it without modifying number. So, we can easily access it from twoAdder function online 7, but not from outside of it on line 11. That’s because variables declared in function (function scope) can be accessed only from inside that function.

That’s the simple representation of global and function scopes.

Continuing the main theme, after ES6 there is another scope called Block scope.

Block scope is the scope which is in {curly} brackets and the variables initialized in that scope can be accessed only from that scope. That scope can be created by functions, for loops, if statements, or just by curly braces.

Hmmm, what is that let keyword?

The answer is that after ES6, there are another two new variable initializers: let and const (from constant), and only using them you can create variables which support block scope.

With let the newSalary is block scoped in if statement

The difference between let and const is that variables initialized with const can’t be mutated. That’s why the const keyword comes from constant (means fixed).

You can’t assign other value to variable

But you can mutate the arrays or objects assigned to variable:

let and const also prevent hoisting (JavaScript’s default behavior of moving declarations to the top).

Yep, that’s long error message

For more details about hoisting you can read here.

Okay why “let”?

Let is a mathematical statement that was adopted by early programming languages like Scheme and Basic. Variables are considered low-level entities not suitable for higher levels of abstraction, thus the desire of many language designers to introduce similar but more powerful concepts like in Clojure, F#, Scala, where “let” might mean a value or a variable that can be assigned, but not changed, which in turn lets the compiler catch more programming errors and optimize code better. The full answer is in this link.

I highly recommend you use mentioned initializers with this priority:

const > let > var

2. Default function parameters

The function overallShoePrice calculates the overall shoe price after discount (if there is any) and returns it to us.

In the old way (before ES6) you would have to check if there is a discount passed through function parameter or not (undefined) and after that continue calculation and returning a final price. But with the new way, you can assign a default value to function’s parameter (On our example: discount = 0).

After running this function without passing the discount parameter, it will be assigned to zero by default. It’s easier, cleaner, and less chance to get an error. 🙃

3. Template literals (embedded expressions and multi-line strings)

Template literals for embedded expressions

Template literals are string literals allowing embedded expressions. You can use your ${variables} in your string much easier or even call ${functions()}. You can use multi-line strings and string interpolation features with them. They were called “template strings” in prior editions of the ES2015 specification.

Template literals for multi-line strings

With template literals, we can just start to write long text from the new line and there would be no errors. The text between `backticks` would be compiled as one string.

4. Destructuring

Destructuring has been added to JavaScript for writing cleaner code and make it easier to unpack values from objects and arrays. So we can use this feature with {objects} and [arrays].

Traditionally, we can access particular object keys like this:

With the new method, it’s like this:

We can see that with the new method, we initialize all needed variables in one line and then pass them into the function printMessage as an argument.

It may look longer, but it will be cleaner and easier to navigate through the needed keys.

A closer look at destructuring, that’s what is going in there. This:

Equals to this:

It’s also possible to go deeper to nested objects:

we have access to nicknames too

Aaaaand we can destructure in a function’s argument field too, like this:

This feature is amazing if you like to write clean and readable code

If we have some invalid JavaScript identifiers, then we can give them valid names and use them as normal.

In this example, big-boss-nickname is an invalid identifier, but you can use for example badassNickname and have access to NoobMaster69 value through it.

Now let’s talk a bit about destructuring in arrays.

We can see that almost like objects, we can destructure arrays in the same way too.

y is the first element in the array and z is the second. We can add 3 more elements and they will correspond to 3, 4, and 5, or we can use the rest parameter and assign the rest elements in the array to one variable as an array.

the name ‘rest’ can be whatever valid identifier as you want

That’s simple, yeah? 🙃

You can learn more about the destructuring feature there.

5. Array helper functions (forEach, map, filter, reduce, includes, flat, reverse)

There are many helper functions for arrays out there, and they make working with arrays incredibly easy. We will talk about 7 of them.

For example, the task is to reverse the array so [1, 2, 3, 4, 5] to be [5, 4, 3, 2, 1]. There are many ways to do that. Like with a stack, with decrementing loop, recursion, etc.

Let’s do that with a decrementing loop.

In this method, we are looping through all elements of arr from backward and pushing them to the reversedArray which will be our new reversed array.

That took from us about 3-5 mins and 7 lines of code. So JavaScript offers the same solution with just 1 line of code and with the speed of light. 🚀

Just think of it so JavaScript is running that “7 lines” of code under the reverse method with some modifications.

forEach, map, filter, reduce

The methods listed above are loop methods.

forEach method executes a provided (callback) function once for each array element. The callback function is the function that we pass to the method as an argument.

DON’T return anything because it’ll be simply discarded

In this example, we have workers’ salaries array and we log every workers’ salary to our console. We have worker, index and array arguments in our callback function. Worker argument is representing array’s every element ( {name: ‘Sam’, salary: 700}, {name: ‘Ani’, salary: 700}, … ). The index argument is the position of a particular element ( 0, 1, … ) and array argument is your array on which you are calling this method. Index and array exist in map, filter, reduce callback functions too.

One more example:

for more than one line of code inside the provided arrow function add paranteces

In this example instead of logging salaries of our workers, we are multiplying them by 2 and pushing to the newSalaries array.

With the map method, you can create a new array without modifying the array on which your method is running. We can demonstrate the map method on our previous example:

Instead of pushing every new element to our newSalaries array, with the map method we just assign to it and return new elements. New elements get automatically pushed to the newSalary array after returning.

I think it’s simpler and easier to use this method for creating new arrays on old arrays or donor array compared with the forEach method.

The filter method receives callback function with a filter condition and creates a new array with elements that meet the condition.

So we have more workers with different salaries, but we need the workers with salaries more than 2000 points. We pass the condition and get the newSalaries array with workers with salaries more than 2000 points.

We can create multiple conditions too.

And that was the filter method.

Now let’s look to reduce method. This was the hardest one I learned from these 4 methods. But it’s easy with some practice, don’t panic 🤫

This method’s callback function accepts 4 arguments (accumulator, currentValue, index, array). The last two methods you already know, so let’s look at the accumulator (let’s call it currentSum) and currentValue.

currentWorker fits better instead of currentValue

We have the same list of our workers and at this time we wanna calculate the sum of all worker salaries. You can notice the second argument of our reduce method (0). It’s the initial value of our calculation.

The currentSum argument gives us a summary of our calculation value at the moment of the current loop phase. For example, if we are on Arthur’s salary phase, we already have the sum of Sam’s and Susan’s salaries (0 (initial value)+ 700 + 700 = 1400), so the currentSum will be 1400.

The currentWorker argument is the same as worker argument in previous method examples.

After all phases of the loop, we will get the sum of all workers’ salaries under the sumOfSalaries variable. We can do any calculation we want with this method.

includes

The includes method determines whether an array includes a certain value among its elements, returning true or false as appropriate.

The !goalsOf2020.includes(newGoal)checks wheather goalsOf2020 has newGoal and if not adds the newGoal.

flat

The flat method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

The depth argument is optional, by default it’s 1

The depth argument is for telling the method how deep it can go and concat sub-arrays into one array.

The depth is 1 which is initialized by default, so the array has sub-array

If we want to have no sub-arrays guaranteed for all level depth arrays, we can use this trick bellow by passing Infinity as depth argument.

So using this, you will always have 0 depth array 😌

I think that’s all for now. That was a little bit long, but I hope you have learned about many new features you didn’t know before. But if you knew about all these features I am leaving some bonus stuff under this post 👇🏻

How to be a pro in coding?

Interested in AI ? Let’s have a sneek peek to what it is ?

How actually JS works ?

JavaScript algorithms and data structures

Clean Code JavaScript

JS features with Samantha Ming

Very popular JS online guide book

Intro to Sets

Classes in JavaScript

Modules in JavaScript

Wanna test your new programming knowledge online ?

--

--

Hello, I am Daniel, developer, also writer and reader in Medium. I hope you enjoy reading my articles 🙋‍♂️