Understanding JavaScript Methods as an Absolute Beginner

As an absolute beginner, having learned and understood the syntax of a programming language, the next step is to understand how to use the “methods” of the language. I like to think of methods as the vocabulary of a language, the more you understand the easier it is to communicate and write code effectively.

What are methods?

Methods are functions which is a property of an object.

Ok, What are objects?

In JavaScript, objects can be seen as a collection of properties. Objects usually contains key/value pairs wrapped in an opening and closing curly brackets, as seen below.

let person = 

fullName: function() 
return this.firstName + " " + this.lastName;


// person is the name of the object
// firstName, lastName and fullName are the keys
// John, Doe, the function are the corresponding values

Now, let’s understand what are methods?

The below lines of code shows an object containing a function. The object name is “objectName” and the method is “methodName”.

const objectName = 
  methodName: function() 
    // Logics to be executed are written

// methodName is a method of this object - called objectName.
// methodName is a function which is a property of the object.

Methods are the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, it provides a better readability of code. So basically, a method is a collection of statements that perform some specific task and returns the result to the caller. A method can also perform some specific task without returning anything.

Accessing Methods

JavaScript provides two notations for accessing methods. The first, and most common, is known as dot notation. Under dot notation, a method is accessed by giving the object name, followed by a period (or dot), followed by the property name.

Dot Notation

You can access an object method using a dot notation. The syntax is:

const object = 
  methodName: function()
    console.log('hello world')

// To access the method using dot notation.
//  hello world

Here, the methodName method is accessed as object.methodName()
If you access a method without the () parentheses, it will return the function definition, to execute a function we invoke the function with ().

Bracket Notation

The second method is the bracket notation. For the bracket notation, a method is accessed by giving the object name, followed by the property name in quotation and then wrapped in an opening and closing square bracket.


Note that in the code below, the quotations are absence, this is because the object properties has been assigned to a variable.

let propertyName = 'property';


Difference between Methods and Functions in JavaScript

We often misplace methods as functions; now let’s try to understand the difference between Method and function in JavaScript.

JavaScript Methods:

A JavaScript method is a property of an object that contains a function definition. Methods are functions stored as object properties. Method can be accessed with the following syntax:


Features of Methods:

  • Actions that can be performed on objects are what we term JavaScript methods.
  • The method can also be called without using parenthesis.

JavaScript Functions:

A function is a block of code written to perform some specific set of tasks. We can define a function using the function keyword, followed by Name and optional parameters. Body of function is enclosed in Curly braces.

Function syntax:

// Function keyword

function functionName() 
// Code to be executed

// Arrow function

const functionName = () => 
// Code to be executed

Features of Functions:

  • The function is executed when something calls/invokes it.
  • The name may contain letters, digits, dollar signs, underscore.
  • Parameters are listed inside round parenthesis after the name of the function.
  • Arguments are values a function receives when it is invoked.
  • When the control reaches the return statement, it will stop executing and the value is returned to the caller.

Built-In JavaScript Methods

Built-in methods are predefined pieces of code in a program or programming framework or a programming language that performs some specific task. This makes programming easy as programmers don’t have to create a new method or function and can simply directly use the built-in methods in their application.

Some JavaScript Built-In Methods are as follow:

Array Methods: Array methods are functions built-in to JavaScript that we can apply to arrays.

String Methods: String methods help you to work with strings.

Object Methods: Object methods help you to work with strings.

Date Methods: Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.

Document Object Methods: JavaScript Document object is an object that provides access to all HTML elements of a document.

Number Methods:The Number object contains only the default methods that are part of every object’s definition.

Math Method: Math is a built-in object that has properties and methods for mathematical constants and functions.

Window Object Method: The window object represents an open window in a browser.

RegExp Methods: Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp, and with the match(), matchAll(), replace(), replaceAll(), search(), and split() methods of String.

Source link

Automated Workflows: Sending your form response to Discord

If you want to establish some nice automated integration between two or more applications, you can make use of low-code tools like Zapier or Integromat. These tools have over 1000 apps available for integration.

