Code Wars: Personalized Message

Breaking down code war challenges in a simple and understandable way.

The Question:

Create a function that gives a personalized greeting. This function takes two parameters: name and owner. Use conditionals to return the proper message.

If name = owner, greet Hello boss. If name is not = owner, greet Hello guest.

Let's analyze the question.

We are asked to create a function that takes two parameters and returns a personalized greeting.

Let's simplify it by creating a basic function.

function(){
//Your Code Goes Here
}

Now, this function takes two parameters, name and owner. So, add the parameters to the function as below.

Note: Parameters goes into the Parenthesis () as shown below and remember to add a comma between the parameters.

function(name, owner){
//Your Code Goes Here
}

So far, we understood the question and wrote a basic function with parameters.

The question states to use conditionals to solve this challenge. For this question, we will use if conditional statement.

Let's move on to the solution.

The Solution:

The syntax for the if statement is:

//Syntax
if (condition) {
  // This code will get executed.
} else {
  // if the above code is false, this block of code will be executed automatically.
}

See how the above syntax will look like in action as follows:

function greet(name, owner) {
  if (name === owner) {
    return "Hello boss";
  } else {  
    return "Hello guest";
  }
}

We are checking if the name = owner by using === (more about === in the note) and if it is true, then return Hello boss. Otherwise, return Hello guest.

Note: === operator will check for both value and type i.e; in our case, the type is a string, and the value is name and owner. Both name and the owner should exactly match the value and type. Otherwise, the code will execute the else statement. If you want some flexibility, use the == operator.

If we call the function with parameters, it will return either Hello boss or Hello guest depending on the condition.

When you call this function wrap the parameters around " " because the parameters are strings.

So let's call the function as shown below and see how our code works.

function greet(name, owner) {
  if (name === owner) {
    return "Hello boss";
  } else {  
    return "Hello guest";
  }
}

greet("Kiran", "Kiran");
greet("Kiran", "Kumar");

The result will be:

greet("Kiran", "Kiran"); //  Hello boss

greet("Kiran", "Kumar"); // Hello guest

Final Words:

If you made this far and liked it. Give a thumbs up and share it with others. Also, if you have any queries, feel free to comment.