简体   繁体   中英

return not working on JS but console.log does

I was trying to set these to work for a simple if else, but return on 2nd argument in Else part doesnt return anything but if I use `console.log('Its not a string');} it works. Can someone enlighten me about it.

 let i = 'String'; console.log(i, 'is a ' + typeof i + '.'); //prints String is a string// i = 100, typeof i; if (i == 'string') { return ('Its a string.'); } else { return ('Its not a string.'); }

return (which is a statement, not a function, so the parenthesis are pointless here) passes data back to the calling function .

Your code isn't in a function. There is nowhere for it to be returned to.

For return to do anything you need to put it inside a function, call that function, and then do something with the return value.

 function example() { let i = 'String'; console.log(i, 'is a ' + typeof i + '.'); i = 100, typeof i; if (i == 'string') { return 'Its a string.'; } else { return 'Its not a string.'; } } let return_value = example(); document.body.appendChild( document.createTextNode(return_value) );

I guess you very new to programming. You need to learn more about functions, datatype, program flow etc.

what you are doing can be done like this:

 let i = 'String'; console.log(i, 'is a ' + typeof i + '.'); //prints String is a string// i = 100; if (typeof i == 'string') { console.log('Its a string.'); } else { console.log('Its not a string.'); }

or you can do it like this:

 let i = 'String'; console.log(i, 'is a ' + typeof i + '.'); //prints String is a string// i = 100; console.log(isString(i)); function isString(i){ if (typeof i == 'string') { return('Its a string.'); } else { return('Its not a string.'); } }

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