Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
Elegant way to return from try...catch - Javascript

Elegant way to return null. Don't want to return it twice.

Option 1:

function readSessionStorage(key) {
    try {
        if (typeof window !== 'undefined') {
            return JSON.parse(window.sessionStorage.getItem(key));
        }
        return null;
    } catch {
        return null;
    }
}

Option 2:

function readSessionStorage(key) {
    try {
        return JSON.parse(window.sessionStorage.getItem(key));
    } catch {
        return null;
    }
}

Option 3: If we pick this option, why should we do this?

function readSessionStorage(key) {
    try {
        if (typeof window !== 'undefined') {
            return JSON.parse(window.sessionStorage.getItem(key));
        }
    } catch {}
    return null;
}

Why do I need to do this?

I'm getting DOMException if I try to get window.sessionStorage, and hence I need to use try...catch.

function readSessionStorage(key) {
    if (typeof window !== 'undefined' || !window.sessionStorage) {
        return JSON.parse(window.sessionStorage.getItem(key));
    }
    return null;
}

Original Code:

function readSessionStorage(key) {
    if (typeof window !== 'undefined') {
        return JSON.parse(window.sessionStorage.getItem(key));
    }
    return null;
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Well, that's odd. No response in seven months? Well, I was looking for something like this myself, and couldn't find an eloquent solution. I created my own.


Edit: upon further work, I found that the null safety operators do exist in JS! Yay! The function below is still quite helpful, perhaps more so now since one can use the safety operator to get to the precise value desired, then handle it correctly.


Consider using a function similar to this:

const defineCheck = (item, defaultVal = '') => { 
    try {
        return (item !== null && item !== undefined) ? item : defaultVal;
    } catch {
        return defaultVal;
    }
}

This might not exactly fit your needs, but you can make your function however you want. This will keep the clutter out of your important business or UI logic, so you and others can focus on what is important.

Sample usage (if account is known to have an expected value):

tempForm.ExpirationDate = defineCheck(account.expirationDate);
tempForm.LicenseType = defineCheck(account.licenseType, 'Nada');

With null safety:

tempForm.ExpirationDate = defineCheck(account?.license?.expireDate);
tempForm.LicenseType = defineCheck(account?.license?.licenseType, 'Nada');

I hope you and others find this useful, or better yet, share a much better way to deal with this problem. I'd hoped the C# null safety check operator made its way to JS, but no luck (e.g., "account?.license?.licenseType ?? 'Nada'")

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda