Harsh Bardhan Mishra
Harsh's Blogs

Harsh's Blogs

Five Concepts to know before you get started with Javascript Development

Five Concepts to know before you get started with Javascript Development

Subscribe to my newsletter and never miss my upcoming articles

Before we start talking about some of the features of Javascript as a language, it would be no heresy to say that you all must have heard about Javascript before. And there are good reasons for that. According to Stack Overflow’s 2020 Developer Survey, Javascript has remained as the most popular and commonly used language for eight times in a row. Even the Github’s State of the Octoverse has ranked Javascript as the most widely used language and has remained consistent at its place since 2014. Well, what makes Javascript so popular after all?

The development of Web Technologies and Frameworks has further heralded the development of Javascript. The rise of niche Front-End Frameworks like React and Angular has paved a new path in Front-End Development and frameworks like NodeJS and Express are icing on the cake which has further boosted the Javascript community. Many developers are now looking for roles in Javascript development and there are right reasons to do so: As a language, it provides capabilities to develop both Client-Side and Server-Side interfaces.

bharat-patil-Vl6nLPF67rg-unsplash.jpg

If you have started with Javascript, there are many things for you to learn before you jump into Frameworks and Libraries. But that is not always the case. People tend to straight away jump into development with Javascript, and they forego the need for getting the basics right. In this article, we will be delving deep into seven of the Javascript concepts that you need to get right before you get started with Javascript development.

1. Arrow Functions

The most obnoxious way to write functions in Javascript is the traditional way, where we declare a function somewhere, define it later and then we call it. But what if, we need an inline function and we need to use them just once. To write such anonymous functions and to make our functions more readable, we can bank on a new feature that the ES6 provides us: Arrow Functions.

Now there are multiple advantages of using Arrow Functions in your code. The most obvious ones are that it makes your code more readable, concise and you can write regular functions as well with shorter syntax. Sounds cool?

/* Standard Javascript Syntax (ES5) */

var multiply = function(a, b) {
  return a * b;
};


 /* Arrow Functions using ES6 Syntax */

 var multiply = (a, b) => { return a * b };

As you can see that you can easily utilize the Arrow Function to simplify your function definition and usage further. If you are having only one parameter in your function definition, you can do that without needing any brackets.

For developers who are just starting to familiarize with ES6 Syntax, this transition might seem difficult. But you can just follow two simple steps to convert your regular function into an Arrow Function:

  • Remove the function() keyword.
  • Add a => just after the ()

Arrow Functions are only callable and not constrictive, unlike Regular Functions. This simply means that you can use the new keyword with Regular functions but not with Arrow Functions. Before you work with Arrow Functions, remember that they are anonymous functions. If you want to call an Arrow Function you can set it in a variable like const, var or let.

2. Importing and Exporting Modules

Let’s imagine a file that you have constructed for your purpose, using Javascript. This file consists of a lot of functions that you have defined and now you want to use them in other files as well. Now, this is actually the best way of developing new applications, where you divide your whole codebase in wholesome chunks and then import and export them as you like.

With Javascript, this whole process is simplified and you can access your files using these simple keywords: import and export. Let’s write a block of code in our file math-operations.js and export a module to add two numbers.

const add = (x, y) => {
  return x + y;
}

export { add };

But how are we going to import that block of code into some other file? Well for this operation, we will be using the import keyword and the best part is you don’t need to rewrite any of the code. Sounds pretty easy?

import { add } from './math-operations.js';

If you are having difficulty in understanding the purpose of importing and exporting modules, you can understand it in a slightly different manner. In Javascript, a module is simply an object, variable or function that you can export using the export keyword. You can export multiple modules but there should be only one default export.

The imports are made using the import keyword and it is executed by placing, the exact name between curly braces. Remember to check out for the correct path if you are importing locally otherwise, you can use an absolute name to check out your node_modules for the exact package.

Let’s see another example for exporting our package:

export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}

We can know import the packages by simply importing them:

import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

3. Promises in Javascript

Well, it sounds pretty strange but we have this concept of promises in Javascript as well. To handle multiple tasks, all of which depends on the completion of each other, we can use multiple callbacks and end up in something we call a callback hell. To resolve this we have got promises in Javascript, that makes an asynchronous promise to do something.

image

A promise can be simply understood as an object that consists of status and value. Promise serves as a constructor that takes a function as an argument with two parameters: resolve and reject. These two parameters determine the outcome of the promise.

Javascript is a single-threaded language, and therefore only a single piece of code can execute at a given time which has to run one after another. So before Promises, you’d probably been using events, async() and callbacks to get around this JavaScript feature. In Promises, we can only succeed or fail once.

