The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 4,224 other subscribers

Archive for October 11th, 2017

Is there a standard function to check for null, undefined, or blank variables in JavaScript? – Stack Overflow

Posted by jpluimers on 2017/10/11

Yes there is; it’s the answer below. Note I needed to exclude false by adding a check value === false to the code below as that was a valid value for me.

You can just check if the variable has a truthy value or not. That means

if( value ) {
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string (“”)
  • 0
  • false

The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.

Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

if( typeof foo !== 'undefined' ) {
    // foo could get resolved and it's defined
}

If you can be sure that a variable is declared at least, you should directly check if it has a truthyvalue like shown above.

Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html

Thanks to [WayBackUser jAndy – Stack Overflow who answered the above at [WayBackIs there a standard function to check for null, undefined, or blank variables in JavaScript? – Stack Overflow.

–jeroen

Posted in Development, JavaScript/ECMAScript, Scripting, Software Development | Leave a Comment »

How do I make the first letter of a string uppercase in JavaScript? – Stack Overflow

Posted by jpluimers on 2017/10/11

I’m a JavaScript n00b, so I like solutions like these:

Another solution:

function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

You could also add it to the String.prototype so you could chain it with other methods:

String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

and use it like this:

'string'.capitalizeFirstLetter() // String

Thanks [WayBackHutch Moore and [WayBackDeviljho for answering at [WayBackHow do I make the first letter of a string uppercase in JavaScript? – Stack Overflow!

Note you can do it in CSS too as explained by [WayBacksam6ber:

In CSS:

p:first-letter {
    text-transform:capitalize;
}

–jeroen

Posted in CSS, Development, JavaScript/ECMAScript, Scripting, Software Development, Web Development | Leave a Comment »

 
%d bloggers like this: