Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining string length in Node JS when string may be null

I'm trying to learn Node and have the 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'm passing it

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

I've tried both == and ===, but I'm still getting errors as the username is not detecting that it is null, and username.length() fails on:

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

I'm sure that Node won't evaluate the second part of the || in the if statement when the first part is true - but I fail to understand why the first part of the if statement is evaluating to false when username is a null object. Can someone help me understand what I've done wrong?

like image 829
Amateur Programmer by Night Avatar asked May 17 '12 12:05

Amateur Programmer by Night


People also ask

What is the length of an empty string JavaScript?

For an empty string, length is 0.

How check string is null in JavaScript?

Empty string, undefined, null, ... To check for a truthy value: if (strValue) { // strValue was non-empty string, true, 42, Infinity, [], ... } To check for a falsy value: if (!strValue) { // strValue was empty string, false, 0, null, undefined, ... }

How do I check if a string is empty?

The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.


1 Answers

length is an attribute, not a function. Try username.length

like image 70
Amberlamps Avatar answered Sep 30 '22 17:09

Amberlamps