You can link up multiple applications and create a smooth automation workflow. 😎

smooth gif image

In this article, we’ll make use of Integromat to connect Discord to a form.

Creating our Integromat account

  • We’d open Integromat homepage and proceed to sign up/in.
  • Click on the Create a new scenario button


With the huge “+”, we can start adding an application and create connections with other applications.

Configuring a webhook

We’ll set up a webhook URL that we can send form data to and trigger appropriate reactions

  • So, we’d click the big “+” button and select the Webhooks application

(Never mind my sketches, you deserve a better artist 😭)

  • Select Custom webhook then select Add and give the custom webhook a name. We’d get a webhook URL that we will keep for later.

  • We’d add a new module


  • We’d select the Post a Message to discord, add a new connection with any text in the content and approve Integromat permissions to our Discord server. Then we should see the bot in our server:


  • We’d create a simple HTML form next to send data to the webhook URL by adding the URL to the action attribute. (This is just a demo form, you can choose how to send data and how your application should react to each form submission):
<!DOCTYPE html>
<html lang="en">
    <form method="post" action="https://hook.integromat.com/hxmcktv6o41acj46lcuw6vio7iqhyisg">
        <label for="firstname">First name</label>
        <input type="text" name="firstname" id="firstname">
        <br />
        <br />
        <label for="message">Message</label>
        <br />
        <textarea name="message" id="message" cols="30" rows="10"></textarea>
        <button type="submit">Submit</button>
  • Open your Integromat scenario, click on Run once, open the web page and send some data to access the placeholders.

  • We now have access to our form response placeholder. We’d head over to our scenario, click on the Discord module edit the content. Then activate the scenario:


  • Submit the form again and we can see our response



I hope you find this article helpful in creating an automated workflow between some applications you regularly use.

Though Integromat free plan has some limitations, it can pretty much satisfy some of your automation needs.
This is not any form of promotion, I am only sharing a tool I find useful.

Thanks for reading!

Source link

Difference between bootstrap and twitter bootstrap

Bootstrap is a CSS framework used in front-end applications – that is, in the user interface screen – to develop applications that adapt to any device.

In WordPress, for example, it can be installed as a theme or used to develop plugins or even within them to stylize their functions. The framework’s purpose is to offer users a more pleasant experience when browsing a site.

For this reason, it has several resources to configure the styles of the page elements and efficiently and facilitate the construction of pages that, at the same time, are adapted for the web and mobile devices.

The above shows why it is essential to know about a potential structure of this type

What is Bootstrap?
Bootstrap is a CSS framework developed by Twitter in 2010 to standardize business tools.

It was initially called Twitter Blueprint, and soon after, in 2011, it went open source, and its name changed to Bootstrap. It is now updated several times and is already in version 4.4.

The framework combines CSS and JavaScript to style the elements of an HTML page. This does more than change the colour of buttons and links.

It is a tool that offers interactivity on the page. It, therefore, provides several components that facilitate communication with the user, such as navigation menus, page controls, progress bars, etc.
In addition to all the functionalities offered by the framework, its main objective is to create responsive websites for mobile devices.

This means that the pages are designed to work on desktops, tablets and smartphones, in a simple and organized way.

Is There Any Difference Between Bootstrap and Twitter Bootstrap?
No, there is no difference between them. They are the same thing. Twitter Bootstrap is called Bootstrap in short form.

Hope you liked the post, kindly share it with your programmer friends.

Source link

Great chat with Devon on his new podcast DEVCODER TV

I’ve been following Devon’s journey for a while while I lurk around Career Karma.

When I heard he was starting a podcast, I reached out – and guess what! I got to be the first guest.

It was really nice to finally meet the real human and not just the avatar – and I think we had a great talk / and that you’d like it.

@sherifferek Talks with Devon Curtis on DEVCODER TV: The Mindset of Becoming a Developer Listen here!

: )

Source link

Is random() really random ?

