Chatbots are getting more and more popular so let’s create one. You will only need JavaScript and HTML so you can run this chatbot in your browser.

You can find full code at the end of this article (it is only 49 lines of code).

This article will cover:

P.S. -> read this article if you want to double your salary as a programmer

How The Chatbot Works?

People usually think creating an effective chatbot is very complicated and your bot needs to develop self-awareness to be convincing.

That is not true.

Especially when you want to create some specialized chatbot. For example, chatbot for your business, or a chatbot that has specialized knowledge.

The more specific it is the better will it (appear to) work.

How Does A Chatbot Work?

The chatbot works by connecting user INTENT with a predefined ANSWER for that intent. So the most difficult task for the chatbot is to recognize user intent. And if that is done correctly, the chatbot will appear intelligent.

Creating JS Chatbot Step-By-Step

First we need a basic HTML structure. And inside of that structure we will put all our JavaScript (chatbot) code:

<!DOCTYPE html>
<html>
  <head>
    <title>Real JS Chatbot</title>
  </head>
  <body>
    <script>
      // all JS code goes here
    </script>
  </body>
</html>

To accept user input we will simply use prompt() function that will show a pop-up to the user with an input field.

Inside that pop-up users will see the chatbot’s response and be able to ask the next question.

So the simplest chatbot looks something like this:

function robotSays(answer = 'ask me a question...') {
  const question = prompt(answer);
  robotSays('interesting... tell me more...');
}
robotSays();

This simple chatbot is not very smart. Basically whatever you ask it always gives you the same answer: “interesting… tell me more…” – which is not bad but not good either.

The last line of the code starts the chatbot logic. After that, the function robotSays keeps calling itself after each question you send to the chatbot.

At he moment we’re not giving any question-specific answers since we’re not using the question variable at all. So let’s refactor our code a little bit.

function getRobotAnswer(question) => {
  return 'interesting... tell me more...';
}

function robotSays(answer = 'ask me a question...') {
  const question = prompt(answer);
  const newAnswer = getRobotAnswer(question);
  robotSays(newAnswer);
}
robotSays();

This code is working the same as before but we now enabled the possibility to provide a different answer to our users depending on what they ask our chatbot.

The robotSays function doesn’t need to be changed anymore. And all the changes will be done in the “thinking” part of our code, i.e. getRobotAnswer function.

What Are We Building?

Since chatbots work best if they’re specialized, we’re going to build our bot to work best when meeting new people. So it can answer questions about itself.

This code will work just fine for other specialized use cases. You just need to change the list of intents and answers and your chatbot will work just fine.

The best format for storing this information is JavaScript object. The object keys are going to be intents and object values are going to be the answers.

const robotMemories = {
  name: 'my name is JSBot',
  age: 'I am 2 minutes old',
  color: 'my favorite color is green',
};

And now, the task is to match an intent of a question with the correct key in our robotMemories. For example:

“what is your name

or

“can you tell me your name

needs to be matched with the key name in our robotMemories object. So that the chatbot can respond with:

“my name is JSBot”

How To Do The Intent-Answer Matching?

We will simply go through every word of the question and try to match it with our JavaScript object key. So it’s very simple.

First we turn every question into an array of words:

const questionArray = question.split(' ');

Then we find the first matching key from the robotMemories object. If there is no match then the default chatbot answer is “I do not understand”.

const robotMemories = {
  name: 'my name is JSBot',
  age: 'I am 2 minutes old',
  color: 'my favorire color is green',
};

function getRobotAnswer(question) {
  const questionArray = question.split(' ');
  let robotAnswer = 'I do not understand';
  for (let questionWord of questionArray) {
    if (robotMemories[questionWord]) {
      robotAnswer = robotMemories[questionWord];
      break;
    }
  }
  return robotAnswer;
}

How To Improve Chatbot AI?

One obvious thing that can happen is that the same things can be said in different ways. This means the same intent can be expressed with different words.

For example, you could ask someone:

“what is your age”

or

“how old are you”

BUT

You probably notice that our chatbot will not understand our second question because there is no “old” keyword in robotMemories object.

One way to fix that is to have duplicate answers in our JavaScript object:

const robotMemories = {
  age: 'I am 2 minutes old',
  old: 'I am 2 minutes old',
};

But that is a very bad programming. Takes too much space and it’s harder to maintain. So a better solution would be for each answer to have multiple keys.

Something like this:

const robotMemories = {
  'age, old': 'I am 2 minutes old',
};

