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
personexists (i.e., is truthy),person.nameis assigned to the variablename. - If
personis falsy (likenull,undefined, or an empty object),"stranger"is assigned toname.
The ternary operator has three parts:
- The condition (
person): Ifpersonis truthy, the condition evaluates to true. - The value if true (
person.name): If the condition is true,person.nameis 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:
- First call:
console.log(greeting({ name: "Alice" }));
personis an object with a propertyname, soname = person.nameevaluates to"Alice".- The returned string is:
"Howdy, Alice".
2. Second call:
console.log(greeting(null));
personisnull, which is falsy.- Since
personis falsy,"stranger"is assigned toname. - 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
personis 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-elsestatements. - 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
personto have a consistent structure (i.e., always containing anameproperty), you could use destructuring to extractnamedirectly
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 ?
