Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!