https://www.robinwieruch.de/javascript-variable-question-mark
JavaScript Variable with Question Mark
If you are new to JavaScript, the question mark after a variable may be confusing to you. Let's shed some light into it. The question mark in JavaScript is commonly used as conditional operator -- called ternary operator when used with a colon (:) and a question mark (?) -- to assign a variable name conditionally.
const isBlack = false;const text = isBlack ? 'Yes, black!' : 'No, something else.';console.log(text);// "No, something else."
Either the expression is true and returns the value after the question mark (?) or the expression is false and returns the value after the colon (:).
This kind of JavaScript variable declaration is used as a shorthand though. You can achieve the same with the "if-else"-statement in JavaScript as conditional operator in contrast to the ternary operator, but it turns out more verbose:
const isBlack = false;let text;if (isBlack) {text = 'Yes, black!';} else {text = 'No, something else.';}console.log(text);// "No, something else."
If this is not what you are looking for, then maybe you are searching for JavaScript's optional chaining feature. It is used to assign a variable conditionally:
const person = {name: 'Robin Wieruch',pet: {name: 'Trixi',},};const petName = person.pet?.name;console.log(petName);// "Trixi"
If the person has no pet, the output would be undefined
without throwing a JavaScript exception.
const person = {name: 'Robin Wieruch',};const petName = person.pet?.name;console.log(petName);// undefined
When this feature was not available in JavaScript, it was common to use the AND (&&) operator or the ternary operator (?:) from before to avoid any JavaScript exceptions:
const person = {name: 'Robin Wieruch',};let petName = person.pet && person.pet.name;console.log(petName);// undefinedpetName = person.pet ? person.pet.name : undefined;console.log(petName);// undefined
Most commonly you will find the question mark in JavaScript for these two use cases. Either it is used as shorthand conditional operator instead of the commonly used "if-else"-statement or as optional chaining operator to assign variables conditionally without hitting an exception.
'C Lang > JS Basic' 카테고리의 다른 글
What do the three dots (…) mean in JavaScript?: (...) = deepCopy, rest parameters (0) | 2021.02.26 |
---|---|
javascript error문법 (1) | 2020.03.04 |
Arrow function사용법, 주의사항 (0) | 2020.02.13 |
함수형 프로그래밍이란 무엇인가? (0) | 2020.02.03 |
함수형 프로그래밍? (0) | 2020.02.03 |