Wake
Wake

Reputation: 15

What is wrong with this scope?

When an HTML form submits, it should run the code inside the IF statement and then console log it. But all I get logged into the console is undefined. What's wrong with this code?

let inputValue = document.getElementById('nicInput').value;
let invChars;
if(/[^A-Za-z0-9]/.test(inputValue)) {
    let invChars = true;
 } else {
    let invChart = false;
 }
 console.log(invChars);

Upvotes: 0

Views: 40

Answers (2)

Anu
Anu

Reputation: 1079

"let" defines a new block level variable.

You wish to conditionally assign value to the same variable invChars and so, your code should be like this:

let inputValue = document.getElementById('nicInput').value;
let invChars;
if(/[^A-Za-z0-9]/.test(inputValue)) {
    invChars = true;
 } else {
    invChart = false;
 }
 console.log(invChars);

or since the test() returns a boolean, you could just assign it directly to the variable:

let invChars = /[^A-Za-z0-9]/.test(inputValue);
console.log(invChars);

Upvotes: 0

Quentin
Quentin

Reputation: 943562

let creates a new variable in the scope of the block it appears in.

So let invChars; is a different variable to let invChars = true;.

It is the former that console.log(invChars); refers to, and you never assign it a value.


To take your approach, you should simple not redeclare the variable inside the blocks of if and else:

let inputValue = document.getElementById('nicInput').value;
let invChars;
if(/[^A-Za-z0-9]/.test(inputValue)) {
    invChars = true;
 } else {
    invChart = false;
 }
 console.log(invChars);

That said, that is an exceptionally inefficient way to assign true or false based on the return value of test() … which itself returns true or false.

It would be easier, faster, and clearer to simply:

let inputValue = document.getElementById('nicInput').value;
let invChars = /[^A-Za-z0-9]/.test(inputValue);
console.log(invChars);

Upvotes: 3

Related Questions