Jessica
Jessica

Reputation: 3769

Is there a ? conditional test in Javascript like in C#?

I have the following:

var isChecked = $('#htmlEdit').is(":checked");

But I don't really need the variable isChecked and what I want to do is to assign a value to a variable called "action" so that if the test on the right above is true then

var action = "Editing HTML" 

if not then

var action = "Editing"

Is there a clean way to do this without just using an if-else?

Upvotes: 1

Views: 145

Answers (6)

Tim M.
Tim M.

Reputation: 54387

var result = someCondition == true ? "state 1" : "state 2";

// the first operand must evaluate to a boolean
var result = someCondition ? "state 1" : "state 2"; // shortened
var result = a == b ? "state 1" : "state 2"; // arbitrary condition

This is the ternary operator and behaves the same in JavaScript as most/all c-style languages.

Upvotes: 2

Didier Ghys
Didier Ghys

Reputation: 30676

Yes there is:

var action = $('#htmlEdit').is(":checked") ? "Editing HTML" : "Editing";

Conditional operator on MDN

Upvotes: 7

anantkpal
anantkpal

Reputation: 100

Yes you can use conditional operator:

var variableToBeAssigned = conditiontoBechecked ? valueTobeAssignedONSucessOfCondition : valueToBeassignedONFailureOfCondition;

In your case, you can just use:

var action = $('#htmlEdit').is(':checked') ? 'Editing HTML' : 'Editing';

Upvotes: 0

linuxeasy
linuxeasy

Reputation: 6499

? is also called as ternary operator.

This is more of a language construct, rather than a Framework stuff.

C# is a language and Jquery is a framework build on Javascript (a language).

And Javascript language and most of the languages (C, C++, C#, Java, Javascript) support this operator.

Upvotes: 0

Alexander Pavlov
Alexander Pavlov

Reputation: 32296

var action = isChecked ? "Editing HTML" : "Editing";

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503090

Yes, Javascript has a conditional operator. You should be able to write:

var action = $('#htmlEdit').is(":checked") ? "Editing HTML" : "Editing";

(Did you try this before asking the question?)

Upvotes: 3

Related Questions