Okay I admit, I am obsessed with all this “random” concept, my third article on this at dev community.
As we all know, computers are dumb machines, they just follow some algorithms, steps programmer tells them to do. So how can a computer randomly generate a number then? And even more importantly, on what basis we say something is actually random?
I spent this week researching over these questions that arose in my mind, and this article will be kind-of summary about that. So follow me for more of such content and connect with me on Twitter as well! (self endorsement is important).

So first let’s dive into the basic stuff. We all must have used Math.random() in JavaScript or srand() and rand() in C++ and similar counter-parts in all other languages. So how do they really work ?

These functions use some pre-defined algorithms to generate a random number. And as you might have got the question, “if it’s predefined procedure, then how can it be really random ?”
Well yes, they aren’t TRULY Random, they are called PSUEDO Random Number Generators.

If you want to dive deep into the algorithms of the same, here is one : Linear congruential generator
The method represents one of the oldest and best-known pseudo random number generator algorithms.

Also if you want me to write over these algorithms in simple words, do let me know in the comment section or my Twitter:)

So lets get back to our point, then how can we generate Truly Random number?
And even before this, why we actually need one? What’s the purpose of all this True Random thing ?

Well, randomness has a lot of applications in real life. Say for instance you are making a Dice game as your project, you will need a random() to generate a number in the dice. In previous times and still in general purposes, things such as a coin flip or a dice are supposed to be random or say fair for all parties involved. But is it really ?

Let’s have a look at Physics behind a coin flip.

There are multiple factors on which the result of coin flip may depend –
1) Which face is currently at the top
2) The weight distribution of the coin
3) The angular velocity and torque provided while flipping
4) The linear velocity and acceleration
5) Air density, pressure, humidity, air speed.
6) The friction coefficient of the floor where the coin lands and so on !!

There dozens of such factors involved in a simple coin flip, which makes it difficult to predict or manipulate the result, but it’s difficult, not Impossible !

Here’s an news article about that : Euro coin accused of unfair flipping

What makes such things feel random to us is the complexities involved, which are difficult for a normal person to solve.

And another very major and important application of randomness is Cryptography!
I will cover this one in my next article ( Link coming soon )

OKAY so just answer the question! How can we get Truly Random Numbers !!

Simple answer is “EXTERNAL ENTROPY”.

So, what’s entropy? Entropy is the measurement of uncertainty or disorder in a system. Good entropy comes from the surrounding environment which is unpredictable and chaotic. You can think of entropy as the amount of surprise found in the result of a randomised process: the higher the entropy, the lesser is the certainty found in the result.

Atmospheric noise, cosmic radiations, quantum particles are currently the best physical ways to do so.

In computing, a hardware random number generator (HRNG) or true random number generator (TRNG) is a device that generates random numbers from a physical process, rather than by means of an algorithm. Such devices are often based on microscopic phenomena that generate low-level, statistically random “noise” signals, such as thermal noise, the photoelectric effect, involving a beam splitter, and other quantum phenomena.

Again even these phenomenons are not 100% Truly Random ( this is debatable though ), but the thousands of factors involved in their calculations make them almost impossible to predict. For measuring these factors, we require external specialised hardware for the same.

You can have a look at RANDOM.ORG that claims to offers true random numbers to anyone on the Internet. The randomness comes from atmospheric noise, which for many purposes is better than the pseudo-random number algorithms typically used in computer programs.
Here’s the link : https://random.org

There are some other methods as well like mouse movements, delay between keyboard presses etc.
You can also have a look at these generators, who claim to be Truly random :
The following (non-exhaustive) list of websites claim to provide random numbers generated from a truly random source

1) Australian National University : QRNG( quantum random number generator ) : https://qrng.anu.edu.au/
2) Humboldt University of Berlin : QRNG( quantum random number generator ) :
3) HotBits : Generated by radioactive decay :

You can read about the theory behind their generators on their websites, I am not including those here, as it will make this article quite complicated ( it might be already for some of you ).

Thanks for your patience !
If you found this article useful, Share this !
It took a lot of time and efforts for this one, and yes, this topic isn’t done yet, stay tuned for the next article on this series, that will focus on Cryptographic aspect of randomness.

