JavaScript Practical Interivew Questions
Javascript
Mamta Kumawat  

JavaScript Practical Interview Questions: What will be the output of the following code ?

Understanding the JavaScript Code: A Breakdown of Conditional Logic and Template Literals

In this blog post, we’ll break down a simple yet insightful piece of JavaScript code and explain how it utilizes conditional logic, destructuring, and template literals to create dynamic greetings based on input.

Here’s the code we’ll be analyzing:

const greeting = (person) => {
   const name = person ? person.name : "stranger";
   return `Howdy, ${name}`;
};
console.log(greeting({ name: "Alice" }));
console.log(greeting(null));
1. Function Definition with Arrow Syntax

The function is defined using an arrow function syntax. Arrow functions are a more concise way of writing functions in JavaScript. The function greeting takes one parameter, person, and returns a greeting string that includes the person’s name or “stranger” if no valid name is provided.

const greeting = (person) => {
// function body
};
2. Conditional (Ternary) Operator

Inside the function, there’s an expression:

const name = person ? person.name : "stranger";

This is a classic use of the ternary operator, a shorthand for an if-else statement. The ternary operator works as follows:

  • If person exists (i.e., is truthy), person.name is assigned to the variable name.
  • If person is falsy (like null, undefined, or an empty object), "stranger" is assigned to name.

The ternary operator has three parts:

  • The condition (person): If person is truthy, the condition evaluates to true.
  • The value if true (person.name): If the condition is true, person.name is returned.
  • The value if false ("stranger"): If the condition is false, "stranger" is returned.

This behavior ensures that the code handles scenarios where person might be null, undefined, or not provided.

3. Template Literals

The function then returns a greeting message using a template literal :

return `Howdy, ${name}`;

emplate literals, enclosed in backticks (`), allow us to embed expressions directly within strings using ${}. In this case, the expression ${name} is dynamically replaced with the value of the name variable, whether it’s "Alice" or "stranger", depending on the input.

4. Calling the Function

The function is called twice with different inputs:

console.log(greeting({ name: "Alice" }));
console.log(greeting(null));

In the first call, an object with the property name: "Alice" is passed in. Since the person is truthy, the name is set to "Alice", and the function returns the string "Howdy, Alice".

In the second call, null is passed as the argument. Since null is falsy, the name is set to "stranger", and the function returns the string "Howdy, stranger".

5. Console Output

Let’s analyze the outputs:

  1. First call:
console.log(greeting({ name: "Alice" }));
  • person is an object with a property name, so name = person.name evaluates to "Alice".
  • The returned string is: "Howdy, Alice".

2. Second call:

console.log(greeting(null));
  • person is null, which is falsy.
  • Since person is falsy, "stranger" is assigned to name.
  • The returned string is: "Howdy, stranger".

Thus, the output would be:

Howdy, Alice
Howdy, stranger
6. Why Use This Pattern?
  • Robustness: The ternary operator ensures that even if person is missing or null, the code doesn’t throw an error and handles it gracefully by providing a default name (“stranger”).
  • Clean and Concise Code: Using a ternary operator and template literals makes the code cleaner and easier to understand compared to traditional if-else statements.
  • Flexible Function: The function is flexible enough to handle different inputs, whether a valid person object or null, providing an appropriate greeting each time.
7. Possible Improvements

While this code works well, you could consider a few enhancements:

  • Destructuring: If you expect person to have a consistent structure (i.e., always containing a name property), you could use destructuring to extract name directly
const greeting = ({ name = "stranger" }) => Howdy, ${name};

This would make the code a bit more concise while still providing the default value “stranger” if name is not defined.

Type Checking: If you expect person to sometimes be an object without the name property or a non-object type, you might want to perform additional type checking

Conclusion

This code provides a simple yet effective way of greeting someone based on input, showcasing the use of the ternary operator, template literals, and arrow functions in JavaScript. The handling of different types of input makes the function robust and adaptable to different scenarios, making it a good example of modern JavaScript practices.

Can you also try this : (data1 === data2) // false. WHY ?

Leave A Comment