How to greet people differently by using JavaScript

Hello friends, In this JavaScript tutorial, I will show you how to greet people differently according to the first letter of their name. I hope this is going to be very much useful. Here we are going to create our custom JavaScript function to perform this task.

In the example below, we are greeting people using JavaScript.

Greet People in JavaScript

var speakWord = "Hello";
function speak(name) {
  console.log(speakWord + " " + name);
}
var speakWord = "Good Bye";
function speak(name) {
  console.log(speakWord + " " + name);
}
(function() {
  var names = ["Rishabh", "John", "jen", "Jason",
    "Shubham", "Bahu", "Divyesh", "Prajwal", "Priyesh", "jim"];
  for (var i = 0; i < names.length; i++) {
    var firstLetter = names[i].charAt(0).toLowerCase();
    if (firstLetter === 'j') {
      byeSpeaker(names[i]);
      function byeSpeaker(names) {
        console.log("Good Bye " + names);
      }
    }
    else {
      helloSpeaker(names[i]);
      function helloSpeaker(names) {
        console.log("Hello " + names);
      }
    }
  }
}
)();

Let’s try understanding the above program step by step :

  • In the code, I have taken four variables – speakWord, names, firstLetter and i.
  • In speakWord, there are two strings one is “Hello” and another one is “Good Bye”.
  • In names, we have taken some strings, here we are taking few names as a variable.
  • In firstLetter, at first, we are changing the first letter to lower case and then we are checking if it is ‘j’ or not.
  • i is an integer. we are using i to set a condition.
  • In the code there are three functions speak(), helloSpeaker and byeSpeaker.
  • speak(), it just prints the Hello or Good Bye and the names according to the condition.
  • In helloSpeaker, after checking the condition that the first letter does not start from ‘J’ or ‘j’ it prints the string which says Hello + name.
  • In byeSpeaker, after checking the condition that the first letter is from ‘J’ or ‘j’ it prints the string which says Good Bye + name.

To check the output go to the console and check it.

( for chrome -> right click -> inspect element -> console tab )

Output:

Hello Rishabh
Good Bye John
Good Bye jen
Good Bye Jason
Hello Shubham
Hello Bahu
Hello Divyesh
Hello Prajwal
Hello Priyesh
Good Bye jim

 

You may also learn,

One response to “How to greet people differently by using JavaScript”

  1. Prajwal Rao says:

    Good it’s working

Leave a Reply

Your email address will not be published. Required fields are marked *