What does the "?" operator do in Javascript? [duplicate] - javascript

This question already has answers here:
Question mark and colon in JavaScript
(8 answers)
Closed 3 years ago.
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, '') : "");
}

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".

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

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'.

Related

Why this code is incorrect in javaScript? JS experts please explain [duplicate]

This question already has answers here:
Javascript inline if statement
(4 answers)
Closed 11 months ago.
var x = 10;
var b = if(x>5){return true};
console.log(b);
I'm not getting why this is incorrect and will give an error.
The syntax of a variable initializer stipulates that it must be an expression. An if statement is not an expression.
You can write
var b = (x > 5) ? true : undefined;
(or whatever you want b to be when x is not greater than 5). That ? : expression is an expression, so it works as the initializer part of the declaration.
You can use this solution
var x = 10;
var b = x>5? true:false
# if the condition (x>5) is true.
# will execute the first return(true)
# or else the second return will execute (false)
console.log(b) #Output= true

What is this called, and how would I use it for a lockdown command [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 7 years ago.
Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.
int row = 10;
int column;
while (row >= 1)
{
column = 1;
while(column <= 10)
{
System.out.print(row % 2 == 1 ? "<" : "\r>");
++column;
}
--row;
System.out.println();
}
This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.
Here's a good example from Wikipedia demonstrating how it works:
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
Basically it takes the form:
boolean statement ? true result : false result;
So if the boolean statement is true, you get the first part, and if it's false you get the second one.
Try these if that still doesn't make sense:
System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
a=1;
b=2;
x=3;
y=4;
answer = a > b ? x : y;
answer=4 since the condition is false it takes y value.
A question mark (?)
. The value to use if the condition is true
A colon (:)
. The value to use if the condition is false
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
Maybe It can be perfect example for Android,
For example:
void setWaitScreen(boolean set) {
findViewById(R.id.screen_main).setVisibility(
set ? View.GONE : View.VISIBLE);
findViewById(R.id.screen_wait).setVisibility(
set ? View.VISIBLE : View.GONE);
}
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
it is a ternary operator and in simple english it states "if row%2 is equal to 1 then return < else return /r"

javascript if statement not evaluated as expected [duplicate]

This question already has answers here:
What's the difference between & and && in JavaScript?
(4 answers)
Closed 5 years ago.
Why my "C" condition go to 'else' statement?, they separated are going to 'if' statement but together are not working.
var objTest = {
ID : "10"
};
//A: First Condition: Exist value in property ID
console.log((objTest.ID ? 'if' : 'else')); // output => "if"
//B: Second Condition: Value different from "0"
console.log((objTest.ID != "0" ? 'if' : 'else')); // output => "if"
//C: First and Second Condition together must be "if"
console.log((objTest.ID & objTest.ID != "0" ? 'if' : 'else')); // output => "else"
Your problem is that you are using the wrong ANDopernator, you need to use && instead of &:
console.log((objTest.ID && objTest.ID != "0" ? 'if' : 'else'));
The first &is a bitwise operator and &&is the logical operator.
Please take a look at What's the difference between & and && in JavaScript? for further details.

What does this mean? Is it an if else representation? [duplicate]

This question already has answers here:
Question mark and colon in JavaScript
(8 answers)
Closed 5 years ago.
What does the following mean?
var iCurrentIndex = oCurrentQuestionModel.getProperty("/index"); ...(1)
iCurrentIndex = iCurrentIndex ? ++iCurrentIndex : 0; ...(2)
The var iCurrentIndex = false in setp 1 and in step 2 it gets assigned value 0.
What does this representation mean can anyone explain me?
Your step 2 can be rewritten like this:
if (iCurrentIndex) {
++iCurrentIndex;
} else {
return 0;
}
You are using ternary operator, read about it here.
Assuming
var iCurrentIndex = oCurrentQuestionModel.getProperty("/index");
returns an undefined or null or just false, then an increment can not take place.
Then you need a check if the returned value is truthy (a value which resolves to true, if casted to boolean), then just increment or assign zero to iCurrentIndex.
iCurrentIndex = iCurrentIndex ? ++iCurrentIndex : 0;
The above conditional oparator uses a condition and evaluates either the part after ?, the then part of an if statement or the part after :, the else part of an if statement.

Use of `?` in a JavaScript timer function return [duplicate]

This question already has answers here:
Question mark and colon in JavaScript
(8 answers)
Closed 8 years ago.
So I stumbled on some Javascript timer example and there was this function, which gets a number into it and then the function returns the time:
function timer(variable){
return variable > 9 ? variable : "0" + variable;
}
And the whole code would look something like this:
var sec = 0;
function timer(variable){
return variable > 9 ? variable : "0" + variable;
}
setInterval(function(){
$("#time-id").val("Minutes: "+timer(parseInt(sec/60, 10))+" Seconds: "+timer(++sec%60));
}, 1000);
So yes, the setInterval function is pretty clear to me but about the timer().
What is the usage of ? in it? And how does it understand if I have multiple params given to it. Should it not be marked like this : timer(variable1, variable2){} ?
Timer is formatting time so that if it is 6:05, it shows up as 6:05 and not 6:5
return variable > 9 ? variable : "0" + variable;
is the same as
if ( variable > 9 ) {
return variable
} else {
return "0" + variable
}
?: is an operator shared by a lot of modern languages. It's a shortcut for an if test. The structure is as follows :
condition ? resultIfTrue : resultIfFalse
In your case, it appends a 0 to your variable if the variable is < 10. You could read it as :
if (variable > 9)
do nothing
else
add a "0" before
It's saying that if variable is 10 or more, it just echoes back variable; otherwise it adds a 0 on the start to still make it two digits.
variable > 9 ? variable : "0" + variable; is a ternary expression. variable > 9 is evaluated, and if it's truthy, variable is returned, otherwise "0" + variable is returned. Think of it as a one-liner substitute for an if-else statement with assignment.

Categories

Resources