Now that we have this multiKey we have to find a way to way to confirm if either age or old is mentioned in the question of our users.

And we can do that with the following function:

function getMatchingKey(questionWord) {
  let matchingKey;
  for (let multiKey in robotMemories) {
    const keys = multiKey.split(', ');
    const key = keys.find(k => k === questionWord);
    if (key) {
      matchingKey = multiKey;
      break;
    }
  }
  return matchingKey;
}

And that is it.

If we ask questions “what is your age” or “how old are you”, we will get the correct answer in both cases.

All that is left to do now is to improve the robotMemories object by adding more intent keys and answers. And I’m very excited to see what awesome chatbots you will develop.

const robotMemories = {
  'who are you, name': 'my name is JSBot',
  'age, old, born': 'I am 2 minutes old',
  color: 'my favorite color is green',
};

Also notice how intent doesn’t have to be a single word.

Full JavaScript Chatbot AI Code

<!DOCTYPE html>
<html>
  <head>
    <title>Real JS Chatbot</title>
  </head>
  <body>
    <script>
      const robotMemories = {
        'who are you, name': 'my name is JSBot',
        'age, old, born': 'I am 2 minutes old',
        color: 'my favorite color is green',
      };

      function getMatchingKey(questionWord) {
        let matchingKey;
        for (let multiKey in robotMemories) {
          const keys = multiKey.split(', ');
          const key = keys.find(k => k === questionWord);
          if (key) {
            matchingKey = multiKey;
            break;
          }
        }
        return matchingKey;
      }

      function getRobotAnswer(question) {
        const questionArray = question.split(' ');
        let robotAnswer = 'I do not understand';
        for (let questionWord of questionArray) {
          const matchingKey = getMatchingKey(questionWord);
          if (matchingKey) {
            robotAnswer = robotMemories[matchingKey];
            break;
          }
        }
        return robotAnswer;
      }

      function robotSays(answer = 'ask me a question...') {
        const question = prompt(answer);
        const newAnswer = getRobotAnswer(question);
        robotSays(newAnswer);
      }

      robotSays();
    </script>
  </body>
</html>

P.S. -> read this article if you want to double your salary as a programmer

TAGS: chatbot javascript, javascript chatbot, javascript ai chatbot, how to create a chatbot in javascript, chatbot framework javascript, create chatbot using javascript, javascript chatbot in 10 minutes, make a chatbot with javascript, html chatbot javascript, how to write a chatbot program in javascript, javascript chatbot gui, chatbot html css javascript code, javascript chatbot python, chatbot reply javascript, create a chatbot in javascript, best ways to use javascript in a chatbot, chatbot using html and javascript, chatbot html css javascript, build an ai chatbot javascript, javascript chatbot icon, how to build a chatbot in javascript, how to program a chatbot in javascript, javascript npm chatbot, free pure javascript chatbot library, chatbot with javascript, javascript chatbot application, complete chatbot javascript, javascript chatbot nodejs, javascript chatbot tutorial, high-quality chatbot free javascript, chatbot javascript template, javascript chatbot code, telegram chatbot javascript, build a chatbot with javascript, javascript chatbot npm, javascript chatbot front end, chatbot using javascript, chatbot javascript framework, how to program a chatbot javascript, javascript chatbot source code, chatbot perform functions in javascript, javascript chatbot library, chatbot reply function javascript, chatbot in javascript, build your own javascript chatbot, a chatbot that uses javascript, chatbot open source javascript, how to make a chatbot in javascript, javascript chatbot framework, chatbot api javascript npm, chatbot ai software for javascript, build a chatbot in javascript, chatbot reply javascript param, capture user input javascript chatbot node.js, simple chatbot using javascript, how to build a chatbot from scratch in javascript, javascript chatbot ai, how to create a chatbot using html and javascript, chatbot tutorial javascript, build a chatbot with javascript website, how to style a javascript chatbot, pure javascript chatbot library, build chatbot javascript, ai chatbot javascript, browser chatbot javascript, creating chatbot using javascript, a.i. chatbot source code javascript, how to make a javascript chatbot, how to code a chatbot in javascript, sample chatbot code javascript, react javascript chatbot, javascript deep learning chatbot, simple chatbot javascript, chatbot library javascript, javascript chatbot interface, creating a chatbot in javascript, chatbot doing functions javascript, chatbot github javascript, chatbot source code in javascript, a.i. chatbot sourcecode javascript, open source javascript chatbot, chatbot javascript code, first javascript chatbot, create a pseudo ai text chatbot with javascript prompts console and html5,