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

program
  • 13
  • 5
  • You never set `var1` if the else-statement is evaluated. – mykaf May 17 '22 at 20:51
  • Where are you seeing the `undefined`? How are you executing this code? – Bergi May 17 '22 at 21:09
  • @Bergi when I console the var1 after condition then I see the undefined in the console – program May 17 '22 at 21:13
  • You don't define it in all cases. If `props.id` is not 1, `var1` does not get defined. – mykaf May 17 '22 at 21:15
  • I am sorry that's a mistake that I make while asking the question. I will correct it – program May 17 '22 at 21:19
  • @user1599011 now see the code – program May 17 '22 at 21:20
  • You still don't define `var1` in the else statement. What are you expecting it to be? – mykaf May 17 '22 at 21:22
  • I expect var 1 to the object ```{id:1,learn:"HTML", do:"cooking"}``` – program May 17 '22 at 21:25
  • Please include your `props` definition. Your code seem to be failing the if-statement, thus executing the else-statement and not defining `var1`. A [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) is needed to know exactly what's going on. – mykaf May 17 '22 at 22:35

1 Answers1

-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("--------");
usman mughal
  • 189
  • 1
  • 3
  • 7