user12008624
user12008624

Reputation:

how to Log valid value to console in JavaScript

I am trying to test an id value is nothing then I am logging in the console as "There is something in that" like that.
so how I can log if something entered in id.

This Code If Nothing Entered:

if(comItem == undefined){
    console.log('There Is Something in that value') 
} else {
    console.log('There is Nothing in that value')
}

I am Not Getting How to Do.

let comItem = 150;

if(comItem != undefined){
    console.log('There Is Something in that value') 
} else {
    console.log('There is Nothing in that value')
}

Upvotes: 0

Views: 441

Answers (1)

Dai
Dai

Reputation: 155588

It sounds like you want to test if comItem is a non-empty, non-whitespace string.

JavaScript has a very loose definition of the == operator - and it helps not to use undefined or null as operands unless you really know what you're doing.

I recommend reading these articles and QAs:

Anyway - the good news is that using just if( comItem ) { ... will work because it will evaluate to true if comItem is not null, and not an empty-string "", but you need a separate check for undefined (using typeof) if var comItem or let comItem (or const comItem) isn't guaranteed to be defined, like so:

if( typeof comItem == 'undefined' ) {
    console.log( );
}
else {
    if( comItem ) {
        console.log('There Is Something in that value') 
    }
    else {
        // `comItem` is either `undefined`, `null`, or an empty string
        console.log('There is Nothing in that value')
    }
}

If you want to test for a non-whitespace string you'll need a regex, like so:

if( comItem ) {
    if( /^\s+$/.test( comItem ) ) { // Test if the string contains only whitespace
        console.log('Whitespace string');
    }
    else {
        console.log('There Is definitely Something in that value');
    }
}
else {
    console.log('There is Nothing in that value');
}

Note that you cannot rely on only if( /\S/.test( comItem ) ) { ... because it evaluates to true for null.

So the total code is:

if( typeof comItem == 'undefined' ) {
    console.log( );
}
else {
    if( comItem ) {
        if( /^\s*$/.test( comItem ) ) {
            console.log( 'Is whitespace' );
        }
        else {
            console.log( 'Has a text value.' );
        }
    }
    else {
        console.log( 'Is null or empty' )
    }
}

Upvotes: 4

Related Questions