const PostUp =[
    { text:"Post 1", text:"This is Post 1" },
    { text:"Post 2", text:"This is Post 2" }
];

// Getting PostUp takes 1 sec
function getPostUp(){
    setTimeout(() => {
        let output = '';
        PostUp.forEach((post) => {
            output += `${post.text} \n`
        })
        console.log(output);
    },1000)
}

// Creating a post takes 2 sec
function createPost(post){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            PostUp.push(post);

            const error = false;
            if (!error){
                resolve();
            } else {
                reject("Something went wrong!!");
            }
        },2000)
    })
}

createPost({ text:"Post 3", text:"This is Post 3" })
    .then(getPostUp)
    .catch(err => console.log(err));

In Promises, we can have three statuses:

  • Initial Status is denoted as pending which is neither fulfilled nor rejected.
  • Fulfilled Status is denoted as fulfilled which means that the operation was successfully executed.
  • Failed Status is denoted as rejected which means that an error was thrown back.

One of the best thing while working with Promises is that, it allows you to use Promise.resolve or Promise.reject with the exact value that you would want to represent.

4. Variable Declaration in Javascript

JavaScript is dynamically typed, that simply means that types can change at run time. Declaring variables with the var keyword allows us to simply overwrite the datatype of the variable without logging in an error. A new ES6 Syntax feature allows us to freeze the datatype of the variable.

image

The new keyword let allows declaring the variables and if we try to use the same variable name elsewhere, it will straight away throw an error. You can also use strict which enables a strict mode that can help catch us some common coding mistakes like accessing a variable without declaring it.

"use strict";
let name = "Hello, World!";  
let number = 7;  
if (number > 4) {  
   let hello = "Hi! What's Up!";   
   console.log(hello) // Output: Hi! What's Up!
}  
console.log(hello) // Error: hello is not defined

The one thing that you need to understand about the let keyword in Javascript, is that it follows the standard Scoping rules. The scope of any variable declared with let is limited only to that block of code.

You can also use the const keyword for declaring only read-only variables. This means that once a const keyword is used, we cannot reassign the value to it. Trying to reassign a variable with const will throw up an error.

const xam = 'Hashnode';
const xam = 'not-hashnode';

// Will give an error: 'constant 'xam' has already been defined'

If you are starting up with declaring variables, you can start with using the const keyword for this purpose. You can later refactor your code and convert const to let once you need to reassign the variable.

5. Map, Filter and Reduce

Map, Filter and Reduce is one important concept that wraps your mind for once, but if you have got your basics right, it would be the most important concept in your Javascript arsenal.

Map, Filter and Reduce are used for Array transformation and can either perform their operations independently or they can be chained to each other. Let’s explore all three of them one by one.

A map is used to take a function and is then called on every other element of the array. It can create a new array from an existing one and call a function to operate on every single element of the array. Sounds pretty cool, isn’t it?

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

const newArr = array.map((num) => num*num) 
//newArr = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The map just loops over all the elements in the array, and transforms every element in the array and return it.

A filter takes every element in an array and applies a conditional statement to filter out the elements in the array. In this way, if we want some condition to be checked in the loop, we don’t need to loop through it entirely. We can just use the filter and extract the specific elements matching the condition.

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

const newArr = array.filter((num) => num % 2 === 0)
//newArr = [2, 4, 6, 8, 10]

A reduce just loops over an entire array and convert it into something else by using a transformer function. This “something else” is referenced by you which is passed as a second argument and it can be used to “reduce” the entire array into something new which can be an object or a variable. Unlike map and filter, reduce takes four arguments:

  • Accumulator
  • Current Value
  • Current Index
  • Source Array

Let’s see an example of reduce:

function sumOfNum(total, num) {
  return total + num;
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const newArr = arr.reduce(sumOfNum);

The reasons why many Javascript Developer use map, reduce and filter so commonly is because they don’t have to loop through an entire array now and they can be chained to each other for easy-to-implement array transformation.

Conclusion

With this, we arrive at the end of some of the most important concepts of Javascript. There are furthermore features with Javascript in general and ES6 in particular that demands further insight and intuition but exceed the scope of this article. Javascript, as a language, is quite complex to understand at first and working around it, is quite difficult, even for Senior Developers, if the basics are not done right.

Learning Javascript does not mean that you have to master everything before you move onto a framework or a library to work with. But essential skills in the basics are quite desirable and this is what has been addressed here.

 
Share this
Proudly part of