Choosing the Optimal Way to Write Code Depends on Complexity

Michael NwoguMichael Nwogu
1 min read

When working with JavaScript or TypeScript, object lookup is often more efficient than using multiple if statements.

🚀 Example: Object Lookup (O(1))—Fast & Scalable

const obj: { [key: string]: string } = {
    key1: "value1",
    key2: "value2"
};

const getObj = (key: string): string => obj[key] ?? "Value does not exist";

Better Readability & Maintainability
Constant Time Complexity (O(1))
Easier to Scale— Just Add Key-Value Pairs

Using Multiple if Statements (O(n)) – Less Optimal

const getObj = (key: string): string => {
    if (key === "key1") return "value1";
    if (key === "key2") return "value2";
    return "Value does not exist";
};

Becomes Harder to Maintain as Keys Grow
Slower for Large Datasets (O(n))

🔥 But context matters!

Not every problem has a one-size-fits-all solution. Sometimes, the most optimal way to write code depends on its complexity and relevance to the use case.

For simple lookups? Object lookup wins.
For complex conditions? Conditionals may be necessary.

What’s your take? Do you always go for object lookup, or do you sometimes prefer if statements?👇💬

0
Subscribe to my newsletter

Read articles from Michael Nwogu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Michael Nwogu
Michael Nwogu