Connect With Me :

And recently as a hobbie, I have started photography, you can have a look at that here :

Source link

The story behind JS: how async works

We all know that JS is a single-threaded non-blocking asynchronous concurrent language.

But what does this actually mean?

Let’s find out:

Suppose we have a function that calls another function that calls one more function, such as:

function add(a,b) 
    return a+b;

function callAdd(a,b) 
    return add(a,b);

function finalFunc(a,b) 
    const addDigits = callAdd(a,b)

finalFunc(3,4); // Output: 7

We all know that finalFunc will call callAdd, callAdd will call add, and add will return the sum of these two numbers and we will get 7.

But what’s happening behind the scenes?

So, there is a thing called call stack in JavaScript which is a type of data structure that records basically where we are currently in our program.

It looks something like this:


And in here, this is how our program runs:

lets take a look at our code:

function add(a,b) 
    return a+b;

function callAdd(a,b) 
    return add(a,b);

function finalFunc(a,b) 
    const addDigits = callAdd(a,b)

finalFunc(3,4); // Output: 7

Here when we called the finalFunc function, it was recorded in the call stack, and inside that we called another function which was then called and got recorded in the call stack again, which called the add function and it gets recorded as we can see in our diagram.

The return statement then gets executed and the function is removed from the call stack.
then the return statement of callAdd function gets executed and it gets removed from the stack and then the finalFunc then calls the console.log function and it gets executed and then the finalFunc is removed from the call stack and the program ends.
ezgif.com-gif-maker (1).gif
So this is how our program actually runs inside JavaScript.

Correction: The code in this video is a bit incorrect, the actual code is the one written above.

Waiting for Callbacks and SetTimeout

Let us assume that callbacks and setTimeout are synchronous and we call them in our program. Then what do you think will happen?
The call stack waits until the processing of the current is done. So, yes, the call stack will have to wait till the timeout ends. Till then we won’t be able to do any task.

And suppose there is one callback that never returns. Then what?
Your code will be stuck forever. That’s why being asynchronous is important.

We did the normal function call in JS. But now let’s try setTimeout in our program. FYI setTimeout and callbacks are not part of the JS engine. They are part of browser API.

And now setTimeouts are something that waits to perform a particular action. But as we said JavaScript is a non-blocking language. Then where does this waiting go?

So what happens behind the scenes, in the case of timeouts, is that when a timeout is called it is shifted to a special place called callback queue or task queue.

The role of the callback queue is to hold the timeouts when they are complete and send it to the call stack when it’s empty.

But who checks if the call stack is empty or not?

This is where the event loop comes into play. The event loop keeps on checking if the queue and call stack are empty or not, if the task queue is not empty it checks if the call stack is empty or not, if the call stack is empty then it sends the timeouts to call stack one by one.

Something like this:

function add(a,b) 
    return a+b;

let a = add(2,3);

setTimeout(() => 
    console.log("hello world");
, 1000)

function callAdd() 

// Output: 
// callAdd
//hello world

This is how a browser looks and as we can see that JS engine is not the only thing that is present in the browser.


If we look at the above code, initially the call stack is empty, when the code starts running, first the console.log() function will come in the call stack and it will call the add function. The add function will execute and is removed from the stack, then console.log is executed and removed from the stack.

Next comes the settimeout, function that comes to the call stack but then it is moved to the browserAPI section and waits till the timer is up, and is moved to the task queue, till then callAdd function is called to the call stack, and is executed, then console.log function is called inside the call stack and is executed and removed and then callAdd function is removed.

And in between that the event loop keeps on checking if the call stack is empty or not, now as our call stack is empty, the event loop sends the setTimeout function from the task queue to the call stack which then calls the console.log() function which executes and removed from the call stack and finally setTimeout is removed from the stack and the program ends.


