0

i want to create variable base on conditional, but even simple code i can not get the new variable this is my code

exports.productPatch = (req, res, next) => {
  const id = req.params.productId;
  const image = req.body.productImage;
  if(image){
    const newImage =  image;
  }else{
    const newImage = "1598173461682-636126917.jpg";
  }
  console.log(newImage);
}

but when i call newImage response is not defined

3 Answers 3

1

Try this

const newImage = (image) ? image : "1598173461682-636126917.jpg" 

If this gives undefined, check if your request body really sends the productImage.

Sign up to request clarification or add additional context in comments.

Comments

0

You cannot reassign and redeclare a variable declared with const (See this).For your code you can use let and then reassign it according to the condition.

exports.productPatch = (req, res, next) => {
  const id = req.params.productId;
  const image = req.body.productImage;
  let newImage;
  if(image){
   newImage =  image;
  }else{
   newImage = "1598173461682-636126917.jpg";
  }
  console.log(newImage);
}

Comments

0

Please check const scope in the below link

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

The value of a constant can't be changed through reassignment, and it can't be redeclared.

use let instead of const like below as @Divin answer

let newImage = (image) ? image : "1598173461682-636126917.jpg" 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.