Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda