Comparison of the Ternary operator, Elvis operator, secure navigation operator, and OR logical operators

Comparison with Ternary vs Elvis operator with safe navigation operator or logical operator in angular


Ternary operator (operator? Obj: obj)

let gender = user.male ? "male" : "female";

Elvis operator (? :)

let displayName = user.name ?: "";

Safe Navigation Operator (?.)

let displayName = user.name ?. "";

Logical or operators

let displayName = user.name || "";

Above, all operators in the same way perform the same process. What are the advantages of the difference, and which are better and worse?

+6
source share
4 answers

, , , , TypeScript elvis . , , !., , js ! . Angular , ||. - .

, TypeScript ?:, , ,

vs . , 3 . , "", .

, 2 . , , , , .

, . , , . , , , , ||, ||, .

TL;DR;

, ,

  • ?:

typescript/javascript/angular , , , ||

  • ?.

Angular,

  • ||

, . , . typescript/javascript/angular

+5

(?.), Angular2

Angular2, javascript.

(? obj: obj)

, , , .

, , ( ), Ternery.

let displayName = user.name || "";

, , , :

let gender = user.male ? "male" : "female";

: , "", ""

(?:)

javascript, , PHP, , , , , ( ) :

:

let m = something ?: somethingElse // if in case of truthiness of `something` you want to return `something` , you can do this

:

let m = something ? something : somethingElse 

EDIt: , .

+1
let gender = user.male ? "male" : "female";

javascript(Typescript), HTML,

, javascript-, , , ,

angular2 Ternary Operator Safe Navigation Operator (?.) Elvis Operator (?: ), - .

alternate: - Elvis Operator (?: ) angular2, ( , )

let gender = user.gender || "";

+1

@Milad RameshRajendran elvis Safe Navigation Operator (?.) angular2, ,


- :

(?:)

" " - Java. , , " " false . : :

def gender = user.male ? "male" : "female"  //traditional ternary operator usage

def displayName = user.name ?: "Anonymous"  //more compact Elvis operator

(?.)

NullPointerException. , , , , null . , null , , :

def user = User.find( "admin" )           //this might be null if 'admin' does not exist
def streetName = user?.address?.street    //streetName will be null if user or user.address is null - no NPE thrown

, . , ?

+1
source

Source: https://habr.com/ru/post/1017341/


All Articles