Now you must be wondering what this microtask queue is?
Well, it’s exactly the same as a callback queue except that all the callbacks functions are stored here and the Microtask queue has a higher priority over the callback queue. which means that if there is anything inside the microtask queue it doesn’t matter if the callback queue is full.

Until the microtask queue is not empty callback queue will not run.

If we made a callback function, then that is stored in the browser api till it gets resolved, it is then sent to the microtask queue and the event loop waits till the call stack is empty and then sends the callback function to the call stack and it executes.

So this was all about how async JS works. And yes, JS doesn’t like to wait so thanks to the event loop and the queues for the hard work.

Source link

13 Questions You Need to Ask Before Buying a Deep Learning Course

Have you considered taking a deep learning course? If so, then there are some questions that you need to ask before diving in. You may not know what you’re getting into with this type of course and it’s important to take the time and think about your needs and goals for buying a course. In this blog post we will discuss 10 questions that every learner should ask before buying a deep learning course!

1. What are the prerequisites?

One of the most important questions to ask is what the prerequisites are for the course. Do you need to have a certain level of programming experience? Are you comfortable with matrix operations and calculus? It’s important that you know what is required of you before buying a course, so that you don’t end up spending money on something that you can’t actually use.

2. What format is the course?

When you’re looking for a deep learning course, it’s important to consider what format the course will be in. Will it be mostly video lectures? Text-based? Or maybe there are interactive exercises included? Each learner has different preferences when it comes to learning, so you’ll want to make sure the course is in a format that will work for you.

3. Who is the instructor?

When you’re taking a deep learning course, it’s important to know who your instructor is. Do they have a lot of experience in the field? Are they active researchers in the area? Or are they just teaching the course because they know how to code? It’s important to have an instructor who is knowledgeable and passionate about the subject matter.

4. What type of learning style do you prefer?

Some people learn best by listening to lectures, while others prefer reading texts. Some people need lots of practice exercises while others can learn by just watching examples. It’s important to know what type of learner you are so that you can find a course that will work best for you.

5. Is the course up-to-date?

It’s important to make sure that any course you buy is up-to-date with the latest research and developments in the field. You don’t want to be learning outdated techniques that are no longer used in practice. Make sure to ask the instructor or course provider about this before buying a course.

6. What topics are covered?

Another important question to ask is what topics are covered in the course. Are you interested in deep learning for natural language processing? Neural networks? Computer vision? Make sure that the course you buy covers the topics that you’re interested in.

7. Is there a lot of theory or is it mostly hands-on?

Some people prefer to learn with a mix of theory and practice, while others prefer just to focus on exercises. It’s important to know what type of learner you are so that you can find a course that will work best for you.

8. How much time is required?

It’s important to know how much time is required for the course. If you’re only able to commit a few hours per week, then you’ll want to find a course that isn’t too intensive. If you have more time to spare, then you can look for a course that is more intensive.

9. What type of learner are you?

It’s important to know what type of learner you are before buying a deep learning course. Do you like lots of practice exercises? Or do you prefer listening to lectures? Make sure to consider your preferences before making a purchase.

10. What is the course’s refund policy?

It’s important to know what the course’s refund policy is before you buy it. Some courses may have a no-refund policy, while others may offer a money-back guarantee if you’re not happy with the product. Make sure to read the fine print before making a purchase.

11. How is the course delivered?

When you’re looking for a deep learning course, it’s important to consider how the course is delivered. Some courses may be delivered entirely online, while others may require you to attend in-person sessions. Make sure to consider your availability and whether or not you’re able to attend in-person sessions before buying a course.

12. What software is required?

Some courses may require you to have certain software installed on your computer in order to participate. Make sure you know what software is required before making a purchase. If you don’t have the required software, you may be unable to participate in the course.

13. What are the course’s prerequisites?

Some courses may have prerequisites that you need to meet in order to be eligible to participate. Make sure you know what the prerequisites are before making a purchase. If you don’t meet the prerequisites, you may not be able to take the course.

These are just a few of the questions you should ask before buying a deep learning course. Make sure to do your research and ask around to find the best course for you.

