
아래는 예제로 공유해주신 각 파일의 코드를 한눈에 보기 좋도록 정리한 내용입니다.
프로젝트 파일 구조는 다음과 같고, 각 파일에는 다음과 같은 코드가 들어 있습니다.
basics-03-variables-operators/
┣─ assets/
│ ┣─ scripts/
│ │ ├─ app.js
│ │ └─ vendor.js
│ └─ styles/
│ └─ app.css
└─ index.html
const defaultResult = 0;
let currentResult = defaultResult;
currentResult = (currentResult + 10) * 3 / 2 - 1;
let calculationDescription = '(' + defaultResult + ' + 10) * 3 / 2 - 1';
outputResult(currentResult, calculationDescription);
defaultResult를 0으로 설정하고, currentResult도 처음에는 0으로 초기화합니다. (currentResult + 10) * 3 / 2 - 1으로 결과를 갱신하고, calculationDescription)로 만들어 outputResult 함수에 넘깁니다.const userInput = document.getElementById('input-number');
const addBtn = document.getElementById('btn-add');
const subtractBtn = document.getElementById('btn-subtract');
const multiplyBtn = document.getElementById('btn-multiply');
const divideBtn = document.getElementById('btn-divide');
const currentResultOutput = document.getElementById('current-result');
const currentCalculationOutput = document.getElementById('current-calculation');
function outputResult(result, text) {
currentResultOutput.textContent = result;
currentCalculationOutput.textContent = text;
}
<input>과 버튼들(+, -, *, /), 그리고 결과 표시용 <h2> 태그들을 document.getElementById로 가져옵니다. outputResult 함수는 전달받은 두 개의 인자(result, text)를 각각 화면의 currentResultOutput, currentCalculationOutput 영역에 반영해 줍니다.* {
box-sizing: border-box;
}
html {
font-family: 'Roboto', open-sans;
}
body {
margin: 0;
}
header {
background: #023d6d;
color: white;
padding: 1rem;
text-align: center;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26);
width: 100%;
}
#results,
#calculator {
margin: 2rem auto;
width: 40rem;
max-width: 90%;
border: 1px solid #023d6d;
border-radius: 10px;
padding: 1rem;
color: #023d6d;
}
#results {
text-align: center;
}
#calculator input {
font: inherit;
font-size: 3rem;
border: 2px solid #023d6d;
width: 10rem;
padding: 0.15rem;
margin: auto;
display: block;
color: #023d6d;
text-align: center;
}
#calculator input:focus {
outline: none;
}
#calculator button {
font: inherit;
background: #023d6d;
color: white;
border: 1px solid #023d6d;
padding: 1rem;
cursor: pointer;
}
#calculator button:focus {
outline: none;
}
#calculator button:hover,
#calculator button:active {
background: #084f88;
border-color: #084f88;
}
#calc-actions button {
width: 4rem;
}
#calc-actions {
margin-top: 1rem;
text-align: center;
}
header 스타일, #calculator 섹션, 입력창, 버튼 등에 대한 CSS 지정 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Basics</title>
<link
href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="assets/styles/app.css" />
</head>
<body>
<header>
<h1>The Unconventional Calculator</h1>
</header>
<section id="calculator">
<input type="number" id="input-number" />
<div id="calc-actions">
<button type="button" id="btn-add">+</button>
<button type="button" id="btn-subtract">-</button>
<button type="button" id="btn-multiply">*</button>
<button type="button" id="btn-divide">/</button>
</div>
</section>
<section id="results">
<h2 id="current-calculation">0</h2>
<h2>
Result: <span id="current-result">0</span>
</h2>
</section>
<script src="assets/scripts/vendor.js"></script>
<script src="assets/scripts/app.js"></script>
</body>
</html>
<h2 id="current-calculation">와 <span id="current-result">를 통해 연산 과정 및 최종 결과를 보여줌. vendor.js → app.js 순으로 스크립트를 불러와서 실행.이상으로, 예제 프로젝트에 포함된 각 파일의 코드와 간단한 설명이었습니다.
실행하면, app.js에서 계산된 결과와 계산식 설명이 화면에 표시되며, 추후 버튼 클릭 등 이벤트를 처리하면 계산기가 좀 더 동적으로 동작하게 확장할 수 있습니다.
아래 내용은 “자바스크립트에서 숫자, 문자열과 같은 자료형(Data Types) 중 특히 문자열(String)과 숫자(Number)를 다루는 방법”을 쉽게, 그리고 자세히 풀어낸 설명입니다. 변수에 값(숫자)을 저장해 계산하고, 계산 내용을 문자열로 설명하는 과정을 구체적으로 다뤘으니, 천천히 읽어보세요.
2, -3)와 소수점 있는 수(예: 22.956) 모두 Number 타입에 속합니다. currentResult = 10;, price = 5.99; 등.' ')나 큰따옴표(" "), 또는 백틱(`)으로 감싸서 만듭니다.'Hello World', "User Name", `This is also a string` '' 혹은 "". 안에 아무 문자도 없다는 뜻이죠.일단 숫자로 연산을 해봅시다.
let currentResult = 0;
currentResult = (currentResult + 10) * 3 / 2 - 1;
// 0에 10 더하고, 3 곱하고, 2로 나누고, 1 빼는 계산
currentResult는 숫자 타입입니다. currentResult에 넣습니다.이제 “어떤 계산을 했는지”를 문자열 형태로 기록하고 싶다고 해봅시다.
let calculationDescription = '(0 + 10) * 3 / 2 - 1';
' ')로 감싸서 "..." 같은 글자를 저장합니다. let emptyString = '';
+ 연산자자바스크립트에서 + 연산자는 숫자끼리 더할 때도 쓰이지만, 문자열을 이어붙일 때도 사용할 수 있습니다.
let currentResult = 10;
let calculationDescription = 'Current result is: ' + currentResult;
+ 뒤에 있는 currentResult는 숫자(10)이지만, 자바스크립트는 문자열 + 숫자를 만나면 숫자를 문자열로 바꿔서 이어붙입니다. 'Current result is: 10' 이라는 하나의 문자열이 됩니다. ( ), +, - 같은 기호도 따옴표 안에 넣으면, 그 역시 텍스트로 간주돼서 그대로 출력됩니다.let defaultResult = 0;
let currentResult = (defaultResult + 10) * 3 / 2 - 1;
// 예: “(0 + 10) * 3 / 2 - 1 = 14” 같은 텍스트를 만들기
let calculationDescription = '(' + defaultResult + ' + 10) * 3 / 2 - 1';
// 만약 currentResult 안의 값도 문자열에 삽입하고 싶다면?
calculationDescription = calculationDescription + ' = ' + currentResult;
(' + defaultResult + ' + 10): 이 부분에서 (와 defaultResult와 + 10)를 모두 문자열로 합칩니다. calculationDescription + ' = ' + currentResult; → 기존에 있던 문자열 뒤에 ' = '와 계산된 숫자를 연결합니다. ' (0 + 10) * 3 / 2 - 1 = 14 ' 같은 형태의 최종 문자열이 만들어집니다.자바스크립트가 문자열 안에 있는 것은 전부 글자 그대로 취급합니다.
예:
let x = 5;
let str = 'x';
// 여기서 str은 숫자 5와 전혀 상관 없는 "x"라는 텍스트
x라는 변수가 아닌, 그냥 문자열 'x'일 뿐이죠. 'currentResult'라고 쓰면, 변수 이름이 아니라 문자열 "currentResult"로만 인식됩니다.기존 코드에서 outputResult 라는 함수를 호출할 때,
outputResult(currentResult, calculationDescription);
currentResult)는 숫자, calculationDescription)는 문자열. outputResult(currentResult, '');
''(빈 문자열)을 주면, 결과 계산값만 표시하고 문자열 영역은 아무것도 보여주지 않게 할 수 있습니다.본문에서 잠깐 언급하셨듯, 자바스크립트에는 백틱(`)을 사용하는 템플릿 문자열(Template Literal) 기능이 있습니다. 이를 이용하면,
let currentResult = 14;
let calculationDescription = `(0 + 10) * 3 / 2 - 1 = ${currentResult}`;
${변수명} 문법을 사용해 문자열 안에 변수나 표현식을 직접 삽입할 수 있어, 복잡한 문자열 결합을 훨씬 간단히 작성할 수 있습니다. +로 문자열을 합치는 것을 배우면 충분합니다.' ' 혹은 "" 내부에 아무 글자도 없는 상태. + 연산자를 이용해 두 문자열을 합치거나, 문자열+숫자를 합쳐 결과를 문자열로 만든다. + 변수 + 형태로 연결하거나, 템플릿 리터럴을 사용해야 함.+ 연산자로 이어붙이거나, 템플릿 문자열(백틱+${})을 활용하면 편리합니다. 이처럼 자바스크립트에서 숫자와 문자열은 서로 다른 데이터 타입이며, 이를 제대로 이해해야 사용자에게 알맞은 형태로 정보를 보여주거나, 수학 계산을 처리할 수 있습니다. 향후 이벤트 처리를 통해 사용자 입력도 받아서 유연한 계산을 할 수 있도록 확장하면, 진짜로 “동작하는 계산기”가 완성될 거예요.
즐거운 코딩 되세요!