React 입문하면서 자바스크립트 공부 중 궁금한 사항이 생겨 결과를 정리 해봤습니다.

(테스트를 더 해보고 싶다면 아래 코드에 label, testValue 에 값을 추가해보시면 되겠습니다.)

 

&& 연산자 (0을 제외한 숫자와 문자들은 모두 true로 인식이 됩니다.)

수식 결과
null && 'T'
 
undefined && 'T'
 
'' && 'T'
 
' ' && 'T'
T
0 && 'T'
0
'0' && 'T'
T
1 && 'T'
T
-1 && 'T'
T
true && 'T'
T
"true" && 'T'
T
false && 'T'
 
"false" && 'T'
T

? 연산자 (3항 연산자)

수식 결과
null ? 'T' : 'F'
F
undefined ? 'T' : 'F'
F
'' ? 'T' : 'F'
F
' ' ? 'T' : 'F'
T
0 ? 'T' : 'F'
F
'0' ? 'T' : 'F'
T
1 ? 'T' : 'F'
T
-1 ? 'T' : 'F'
T
true ? 'T' : 'F'
T
"true" ? 'T' : 'F'
T
false ? 'T' : 'F'
F
"false" ? 'T' : 'F'
T

?? 연산자 ( null ?? 'F'   로 입력을 하였는데 내부적으로 아래와 같은 코드로 변경이 되네요.)

 null, undefined 인 경우에만 값을 넣어줄 수 있습니다.

수식 결과
null !== null && null !== void 0 ? null : 'F'      (null ?? 'F')
F
undefined !== null && undefined !== void 0 ? undefined : 'F'     (undefined ?? 'F')
F
'' !== null && '' !== void 0 ? '' : 'F'
 
' ' !== null && ' ' !== void 0 ? ' ' : 'F'
 
0 !== null && 0 !== void 0 ? 0 : 'F'
0
'0' !== null && '0' !== void 0 ? '0' : 'F'
0
1 !== null && 1 !== void 0 ? 1 : 'F'
1
-1 !== null && -1 !== void 0 ? -1 : 'F'
-1
true !== null && true !== void 0 ? true : 'F'
 
"true" !== null && "true" !== void 0 ? "true" : 'F'
true
false !== null && false !== void 0 ? false : 'F'
 
"false" !== null && "false" !== void 0 ? "false" : 'F'
false

|| 연산자 (null, undefined, blank, false, 0 인 경우에 기본 값 지정이 가능합니다.)

수식 결과
null || 'Or Default'
Or Default
undefined || 'Or Default'
Or Default
'' || 'Or Default'
Or Default
' ' || 'Or Default'
 
0 || 'Or Default'
Or Default
'0' || 'Or Default'
0
1 || 'Or Default'
1
-1 || 'Or Default'
-1
true || 'Or Default'
 
"true" || 'Or Default'
true
false || 'Or Default'
Or Default
"false" || 'Or Default'
false

 

아래는 로그에 찍히는 내용으로

xml 형태가 아닌 react에서 실제 변경되어 사용되는 모습이 흥미롭네요!

 

읽어 온 함수 내용 :  value => {
    return /*#__PURE__*/(0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)("div", {
      children: value && 'T'
    }, void 0, false, {
      fileName: _jsxFileName,
      lineNumber: 72,
      columnNumber: 12
    }, undefined);
  }

 

export const OperationExample = () => {
  const label = ['null', 'undefined', "''", "' '", '0', "'0'", '1', '-1', 'true', '"true"', 'false', '"false"'];
  const testValue = [null, undefined, '', ' ', 0, '0', 1, -1, true, "true", false, "false"];
  let keyPrefix = 0;

  //css 한 파일로 하려고 선언...
  const style = {
    border: '1px solid black',
    borderCollapse: 'collapse',
    textAlign: 'center',
  };

  const CustomTable = ({ condition }) => {
    keyPrefix++;

    return (
      <table key={keyPrefix} style={style}>
        <tbody>
          <tr style={style}>
            <td style={style}> 수식 </td>
            <td style={style}> 결과 </td>
          </tr>
          {testValue.map((v, index) => {
            const trKey = keyPrefix + 'tr' + index;
            const tdLabelkey = keyPrefix + 'label' + index;
            const tdValuekey = keyPrefix + 'value' + index;

            const content = GetFunctionCode(condition, index);

            return (
              <tr key={trKey} style={style}>
                <td key={tdLabelkey} style={style}>
                  {content}
                </td>
                <td key={tdValuekey} style={style}>
                  {condition(v)}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    );
  };

  //`${함수명}` 을 통해 함수 코드를 볼 수 있습니다!
  const GetFunctionCode = (fn, index) => {
    const functionToString = `${fn}`; //재미있는 부분..! 함수 내용을 읽어옵니다.
    const target = 'children: '; //읽어온 함수에서 children 항목을 찾습니다.
    let result = '';
    let i = functionToString.indexOf(target) + target.length;

    console.log('읽어 온 함수 내용 : ', functionToString);

    //children에 담긴 코드 부분만 추출해줍니다.
    for (i; i < functionToString.length; ++i) {
      if (functionToString[i] === '}') {
        break;
      }
      result += functionToString[i];
    }

    return result.replaceAll('value', label[index]).trim(); //함수 핵심 로직만 읽어오기
  };

  const AndCondition = (value) => {
    return <div>{value && 'T'}</div>;
  };

  const SingleQuestionMarkCondition = (value) => {
    return <div>{value ? 'T' : 'F'}</div>;
  };

  const DoubleQuestionMarkCondition = (value) => {
    return <div>{value ?? 'F'}</div>;
  };

  const OrCondition = (value) => {
    return <div>{value || 'Or Default'}</div>;
  };

  return (
    <div>
      <b>&& 연산자</b>
      <CustomTable condition={AndCondition} />
      <b>? 연산자</b>
      <CustomTable condition={SingleQuestionMarkCondition} />
      <b>?? 연산자</b>
      <CustomTable condition={DoubleQuestionMarkCondition} />
      <b>|| 연산자</b>
      <CustomTable condition={OrCondition} />
    </div>
  );
};

+ Recent posts