Determining string length in Node JS when a string can be null

I am trying to learn Node and have a function:

this.logMeIn = function(username,stream) {
  if (username === null || username.length() < 1) {
    stream.write("Invalid username, please try again:\n\r");
    return false;
  } else {
  ....etc

and i pass it

if (!client.loggedIn) {
  if (client.logMeIn(String(data.match(/\S+/)),stream)) {

I tried both == and ===, but I still get errors, because the username does not detect that it is null, and username.length () does not work:

if (username === null || username.length() < 1) {
                                  ^
TypeError: Property 'length' of object null is not a function

I'm sure Node will not evaluate the second part || in the if statement, when the first part is true, but I don’t understand why the first part of the if statement evaluates to false when username is a null object. Can someone help me understand what I did wrong?

+5
source share
4 answers

String(data.match(/\S+/)) username , , data.match(/\S+/) null, "null" not null username, :

String(null) === "null"

, :

if( username === null || username === "null" || username.length < 1 )
+4

length - , . username.length

+7

, "" , null, undefined, '' ..:

if (username) { ... }

.length. , length , .


: - . , , - , String(data.match(/\S+/)) , ( @Engineer ).

: null Array. , , @Engineer, "null" , . :

if (!client.loggedIn) {
    var matches = data.match(/\S+/);
    if (client.logMeIn(matches ? matches[0] : '',stream)) {

.length, 1 - . console.log(), , .

+1

if ( === null || _ .toString(). length < 1)

if ( === null || username.length < 1), .

+1

All Articles