-2

I am wondering what this question mark symbol means in a function return statement in JS.

function getValue(val) {        
return (val != null ? val.toString().replace(/,/g, '') : "");
}
Ben Smith
  • 228
  • 2
  • 12

3 Answers3

1

Its a Conditional (Ternary) Operator:

Syntax:

variablename = (condition) ? value1:value2 

Example:

var voteable = (age < 18) ? "Too young":"Old enough";

Explanation: If the variable age is a value below 18, the value of the variable voteable will be "Too young", otherwise the value of voteable will be "Old enough".

ziga1337
  • 106
  • 9
0

In this case "?" allow to write if ... else in one line, it's what we called ternary operator, refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

-2

It's a way to choose a value conditionally based on another value.

Variables are 'truthy' in javascript, and so let's say you have a variable x, and you want to choose variable y based on if variable x is truthy or not

 var y = x ? '1' : '2';

If x is truthy, y will be '1', otherwise '2'.

TKoL
  • 10,782
  • 1
  • 26
  • 50