Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Nicholas Lee
Nicholas Lee
12,474 Points

What does this mean in javascript, return m === null ? 0 : m.length;

I am confused and not sure what this is called, I understand the regular expressions but don't know what ? or : mean.

function getVowels(str) {
  var m = str.match(/[aeiou]/gi);
  return m === null ? 0 : m.length;

2 Answers

Jenny Veens
Jenny Veens
10,896 Points

Hi Nicholas,

This is a Ternary (or Conditional) return statement. It's like a short form for an if/else, and has nothing to do with regular expressions.

The first part of the statement is the condition (m === null). If the condition is true, the statement will return what's directly after the '?' ( 0, in this case ). If the condition is false, the statement will return the value after the ':' ( m.length ).

In this example a regex is checking for vowels in a string, and returning the number of vowels if any are found, otherwise it's returning 0.

expression ? value_when_true : value_when_false

forms a ternary operator ( a fancy way of saying it takes three )

its a shorthand for this code in your case

if (m === null) {
  return 0;
} else {
  return m.length;