주석처리
대소문자 구별 및 카멜케이스(소문자로 시작) 사용한다.
주석
// 단일라인 주석
/*
멀티라인1
멀티라인2
*/
let(변수) , const(상수) 선언
var가 function-scouped로 전역적으로 hoisting이 일어나서 변수 선언이전에도 해당 변수를 사용할 수 있었으며 여러 문제를 야기한다.
var colorCode = "red";
let, const는 block-scoped단위로 hoisting이 일어난다.
앞으로 var대신에 let, const 문으로 변수를 선언한다.
let colorCode = "red";
연산자
산술 연산자(예: +, -, *, /, %)
비교 연산자(예: ==, ===, !=, !==, >, <, >=, <=)
논리 연산자(예: &&, ||,!)
할당 연산자(예: =, +=, -=, *=, /=, %=)
조건부(삼항) 연산자(예: a ? b : c)
"="과 "=="은 다른 연산자이다. 비교를 할 경우에는 "=="를 사용하여야 한다.
"="은 할당연산자(또는 대입연산자)로 값을 변수에 할당하는 역할을 수행한다.
"===" 연산자는 값 및 변수유형까지 동일한 지 비교한다.
"!==" 연산자는 값 및 변수유형까지 틀린 지 비교한다.
연산자 예제
// Arithmetic operators(산술 연산자)
let x = 5;
let y = 2;
console.log(x + y); // 7
console.log(x - y); // 3
console.log(x * y); // 10
console.log(x / y); // 2.5
console.log(x % y); // 1
// Comparison operators(비교연산자)
let a = "hello";
let b = "world";
console.log(a == b); // false
console.log(a === b); // false
console.log(a != b); // true
console.log(a !== b); // true
console.log(x > y); // true
console.log(x < y); // false
// Logical operators(논리연산자)
let p = true;
let q = false;
console.log(p && q); // false
console.log(p || q); // true
console.log(!p); // false
// Assignment operators(할당연산자)
let m = 5;
m += 2; // m = m + 2
console.log(m); // 7
// Conditional (ternary) operator(3항 연산자)
let age = 25;
let canDrive = (age >= 18) ? "can drive" : "cannot drive";
console.log(canDrive); // "can drive"
// typeof operator(typeof 연산자 : 변수의 타입을 알아낼때)
let person = { name: "John", age: 30 };
console.log(typeof person); // "object"
// instanceof operator(인스탄스 상태 연산자)
console.log(person instanceof Object); // true
// delete operator(삭제 연산자)
delete person.age;
console.log(person); // { name: "John" }
// in operator(in 연산자)
console.log("name" in person); // true
함수
자바스크립트 함수는 프로그램 전체에 걸쳐 정의되고 재사용될 수 있는 코드 블록이다. 함수는 0개 이상의 매개 변수를 입력으로 사용할 수 있으며 값을 반환하거나 반환하지 않을 수 있다.
다음은 자바스크립트에서 함수를 정의하기 위한 기본 구문이다.
function functionName(parameter1, parameter2, ...) {
// function body
// statements to be executed
}
function sayHello(name) {
console.log("Hello, " + name);
}
sayHello("John"); // Output: "Hello, John"
문자열 함수
자바스크립트에서 문자열은 텍스트를 표현하는 데 사용되는 연속된 문자이다. 문자열은 작은따옴표 또는 큰따옴표로 묶는다.
다음은 자바스크립트에서 문자열을 만드는 방법의 예이다.
let message = "Hello, World!";
자바스크립트는 문자열을 조작하는 데 사용할 수 있는 다음과 같은 많은 내장 메서드를 제공한다:
- length: returns the number of characters in a string
- toUpperCase(): returns the string in uppercase
- toLowerCase(): returns the string in lowercase
- indexOf(substring): returns the index of the first occurrence of the substring in the string
- lastIndexOf(substring): returns the index of the last occurrence of the substring in the string
- slice(start, end): returns a new string that is a substring of the original string
- substring(start, end): returns a new string that is a substring of the original string
- substr(start, length): returns a new string that is a substring of the original string
- replace(oldValue, newValue): replaces all occurrences of the old value with the new value in the string
- trim(): removes whitespaces from the beginning and end of the string
- split(separator): splits the string into an array of substrings using the separator
- concat(string1,string2,..): joins two or more strings together
let message = "Hello, World!";
console.log(message.length); // Output: 13
console.log(message.toUpperCase()); // Output: "HELLO, WORLD!"
console.log(message.toLowerCase()); // Output: "hello, world!"
console.log(message.indexOf("World")); // Output: 7
console.log(message.slice(7, 12)); // Output: "World"
console.log(message.replace("World", "Friend")); // Output: "Hello, Friend!"
console.log(message.trim()); // Output: "Hello, World!"
console.log(message.split(",")); // Output: ["Hello", " World!"]
console.log(message.concat(" How are you?")); // Output: "Hello, World! How are you?"
console.log(message.startsWith("Hello")); // Output: true
console.log(message.endsWith("World!")); // Output: true
백틱(`)과 템플릿 리터럴
avaScript 템플릿 리터럴은 ECMA스크립트 6(ES6)에 도입된 새로운 기능으로 보다 강력하고 유연한 구문으로 문자열을 만들 수 있다. 템플릿 리터럴은 작은따옴표나 큰따옴표 대신 백틱(`)으로 묶는다.
템플릿 리터럴의 주요 이점 중 하나는 문자열에 식을 ${}(으)로 묶어서 포함할 수 있다는 것이다.
let name = "John";
let age = 30;
console.log(`My name is ${name} and I am ${age} years old.`); // Output: "My name is John and I am 30 years old."
템플릿 리터럴을 사용하면 이스케이프 문자()를 사용하지 않고 여러 줄의 문자열을 만들 수 있다.
let text = `This is
a multiline
string`;
console.log(text);
/* Output:
This is
a multiline
string
*/
let price = 10;
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
배열
javaScript 배열은 단일 변수에 여러 값을 저장하는 데 사용된다. 배열은 숫자, 문자열 및 개체와 같은 서로 다른 데이터 유형의 값을 저장할 수 있다.
let numbers = [1, 2, 3, 4, 5];
배열 생성자를 사용하여 배열을 생성할 수도 있다. 그러나 new Array()보다 [] 방식을 권장한다.
let numbers = new Array(1, 2, 3, 4, 5);
배열은 인덱스를 사용하여 배열 요소에 액세스할 수 있다. 배열은 인덱스 이렇게 외어야 한다.
console.log(numbers.length); // Output: 5
console.log(numbers[0]); // Output: 1
console.log(numbers[2]); // Output: 3
배열에서 사용되는 내장 메서드
- push(element): adds an element to the end of the array
numbers.push(6); console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]
- pop(): removes the last element of the array and returns it
let last = numbers.pop(); console.log(last); // Output: 6 console.log(numbers); // Output: [1, 2, 3, 4, 5]
- shift(): removes the first element of the array and returns it
let first = numbers.shift(); console.log(first); // Output: 1 console.log(numbers);
배열에서 값 이터레이트
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
let numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number);
}
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
if else 조건문
특정 조건에 따라 다른 처리를 하기위해 조건문을 사용한다.
let age = 19;
if (age >= 21) {
console.log("You are old enough to drink!");
} else if (age >= 19) {
console.log("You are old enough to vote!");
} else {
console.log("You are not old enough to drink or vote!");
}
이 예에서 다른 if 블록 내부의 코드는 가변 연령 값이 19보다 크거나 같으나 21보다 작은 경우에만 실행된다. 연령이 19세 미만이면 마지막 블록의 코드가 실행된다.
switch 조건문
switch 문은 식의 값을 여러 개의 경우와 비교하고 일치하는 경우 블록 내의 코드가 실행된다.
각 블록의 하단에는 break문을 사용해 다른 블록으로 실행을 막아야 한다.
let day = 'Monday';
switch (day) {
case 'Monday':
console.log('Today is Monday');
break;
case 'Tuesday':
console.log('Today is Tuesday');
break;
case 'Wednesday':
console.log('Today is Wednesday');
break;
default:
console.log('Today is another day');
}
let x = 3;
switch(true){
case x > 0 && x < 5:
console.log("x is between 0 and 5");
break;
case x > 5 && x < 10:
console.log("x is between 5 and 10");
break;
default:
console.log("x is not in the range 0 to 10")
}
for 반복문
for (let i = 1; i <= 10; i++) {
console.log(i);
}
1부터 10까지 출력하는 예제이다.
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
배열의 값을 순차적으로 읽어서 출력하는 예제이다.
let person = {name: "John", age: 25, city: "New York"};
for (let key in person) {
console.log(key + ": " + person[key]);
}
person 객체의 값을 in키워드를 사용해서 key를 찾고 key에 해당하는 값을 출력하는 예제이다.
let key in person 문장은 person 객체의 키를 순차적으로 가져온다.
let numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number);
}
배열의 값을 of 키워드를 사용하여 순차적으로 가져와 출력하는 예제이다.
for (let i = 1; i <= 10; i++) {
if (i % 2 === 1) {
continue;
}
console.log(i);
}
2로 나눈 나머지가 1인 경우(홀수)는 continue해서 하위코드를 실행안하고 다음 루프를 진행하여 1부터 10까지 짝수만 출력된다.
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
1부터 10까지 1씩 증가하며 출력하다 i가 5인 경우 루프수행을 중단하고 빠져나온다.
에러처리 및 디버깅
try {
let x = y + 2;
// m, n 변수를 선언하지 않아서 예외가 발생
let z = m / n;
} catch (error) {
if (error instanceof ReferenceError) {
console.log("ReferenceError: " + error.message);
} else if (error instanceof TypeError) {
console.log("TypeError: " + error.message);
}
}
try catch문을 사용하여 예외사항을 처리
try {
// y변수를 선언하지 않아 예외가 발생
let x = y + 2;
} catch (error) {
console.log(error);
} finally {
// 오류가 발생하던 안하던 수행하는 코드
console.log("나는 항상 수행되는 코드다");
}
try catch문을 사용하여 예외사항을 처리하고 finally문안에 있는 코드는 오류와 상관없이 실행되는 코드
class 클라스명 {}로 선언
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}
let person = new Person("John");
person.greet(); // Output: "Hello, my name is John."
생성자 생성 : `constructor`를 사용하여 생성
let person = new Person("John");
new문을 사용하여 Person클래스로 부터 person 객체를 생성한 뒤
person.greet(); 와 같이 person객체의 greet()메서드를 사용한다.
댓글