0

In javascript, how do you declare a variable and set its value to the result of a function in a single line?

In pseudo-code, what I am trying to achieve is this:

var coinToss = if(Math.random() < 0.5), assign value of "tail" to my variable, otherwise, assign value of "head" to my variable. 

I could do this is a block of code, but I assume that there must be a way to achieve the result in a single line?

Many thanks in advance,

0

1 Answer 1

1

It sounds like you're looking for the ternary conditional operator:

var coinToss = (Math.random() < 0.5) ? "tail" : "head";
Sign up to request clarification or add additional context in comments.

1 Comment

Hi David, thank you, that's exactly it! ;) Actually easier to answer than to explain! Many thanks for the quick response

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.