JordanBelf JordanBelf - 6 months ago 12
Node.js Question

Undefined variable defined inside an 'if' not recognized

I know this might have a really simple answer but I can't seem to figure it out.

I need to define the contents of a variable depending on the value of a parameter coming to a function.

The issue is that when I set my values inside an

if
I get
ReferenceError: newval is not defined


Below is a simplified version of the code which runs the error:

const myMessage = (recipientId, msg, miller) => {
const tip = 1;
if (tip===1)
{
console.log("in here");
const newval = "some value";
}
console.log("executes this");
const send = newval;


When I check the console I get the
in here
before the
execute this
message. That is why I am not sure why
send
doesn't know what
newval
is.

Any tip in the right direction will be appreciated,
Thanks

Answer

let and const are both sensibly block-scoped, unlike var, so you cannot reference them outside of the surrounding block (not function):

function scopes() {
  if (true) {
    var foo = 'visible';
    let bar = 'not visible';
    console.log(foo, bar); // both foo and bar are visible
  }
  console.log(foo, bar); // foo is visible, bar is not
}
console.log(foo, bar); // neither foo nor bar are visible

If you want to set const to the result of a branch, try moving the branch to a small function and call that:

function getNewValue(tip) {
  if (tip === 1) {
    // do stuff
    return "some value";
  } else {
    // do other stuff
    return "other value";
  }
}

const tip = 1;
const send = getNewValue(tip);