Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

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;
}