JavaScript의 명령문
JavaScript 문은 일부 동작 또는 작업을 완료하는 코드 블록입니다. 기본적으로 JavaScript 인터프리터는 이러한 명령문을 작성된 순서대로 차례로 실행합니다.
아래 JS의 다양한 종류의 문장을 이해해 봅시다.
1. 표현문
부작용이 있는 표현식은 대입문, 함수 호출, 증가 및 감소 연산자, 대입문과 관련된 ++ 및 —, 삭제 연산자와 같은 표현식 문 으로 간주 됩니다.
let greeting = “Hello “ + name; //assignment statement
counter ++; // increment operator which is changing a variable value
delete o.x; // deleting a property of an object O
cx = Math.cos(x);; // function invocation and assign the value to a variable
단일 문은 JS에서 복합 문 또는 문 블록 으로 간주되는 둘 이상의 하위 문을 포함할 수 있습니다 . 다음 줄은 단일 문 역할을 합니다.
{
x = Math.PI;
cx = Math.cos(x);
console.log(“cos(π) = “ + cx);
}
3. 조건문
if 및 switch 문과 같이 표현식의 값에 따라 JS 인터프리터가 다른 문을 실행하거나 건너뛰도록 하는 문입니다 .
3.1 if 문
JS가 결정을 내리고 조건부로 문을 실행할 수 있도록 하는 기본 제어 문입니다.
//syntax
If (expression)
Statement1
else
Statement 2
//example
if (n === 1) { //curly braces are optional in case of single statement
console.log("You have 1 new message.");
} else {
console.log(`You have ${n} new messages.`);
}
3.2 Switch 문
같은 표현식의 값이 2개 이상의 선택지 중에서 결정을 내리는 데 사용될 수 있는 경우 JS는 switch 문을 제공합니다.
//Syntax
switch(expression) {
case label1: statement1; // if expression value === label1 execute statement1
case label2: statement2; // if expression value === label2 execute statement2
…
default: default_statement; // optional
}
//Example:
switch(n) {
case 1:
// Start here if n === 1.(sameness is determined by the === operator)
// Execute code block #1.
break; // stop here
case 2:
// Start here if n === 2
// Execute code block #2.
break; // Stop here
case 3:
// Start here if n === 3
// Execute code block #3;
break; // Stop here
default:
// If no case match the value of n
// Execute code block #4.
}
4. 루프 문
while 및 for 와 같이 다른 문을 반복적으로 실행하는 문 .
4.1 While 루프
인터프리터는 먼저 표현식을 평가합니다 . 표현식의 값이 거짓이면 인터프리터는 루프 본문 역할을 하는 명령문을 건너뛰고 프로그램의 다음 명령문으로 이동합니다. 반면에 표현 이 참이면 통역사는 그 문장을 실행 하고 반복합니다.
//Syntax
while (expression) { //curly braces are optional in case of single statement
//statment or statement block
}
//Example
let count = 0;
while(count < 10) {
console.log(count);
count++;
}
//Syntax
do { //curly braces are optional in case of a single statement
//statement / statement block
}
while (expression);
//Example
let count = 0;
do {
console.log(count);
count++;
}
while (count < 10);
//syntax
for(initialize ; test ; increment) { //curly braces are optional in case of single statement
//statement / statement block
}
//Example:
for(let count = 0; count < 10; count++) {
console.log(count);
}
//Syntax with example
let data = [1, 2, 3, 4, 5, 6, 7, 8, 9], sum = 0;
for(let element of data) {
sum += element;
}
// for of with map
let m = new Map([[1, "one"]]);
for(let [key, value] of m) {
key // => 1
value // => "one"
}
//syntax
for (variable in object) {
//statement / statement block
}
//Example:
for(let p in o) { // Assign property names of o to variable p
console.log(o[p]); // Print the value of each property
}
break , return 및 throw 와 같이 인터프리터가 프로그램의 다른 부분으로 이동하도록 하는 문 .
5.1 레이블 지정
모든 명령문은 앞에 식별자와 콜론을 붙여 레이블을 지정할 수 있습니다 . 명령문에 레이블을 지정하면 프로그램의 다른 곳에서 참조하는 데 사용할 수 있는 이름을 지정할 수 있습니다.
//syntax
identifier: statement
//example
mainloop: while(token !== null) {
// Code omitted…
continue mainloop; // Jump to the next iteration of the named loop(mainloop)
// More code omitted…
}
5.2 Continue
continue 문이 실행되면 둘러싸는 루프의 현재 반복이 종료되고 다음 반복이 시작됩니다.
//example
for(let i = 0; i < data.length; i++) {
if (!data[i]) continue; // jump to the next iteration of the loop
total += data[i];
}
//syntax
return expression;
//Example
function square(x) { return x*x; } // A function that has a return statement
square(2) // => 4
// A generator function that yields a range of integers
function* range(from, to) {
for(let i = from; i <= to; i++) {
yield i;
}
}
try/catch/finally
try/catch/finally 문은 JavaScript의 예외 처리 메커니즘입니다.
//syntax
try {
//Normally, this code runs from the top of the block to the bottom
//without problems. But it can sometimes throw an exception,
//either directly or with a throw statement.
} catch(e) {
// The statements in this block are executed if, and only if, the try
// block throws an exception. These statements can use the local variable
// e to refer to the Error object or other value that was thrown.
} finally {
// This block contains statements that are always executed, regardless of
// what happens in the try block. They are executed whether the try
// block terminates:
}
//example
try {
// Ask the user to enter a number
let n = Number(prompt("Please enter a positive integer", ""));
// Compute the factorial of the number, assuming the input is valid
let f = factorial(n);
// Display the result
alert(n + "! = " + f);
} catch(e) { // If the user's input was not valid, we end up here
alert(e); // Tell the user what the error is
}
다음 몇 개의 게시물은 JavaScript에 대한 기본 및 고급 주제를 논의하는 시리즈의 일부가 될 것입니다.
이 이야기가 마음에 드셨다면 버튼을 눌러 다른 사람들도 찾을 수 있도록 공유해주세요! 또한 아래에 의견을 남겨주십시오.
Groww Engineering은 일반적인 프로그래밍 문제를 해결하기 위한 기술적 일화, 최신 기술 및 더 나은 방법을 게시합니다. 최신 업데이트를 받으려면 여기에서 구독 할 수 있습니다 .
직원 모집합니다. 여기에서 구인 정보를 확인하십시오 .

![연결된 목록이란 무엇입니까? [1 부]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































