简体   繁体   中英

Javascript using a Variable declared outside the function returns the value + undefined along with it

var name = "myName";

function test() {
    document.write(name);
}

var testcheck= test();

document.write(testcheck);

This returns " myNameundefiend " that is the value+undefined why is that happening ?

You're not returning a value from your test function, making the testcheck variable undefined .

The test() call first writes the name to the document, then document.write(testcheck); adds undefined behind that.

You'll need to return name from the function:

function test() {
    document.write(name);
    return name;
}

There's no need to document.write twice. Either only keep it in the function, or remove it from the function and use document.write(testcheck); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM