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

211
Vistas
scope of if statement in javascript compared to python

I have a function in react where i want to do :

   renderPost(data) {
        const dateStr = new Date(data.pub_date).toLocaleString();
        const img='empty'
        if (data.header_image_url.url!=null) {
            const img=data.header_image_url.url}
        else {
            const img="/app/frontend/img.png"}
        return (
            <div className="card mb-4">
            <Link to={`/post/${data.id}`}> <img src={img} className="card-img-top" alt=""/> </Link>

But it's not working like python : the const img inside the {} in the if and else statements dont take effect and dont override my const variable declaration above.

How can i do that ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You have two problems here.

You can't change the value of a const. That's the whole point of consts! If you want to change it, use let.

Declaring a variable in a different scope shadows the variable in the wider scope. It doesn't overwrite it. Don't use const (or let) inside the block.


There is a school of thought which says you should avoid overwriting variables in favour of code structures where they are assigned in a single place. This can make code more readable.

In this case, each branch of the if does nothing except make an assignment to the same place.

This is the ideal place to use a conditional operator.

const img = data.header_image_url.url != null
     ? data.header_image_url.url
     : "/app/frontend/img.png";

… or a nullish coalescing operator:

const img = data.header_image_url.url ?? "/app/frontend/img.png";
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