images.cv provide you with an easy way to build image datasets.
15K+ categories to choose from
Consistent folders structure for easy parsing
Advanced tools for dataset pre-processing: image format, data split, image size and data augmentation.

👉Visit images.cv to learn more

Source link

Creating a better date-picking experience with the DateRangePicker component

When crafting a search interface, it’s often enough to use what comes prepackaged with Algolia’s InstantSearch libraries. Each library comes in a different flavor of JavaScript for your ease of use. Each one has all the main pieces you need to craft a strong UI. 

Sometimes you want to go beyond what’s available. 

At that point, you’re presented with two options: craft your own with our connector APIs or find a pre-built custom widget.

It should come as no surprise to anyone that knows me that when presented with wanting a React date picker for December’s coding challenge, I wanted to write as little code as possible to make it work, but I also wanted the best UI possible for Santa. When it came to bonus challenge number 5, I needed something extra. My first stop? The Algolia Code Exchange!

After a quick search around date components, I found exactly what I needed: the aptly-named @algolia/react-instantsearch-widget-date-range-picker!

Setting up the project

If you’d like to follow along, you’ll need to install a new React InstantSearch project. The easiest way to do that is to run the following command:

 npx create-instantsearch-app concert-search 
 --app-id latency 
 --api-key 059c79ddd276568e990286944276464a 
 --index-name concert_events_instantsearchjs 
 --template "React InstantSearch"

This monster command will set up a React InstantSearch project and connect it to Algolia’s hosted concert Index. Change directory into the created folder and run yarn start for a solid starting point.

At this point, you’ve got a full search experience for a set of concerts. 

If you want to filter by date, you could set up a <RefinementList> component and set its attribute prop to date, but those dates are Unix timestamps (for easiest comparisons). This isn’t ideal for the user experience. Let’s make that better.

Installing and configuring the widget

To get the date range picker up and running, we need to install a couple of dependencies.


npm install @algolia/react-instantsearch-widget-date-range-picker @duetds/date-picker

This will install the official Algolia React Date picker widget and its dependency the Duet Date picker.

From here, we need to import the packages into our src/App.js file and initialize the Duet Date Picker for use.

// Add right after the imports included in the create-instantsearch-app code

import  DateRangePicker  from '@algolia/react-instantsearch-widget-date-range-picker';  
import  defineCustomElements  from "@duetds/date-picker/dist/loader";

// Defines the custom elements from the date picker for use on the window object  

Now that these packages are imported, we’re ready to get this on the page.

Adding the date range picker

To add the picker to the page, we need to select a spot within the <InstantSearch> component. The base of the app is a search-panel. By default, all we have inside this is the results, but we can add a filter panel, as well.

<InstantSearch _searchClient_=searchClient indexName="concert_events_instantsearchjs">  
  <div className="search-panel">  
    <div className="search-panel__filters">  
      <DateRangePicker attribute="date" />  

    <div _className_="search-panel__results">

      //... Results code


The DateRangePicker accepts an attribute prop. This prop accepts a date-based attribute from the hits in our Index. 

Quick note: The DateRangePicker accepts a Unix timestamp with milliseconds since the Epoch, not seconds. Depending on your data structure, you may need to create a secondary timestamp in your data.

When you view the rendered page, you should now have a date picker. There are a few small UI snags to clean up. 

The Duet Date picker uses a slew of CSS Custom Properties for much of its styling. At the start of our src/App.css file, we need to paste those in and configure for our app (as appropriate).

  --duet-color-primary: #3c4ee0;  
  --duet-color-text: #333;  
  --duet-color-text-active: #fff;  
  --duet-color-placeholder: #666;  
  --duet-color-button: #f5f5f5;  
  --duet-color-surface: #fff;  
  --duet-color-overlay: rgba(0, 0, 0, 0.8);  
  --duet-color-border: #d6d6e7;  

  --duet-font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,  
  Arial, sans-serif;  
  --duet-font-normal: 400;  
  --duet-font-bold: 600;  

  --duet-radius: 3px;  
  --duet-z-index: 600;  

