<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>In HTML, JavaScript statements are executed by the browser.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello Dolly.";
</script>
</body>
</html>
RUN 결과.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>JavaScript statements are separated by semicolons.</p>
<p id="demo1"></p>
<script>
let a, b, c;
a = 5;
b = 6;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>
</body>
</html>
RUN 결과.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>Multiple statements on one line are allowed.</p>
<p id="demo1"></p>
<script>
let a, b, c;
a = 5; b = 6; c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>
</body>
</html>
RUN 결과는 위와 동일하다.
세미콜론은 JS 문법(코드)를 분리한다. 각 실행되는 문법 마지막에 세미콜론을 붙인다.
세미콜론으로 분리되어 있다면, 여러 문법(코드)를 한줄에 작성하여도 문제없다.
※주의 : 웹에서 세미콜론이 없는 예제를 볼 수도 있다. 세미콜론으로 문장을 안끝내도 가능하지만, 하는것이 좋겠다.
let person = "Hege";
let person="Hege";
let x = y + z;
JS는 빈공간은 인식하지 않는다. 작성자는 script에 빈칸을 추가하여 가독성을 올릴 수 있다.
연산자(= + - * /) 앞뒤로 빈칸을 넣는 것이 좋겠다.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>
The best place to break a code line is after an operator or a comma.
</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Hello Dolly!";
</script>
</body>
</html>
RUN 결과.
가독성을 위해, 프로그래머는 습관적으로 한 줄에 80자 이하로 입력을 한다.
만약 JS 문장이 한줄에 안들어가면, 연산자를 기준으로 줄변경을 하면 된다.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>JavaScript code blocks are written between { and }</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}
</script>
</body>
</html>
RUN 결과.
버튼 클릭 시 결과.
JS문장은 code block에서 그룹화 될 수 있다. 여기서 code block은 {...} 대괄호를 뜻한다. code block의 목적은 한번에 같이 실행시키도록 문장을 정의 하기 위함이다.
※통상 2칸의 빈칸으로(들여쓰기) code block을 작성한다.
JS 문장은 일반적으로 약속된 키워드로 사직한다.
※JS 키워드는 예약어이다. 예약어는 변수명으로 설정이 불가하다
자세한 키워드는 아래 주소를 참고한다.