Home > Mobile >  scope of if statement in javascript compared to python
scope of if statement in javascript compared to python

Time:06-11

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 ?

CodePudding user response:

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";
  • Related