top of page
Writer's pictureThe Tech Platform

Object Literals in JavaScript to write complex conditions?

Updated: Jun 9, 2023



A JavaScript object literal is a concise way to create an object by specifying its properties and values using curly braces. It helps encapsulate data in a structured format and reduces reliance on global variables, thereby avoiding potential issues when combining code.


The syntax for creating an object literal is as follows:

var myObject = {
    propertyName1: value1,
    propertyName2: value2,
    propertyName3: value3,
    // ...
};

In this syntax:

  • Each property is represented by a propertyName followed by a colon (:) and its corresponding value.

  • Multiple properties are separated by commas (,), except for the last property.

  • The comma after the last property is optional.

Here's an example using the provided code snippet:

var myObject = {
    sProp: 'some string value',
    numProp: 2,
    bProp: false
};

In this example, myObject is an object with three properties:

  • sProp with the value 'some string value'.

  • numProp with the value 2.

  • bProp with the value false.


How to use Object Literals in JavaScript to write complex conditions?

To write complex conditions in JavaScript using object literals, you can structure your code in a more readable and maintainable way compared to using long lists of if/else statements or switch cases. Object literals provide a concise syntax for defining and organizing conditions based on different cases. Here's an example illustrating how to use object literals for complex conditions:

function getDogQuote(breed) 
{
  var quotes = 
  {
    retriever: "Retrievers are friendly and intelligent.",
    bulldog: "Bulldogs are known for their stubbornness.",
    poodle: "Poodles are highly trainable and elegant.",
    default: "Sorry, we don't have information about that breed."
  };

  return quotes[breed] || quotes.default;
}

In this example, we define an object called quotes using an object literal. Each property within the object represents a dog breed, and the corresponding value is the quote associated with that breed. The default property is used to handle cases where the provided breed is not found.


To retrieve the quote for a specific dog breed, you can simply access the corresponding property of the quotes object using the breed as the key. If the breed is found, the associated quote will be returned. If the breed is not found, the default quote will be returned.

Here's how you can use the getDogQuote function:

var breed = "retriever";
var quote = getDogQuote(breed);
console.log(quote); // Output: "Retrievers are friendly and intelligent."

breed = "bulldog";
quote = getDogQuote(breed);
console.log(quote); // Output: "Bulldogs are known for their stubbornness."

breed = "poodle";
quote = getDogQuote(breed);
console.log(quote); // Output: "Poodles are highly trainable and elegant."

breed = "unknown";
quote = getDogQuote(breed);
console.log(quote); // Output: "Sorry, we don't have information about that breed."

By using object literals, you can easily add or modify conditions without cluttering your code with multiple if/else statements or switch cases, resulting in cleaner and more maintainable code.


An Alternative

An alternative approach to achieve the same functionality in a neater way is by using an object to map the conditions to their respective responses. Here's an example:

function getDogQuote(breed) {   
    var breeds = {     
        retriever: "Retrievers are friendly and intelligent.",     
        bulldog: "Bulldogs are known for their stubbornness.",     
        poodle: "Poodles are highly trainable and elegant."   
    };    
    
    return breeds[breed.toLowerCase()] ?? "Quote not found"; 
} 

In this alternative approach, we create an object called breeds where the keys represent the conditions (dog breeds) and the values represent the corresponding responses (quotes).

To retrieve the quote for a specific breed, we use the square bracket notation (breeds[breed.toLowerCase()]) to access the value associated with the provided breed. The breed.toLowerCase() is used to ensure case-insensitive matching.

The ?? operator is used for nullish coalescing. It checks if the value obtained from breeds[breed.toLowerCase()] is null or undefined. If it is, the expression evaluates to the default string "Quote not found" and is returned as the result.

Here's an example usage:

var breed = "retriever"; 
var quote = getDogQuote(breed); 
console.log(quote); // Output: "Retrievers are friendly and intelligent."  

breed = "bulldog"; 
quote = getDogQuote(breed); 
console.log(quote); // Output: "Bulldogs are known for their stubbornness."  

breed = "poodle"; 
quote = getDogQuote(breed); 
console.log(quote); // Output: "Poodles are highly trainable and elegant."  

breed = "unknown"; 
quote = getDogQuote(breed); 
console.log(quote); // Output: "Quote not found"

Using an object for mapping conditions to responses provides a more elegant and maintainable solution compared to lengthy if/else statements or switch cases. It allows you to easily add or modify conditions without cluttering the code and provides the flexibility to handle default responses if needed.


More Complex Logic

In scenarios where you need to perform more complex logic within your conditions, you can pass a function as the value for your object keys and execute the corresponding response.


Here's an example:

function calculate(operation, num1, num2) {
  var calculations = {
    addition: function(num1, num2) {
      return num1 + num2;
    },
    subtraction: function(num1, num2) {
      return num1 - num2;
    },
    multiplication: function(num1, num2) {
      return num1 * num2;
    },
    division: function(num1, num2) {
      return num1 / num2;
    },
    default: function() {
      return "Invalid operation";
    }
  };

  return calculations[operation]?.(num1, num2) ?? calculations.default();
}

In this example, we have a function called calculate that takes an operation (e.g., "addition", "subtraction", etc.) along with two numbers. The calculations object contains keys that represent different operations, and the corresponding values are functions that perform the desired calculations.


To execute the appropriate response, we use calculations[operation]?.(num1, num2). The optional chaining operator (?.) ensures that the function is only executed if it is defined. If the function is not defined for the given operation, the expression falls through to the default return value.


Here's how you can use the calculate function:

console.log(calculate("addition", 5, 3)); // Output: 8
console.log(calculate("subtraction", 10, 4)); // Output: 6
console.log(calculate("multiplication", 2, 6)); // Output: 12
console.log(calculate("division", 15, 3)); // Output: 5
console.log(calculate("exponentiation", 2, 3)); // Output: "Invalid operation"

By passing functions as values within an object, you can perform more complex logic inside your conditions. The optional chaining operator allows you to handle cases where the desired function is not defined, ensuring a fallback to a default response if needed.

0 comments

Opmerkingen


bottom of page