
아래는 예제로 공유해주신 각 파일의 코드를 한눈에 보기 좋도록 정리한 내용입니다.
프로젝트 파일 구조는 다음과 같고, 각 파일에는 다음과 같은 코드가 들어 있습니다.
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);
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;
}
* {
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;
}
<!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>
이상으로, 예제 프로젝트에 포함된 각 파일의 코드와 간단한 설명이었습니다.
아래 내용은 “자바스크립트 코드를 작성할 때 상수(const)와 변수(let)를 어떻게 적절히 사용하고, 값이 어떻게 흐르는지(복사 vs. 원본) 이해하는 과정”을 쉽게 자세히 풀어낸 설명입니다. “왜 defaultResult는 0이지만, 최종 결과는 14가 될 수 있는지”, “상수를 복사한 뒤 변경해도 원본은 변하지 않는 이유” 등도 함께 다룹니다. 편하게 읽어보세요!
자바스크립트 코드(HTML에 연결된 JS 파일)는 위에서부터 아래로 순서대로 실행됩니다.
let currentResult = 0; → currentResult를 먼저 0으로 선언currentResult = (currentResult + 10) * 3 / 2 - 1; → 여기서 currentResult가 새로 계산되어 14가 됨outputResult(currentResult, ...) → 최종적으로 14가 출력결국 맨 위에 currentResult가 0이라고 선언되어 있어도, 그 다음 코드에서 (0 + 10) * 3 / 2 - 1 = 14로 업데이트해 버리므로, 최종 결과는 14가 표시됩니다.
Tip: 자바스크립트는 코드를 무조건 순차적으로 실행합니다. 위에서부터 “한 줄씩” 실행해 내려간다고 생각하면 돼요.
defaultResult 도입하기const: 한 번 할당하면 절대 바꿀 수 없는 값(상수). let: 값이 언제든지 변할 수 있는 변수.예를 들어, “처음 결과값”을 저장할 때 defaultResult를 상수로 선언하면:
const defaultResult = 0; // 절대 변하지 않는 상수
let currentResult = defaultResult; // 변할 수 있는 변수
currentResult = (currentResult + 10) * 3 / 2 - 1;
defaultResult: 0 (고정, 변경 불가능) currentResult: 처음에는 defaultResult와 같은 값(0)이 되지만, 이후 (0 + 10)*3/2 -1으로 14가 됩니다.currentResult를 defaultResult로 초기화한다고 해서, defaultResult가 바뀌는 게 아닙니다. currentResult에 넣은 것이고, 이후에 currentResult를 변경해도 defaultResult는 그대로 0을 유지합니다.만약 다음과 같은 코드를 추가한다면:
defaultResult = 5; // 상수인 defaultResult를 바꾸려 시도
HTML 출력 시 “최신값”인 currentResult를 사용하기 때문입니다.
outputResult(currentResult, '...');
currentResult가 이미 14로 업데이트되어 있으니, 화면에 14가 표시되는 겁니다. currentResult를 업데이트하기 전에 outputResult를 호출하거나, 따로 저장한 값(다른 변수)에 0을 담아두고 그걸 출력해야겠죠.defaultResult) 보관용 currentResult) defaultResult = 0 currentResult = defaultResult → 지금은 0 currentResult = (0 + 10) * 3 / 2 - 1 = 14 outputResult(14, ...) → 화면에 “14” 표시currentResult를 0으로 초기화해도 다음 줄에서 바로 14로 업데이트하면 최종으로 14가 됩니다.let 변수로 쓰일 수 있지만, 상수 자체를 변경할 수는 없습니다. outputResult 함수가 최종 currentResult 값을 HTML에 표시하므로, 당연히 “0”이 아닌 “14”가 나온다는 점 잊지 마세요.이처럼 자바스크립트에서는 상수, 변수, 연산, 출력 순서를 정확히 이해해야 원하는 결과를 얻을 수 있습니다. 차근차근 익혀가며, 값의 흐름(“복사냐 원본이냐”)과 실행 순서(“위에서 아래”)를 잘 파악하시면, 점점 더 복잡한 로직도 쉽게 다룰 수 있을 거예요!
즐거운 코딩 되세요!
아래 내용은 자바스크립트에서 문자열(String)을 다루는 여러 가지 방법을 쉽고 상세하게 풀어 쓴 설명입니다. 큰따옴표, 작은따옴표, 백틱(템플릿 리터럴) 사이의 차이와 문자열 결합, 줄 바꿈, 특수 문자(이스케이프 시퀀스) 같은 내용을 차근차근 익혀볼 수 있도록 정리했으니 편하게 읽어보세요.
'Hello' (작은따옴표로 열고 작은따옴표로 닫음)"World" (큰따옴표로 열고 큰따옴표로 닫음)'를 썼는데 닫을 때 "를 쓰면, 자바스크립트가 어디서 문자열이 끝나는지를 알 수 없어 오류가 납니다.title="..." 등 예외 상황은 있을 수 있음)'I'm here' → 중간에 '이 또 나와서 혼란 발생.// 문자열 전체를 큰따옴표로 감싸고, 안에 작은따옴표 사용
let message = "I'm here";let message = 'I\'m here';
// \' 로 작은따옴표를 출력용으로 사용`Hello World`let userName = 'Max';
let greeting = `Hello, ${userName}!`;
// 결과: "Hello, Max!"let multiLine = `이 문장은
두 줄에 걸쳐 있습니다.`;\n 같은 특수 문자를 써야 하지만, 템플릿 리터럴은 그대로 줄을 바꿔 쓸 수 있어 가독성이 좋아집니다.const defaultResult = 0;
let currentResult = (defaultResult + 10) * 3 / 2 - 1;
// 템플릿 리터럴 사용
let calculationDescription = `(${defaultResult} + 10) * 3 / 2 - 1 = ${currentResult}`;
// 결과: "(0 + 10) * 3 / 2 - 1 = 14"
+작은따옴표나 큰따옴표를 사용할 때, 변수 값을 문자열 중간에 넣으려면 + 연산자를 활용해야 합니다.
let defaultResult = 0;
let calculationDesc =
'(' + defaultResult + ' + 10) * 3 / 2 - 1';
// 결과: "(0 + 10) * 3 / 2 - 1"
템플릿 리터럴을 사용하면 +로 결합할 필요 없이 ${} 구문을 사용하기만 하면 되죠.
\\: 백슬래시 자체를 출력하고 싶을 때 \n: 줄 바꿈(new line) \': 문자열 내부에서 작은따옴표를 출력 \": 문자열 내부에서 큰따옴표를 출력 예:
let errorMessage = 'An error\noccurred!';
console.log(errorMessage);
// 출력:
// An error
// occurred!
let quote = 'He said: \"Hello\"';
console.log(quote);
// He said: "Hello"
\) 뒤에 오는 문자를 “특별한 의미”로 해석합니다. '\n'은 실제로 개행(줄 바꿈)을 의미하고, '\\'는 백슬래시 한 개를 화면에 표시합니다.'\n'을 써야 하거나, + 연산자로 나누어 결합해야 합니다.let multiLineStr = 'Line1\nLine2\nLine3';let multiLineTpl = `Line1
Line2
Line3`;<span>, <h2>)에 기본 white-space 스타일이 적용되어 있어서, 자동으로 여러 줄을 표시하지 않을 수도 있습니다. white-space: pre; 처럼 설정하면, 문자열 내 줄 바꿈을 그대로 화면에 표시하게 만들 수 있습니다.\n (줄 바꿈), \\ (백슬래시), \' (작은따옴표) 등. + 연산자로 문자열을 이어 붙이거나, 템플릿 리터럴로 더 편하게 작성.\n 또는 + 연산으로 이어줘야 함.현재 예제(app.js)에서 문자열을 만드는 방법은 크게 두 가지가 있었습니다:
defaultResult)를 이어 붙임. 템플릿 리터럴이 등장하면서 코드를 더 간단하고 읽기 좋게 만들 수 있습니다. 예를 들어:
const defaultResult = 0;
let currentResult = (defaultResult + 10) * 3 / 2 - 1;
// 템플릿 리터럴 사용
let calculationDescription = `(${defaultResult} + 10) * 3 / 2 - 1 = ${currentResult}`;
// 화면에 출력
outputResult(currentResult, calculationDescription);
이렇게 작성하면, 기존의 문자열 합치기(+) 작업을 간소화할 수 있고, 중간에 변수를 넣는 것도 쉽습니다.
결론:
앞으로 다른 예제를 작성하면서 문자열을 반복적으로 다루게 될 텐데, 이런 개념들을 알아두면 로그 메시지, 사용자 알림, 데이터 표시 등 다양한 작업에 응용하기 훨씬 수월해집니다.
즐거운 코딩 되세요!