0

I have 2 objects coming from props and I am assigning these objects to their variable by if else condition

  let var1;
  let var2;

    if (props.id === 1) {
      var1 = props;
      console.log(var1); //  returns {id:1,learn:"HTML", do:"cooking"}
    } else {
      var2 = props;
    }

  console.log(var1); // returns {id:1,learn:"HTML", do:"cooking"} and undefined

When I console.log after condition why does it returns the object and undefined? But when console.log inside if condition only returns the object.

I want that it returns only the object if console.log after the condition

My two objects coming like this

{id:1,learn:"HTML", do:"cooking"}
{id:2,learn:"Css", do:"home-work"}

I have seen resources from StackOverflow

Javascript variable is undefined outside if condition

JavaScript Variable undefined outside of function

This question is said to be duplicate for Chrome/Firefox console.log always appends a line saying 'undefined'

but it's completely different it's not about the browsers console I am getting undefined from my javascript file

9
  • You never set var1 if the else-statement is evaluated. Commented May 17, 2022 at 20:51
  • Where are you seeing the undefined? How are you executing this code? Commented May 17, 2022 at 21:09
  • @Bergi when I console the var1 after condition then I see the undefined in the console Commented May 17, 2022 at 21:13
  • You don't define it in all cases. If props.id is not 1, var1 does not get defined. Commented May 17, 2022 at 21:15
  • I am sorry that's a mistake that I make while asking the question. I will correct it Commented May 17, 2022 at 21:19

1 Answer 1

-2

Use const instead of let and try to differentiate the logs of next render from the previous render like this

const var1;
const var2;

if (props.id === 1) {
  var1 = data;
  console.log(var1);
} else {
  var2 = data;
}
console.log(var1);
console.log("--------");
Sign up to request clarification or add additional context in comments.

1 Comment

we can not change the const variable it would give an error

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.