29

While trying to debug I am get the 'length' null error with this line. It is written just like the book instructed, so I don't understand why it is giving me the error? Thanks, =)

if (capital.length < 1) {

( here is the full code as requested.. SORRY)

<script type="text/javascript">
var capital = window.prompt("What is the capital of Missouri?","")

if (capital.length < 1) {
    document.getElementById("firstdiv").innerHTML="Sorry you don't feel like playing.<br /> The Capital of Missouri is Jefferson City.";
}
else {
    if (!window.confirm("Is that your final answer?")){ return true;

        document.getElementById("firstdiv").innerHTML = "The capital of Missouri is: <bold>" + capital + "</bold>, so says you.";
    }
    else{
        return false;
    }
}
</script> 
5
  • post full code please Commented Mar 31, 2013 at 16:20
  • 2
    What language is this? JavaScript? Commented Mar 31, 2013 at 16:20
  • Because you never set capital. Commented Mar 31, 2013 at 16:21
  • The variable capital is null. Commented Mar 31, 2013 at 16:24
  • Done =) sorry about that Commented Mar 31, 2013 at 17:22

6 Answers 6

88

The proper test is:

if (capital != null && capital.length < 1) {

This ensures that capital is always non null, when you perform the length check.

Also, as the comments suggest, capital is null because you never initialize it.

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

2 Comments

I am so sorry.. Yes it is in JavaScript
I would probably write this as if (capital && capital.length < 1) now and not explicitly reference null.
4

This also works - evaluate, if capital is defined. If not, this means, that capital is undefined or null (or other value, that evaluates to false in js)

if (capital && capital.length < 1) {do your stuff}

2 Comments

If capital is non-null but points to the empty string, will the logic be correct with this solution?
probably not, in 2021 is better use nullish coalesce operator ?? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
1

From the code that you have provided, not knowing the language that you are programming in. The variable capital is null. When you are trying to read the property length, the system cant as it is trying to deference a null variable. You need to define capital.

Comments

1
if (capital.touched && capital != undefined && capital.length < 1 ) { 
//capital does exists
}

Comments

0

I tried this:

if(capital !== null){ 
//Capital has something 
}

Comments

0

Use Try cache

try{

//Your Code

} catch(err){

console.log(err)

}

1 Comment

Could you expand your answer to help OP a little as to why this answer may work for them?

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.