DEV Community

Maulik Chaudhary
Maulik Chaudhary

Posted on

"if" and "?": how they're different in Javscript

You might have come across the conditional code which has "if" statements and at same time conditional code with ? question mark operator is also widely being used.

If both does the same thing then what is the best practice and when to use which?!

Turns out,

if statement is used when we just want to execute some block of code based on the condition.

if (true) {
 alert("Hello World");
else {
 alert("Good night!");
}

Enter fullscreen mode Exit fullscreen mode

if we want to assign the result of a condition to a variable then question mark operator is something you should use.

const allowedAccess = age > 23 ? true : false;
Enter fullscreen mode Exit fullscreen mode

although both can be used interchangeably.

Top comments (0)