The two picker areas are a little close together still, so let’s fix that with a little CSS, as well. This can go in src/App.css but should be closer to the bottom. There are many ways to get the space between the two items, the quick and easy solution is to use CSS Grid and the gap property.

  display: grid;  
  gap: 1rem;  

And with that, we have a functioning, user-friendly date picker. No more dealing with Unix timestamps and conversions.

Take this further

This works great in the small sample dataset, but can also be brought into any Algolia InstantSearch application. If you’re looking to take this example further, create a better UI around each Hit by editing the hit component in src/App.js. You could also show the current filters applied with the CurrentRefinements component.

Source link

Binary search is not for sorted arrays only !

While talking about ‘ Binary Search ‘ , we consider that it will only work for “Sorted arrays” , but that’s not the condition.

It will work for ” Unsorted arrays” also ,

yes but only one kind of “unsorted array” ,
i.e., The Rotated Array.

It can be done in O(log n) time complexity , like a binary search , but it uses different method .
It uses “adjusted divide and conquer algorithm”
The DAC👍

And ssshhhh 🤫 it will be solved recursively only

Source link

Nullish Coalescing??

Nullish coalescing?

what is that word. Hmm… koala…sing?
koala siningbad joke alert!!!

Hello everyone, I’m Saksham and I am back again with a new blog about an es6 feature which I personally found really cool and is pronounced as Null-ish koh-uh-les-ing.

Yeah, it took me some time too, to get the spelling right haha.

What is it?

Nullish coalescing is a short circuiting operator denoted by ‘??

Purpose of this operator is very simple. Do you know about short circuiting OR operator? Its the same but with some precision, we can say.

lets first discuss about short circuiting OR operator in short.

OR operator, other that using it in getting boolean values, can be used directly if we want to evaluate something from left to right and get the result
Lets take an exampe to understand it much better

const name = "Saksham";
const myName = name || "New User";

console.log("My name is: ", myName) //My name is Saksham

const anotherName = "";
const newName = anotherName || "New User";

console.log("Welcome ", newName) //Welcome New User

As we can see in the above example, When there was a value in the right hand side it returned that but when the string was empty it returned the left hand side value.

That’s because OR operator check for the right hand side value and if its a falsy value (0, “”, [], null, undefined, NaN) then it returns the left side (no matter what value is there).

This is how OR operator works.

Similar is the case of nullish coalescing operator, the difference is that it will return the right hand side only when the left side give null or undefined.

How it works

Lets take another example

const setHeight = 0;
const getHeight = setHeight || 100;

console.log("Height is set to ", getHeight); // Height is set to 100

Here setHeight was 0 but as it is a falsy value 100 was printed. But as we know heights can be 0, This is where nullish coalescing operator is used.

In case of nullish coalescing operator, when the left hand side is null or undefined, only then it will return the right hand side.

const setHeight = 0;
const getHeight = setHeight ?? 100;

console.log("Height is set to ", getHeight); // Height is set to 0

Chaining operators

We can add multiple statements while using nullish coalescing operator

const firstname = null
const lastname = undefined

console.log("My name is ", firstname ?? lastname ?? "Anonymous") 
//My name is Anonymous

Here we chained 2 operators, the first one returned null due to which it moves to the second one, but as I said that it will return it without checking and hence returns lastname (which is undefined) but we can see that there is another operator right next to it and hence it becomes a left hand side for the second operator and it is again checked and as its undefined the answer comes out to be Anonymous.

This is how chaining works. But you know we cannot use chaining with OR and AND operators like above, if we try, it will give an error as it is not able to decide whom to give more precedence.

So to remove that error we put one of the condition in parenthesis.

const firstname = null
const lastname = undefined

console.log("My name is ", firstname || lastname ?? "Anonymous") 
//Uncaught SyntaxError

console.log("My name is ", (firstname || lastname) ?? "Anonymous") 
//My name is Anonymous

And this is how ‘??’ works. That’s all about this operator.
Thank you for reading this blog ❤️

Source link