[디버깅 방법]
debugger;
for (let i = 0; i < 10; i++){
console.log(i);
}
[개발자 도구를 통해 for loop의 동작과정을 확인할 수 있다.]

[console.log]
let value = 10;
console.log(value); //결과 : 10
function foo(value){
return value;
}
console.log(foo(10)); //결과 : 10
[console.table]
let obj = {a:1,b:2,c:3}
console.table(obj);
| [출력 결과] |
|---|
![]() |
많이 발생했던 에러
ReferenceError : 정의되지 않은 변수 사용 시 에러
TypeError : 구문이 잘못되었을 때 발생하는 에러
SyntaxError: 괄호가 빠지거나 잘못 사용할 경우 발생하는 에러
변수 선언
let variable;
console.log(variable); //결과 : undefined
변수에 값 할당
variable = 10;
console.log(variable); // 결과 : 10
변수 선언과 값 할당(변수 초기화)
let variable2 = 'Test';
console.log(variable2); // 결과 : Test
변수에 값 재할당
variable = 12;
console.log(variable); // 결과 : 11
변수 타입 확인
function foo(){}
let obj = {}
let arr = []
console.log(typeof 1); // 결과 : number
console.log(typeof '1'); // 결과 : string
console.log(typeof true); //결과 : boolean
console.log(typeof foo()); // 결과 : function
console.log(typeof obj); //결과 : object
console.log(typeof arr); //결과 : object
reference type과 primity type 정리 링크 참조
shallow copy와 deep copy 정리 링크 참조
| var vs let keyowrd의 차이점 |
|---|
![]() |
const c = 10
c = 11 //에러 발생 Uncaught TypeError: Assignment to constant variable.
매개변수(parameter)와 전달인자(arguments)
function identity(val){ // val이 매개변수(parameter)
return val;
}
identity(10) // 10이 전달인자(arguments)이다.
function identity(){
console.log(arguments);
console.log(arguments[0]);
console.log(arguments[1]);
}
identity(1,'10');
// 결과
// Arguments(2) [1,'10',callee: f, Symbol (Symbol.iterator): f]
// 1
// '10'
함수 선언문 (function declaration)
identity(10); // 결과 : 10, 호이스팅
function identity(val){
return val;
}
함수 표현식 (function expression)
identity(10); // Uncaught SyntaxError: Missing initializer in const declaration
const identity = function (val){
return val;
}
identity(10); // Uncaught SyntaxError: Missing initializer in const
var vs let 호이스팅 차이점
//var 호이스팅
varHoisting = 6;
varHoisting + 7;
var varHoisting;
// 결과 : 13
//let 호이스팅
letHoisting = 6;
letHoisting + 7;
let letHoisting;
// 결과 : Uncaught ReferenceError: Cannot access 'letHoisting' before initialization
(shift = function (val){
console.log(val || 'IIFE');
})()
shift('Goal'); // Goal
shift(); // IIFE
if(조건식){
// do run stuff
}
// "옷사려면 버스타야되고 아니면 집가려면 지하철을 타야한다 아니면 밥을 먹는다"를 if문으로 작성한다면
if(옷){
//버스를 탄다
}else if(집){
// 지하철을 탄다
}else{
// 밥 먹는다
}
** Equality (==) vs Identity (===) Operators
let one = 1;
let oneStr = '1';
one == oneStr // 결과 : true
one === oneStr // 결과 : false
truthy와 falsy의 차이점을 알고 있다.
let str = "Hello";
console.log(str[0]); // H
str[1] = 'o';
console.log(str); // Hello
let str = "Hello"
console.log(str); //결과 : 5
Methods
let str = 'canada';
console.log(str.indexOf('n')); // 결과 : 2
console.log(str.lastIndexof('a')); // 결과 : 5
console.log(str.indexOf('b')); // 결과 : -1
console.log(str.lastIndexOf('b')); // 결과 : -1
let str = 'Hello from the other side';
console.log(str.split(' '));
// ['Hello', 'from', 'the', 'other', 'side']
// substring
var str = 'abcdefghij';
console.log(str.substring(0, 3)); // 'abc'
console.log(str.substring(3, 0)); // 'abc'
console.log(str.substring(1, 4)); // 'bcd'
console.log(str.substring(-1, 4)); // 'abcd', 음수는 0으로 취급
console.log(str.substring(0, 20)); // 'abcdefghij', index 범위를 넘을 경우 마지막 index로 취급
console.log(str.substring(0, -1)); // 빈 문자열
console.log(str.substring(-100)); // 'abcdefghij' 음수값은 모든 문자열 출력
// slice
console.log(str.slice(0, 3)); // 'abc'
console.log(str.slice(3, 0)); // 빈 문자열
console.log(str.slice(1, 4)); // 'bcd'
console.log(str.slice(-1, 4)); // 빈 문자열
console.log(str.slice(0, 20)); // 'abcdefghij', index 범위를 넘을 경우 마지막 index로 취급
console.log(str.slice(-1)); // "i"
console.log(str.slice(0, -1)); // "abcdefghi"
console.log(str.slice(-100)); // 'abcdefghij' 음수값은 모든 문자열 출력
let str = 'abCdEFg';
console.log(str.toLowerCase()); // abcdefg
console.log(str.toUpperCase()); // ABCDEFG
let str = "Hello";
let changeStr = str.replace('e','o');
console.log(changeStr); //결과 : Hollo
console.log(str); // 결과 : Hello
let str = "Hello Word!";
console.log(str.includes("Word")); //결과 : true
문자열 합치기(concat method / + operation)
let str = "Hello";
let strSum = str.concat(" Word!");
console.log(str); // Hello
console.log(strSum); // Hell Word!
let str = "Hello"
let strSum = str + " Word!"
console.log(str); // Hello
console.log(strSum); // Hell Word!
문자열과 다른 데이터 유형 합치기
let str = '1'
let result = str + 2
console.log(result); // 결과 : '12'
result = str + true
console.log(result); // 결과 : '1true'
result = str + undefined
console.log(result); // 결과 : '1undefined'
for(let i = 0; i < 10; i++){
if( i === 2 ) continue
console.log('i의 값 : ',i);
}
// 결과
// i의 값 : 0
// i의 값 : 1
// i의 값 : 3
// i의 값 : 4
// i의 값 : 5
// i의 값 : 6
// i의 값 : 7
// i의 값 : 8
// i의 값 : 9
for(let i = 0; i < 10; i++){
if( i === 2 ) break
console.log('i의 값 : ',i);
}
// 결과
// i의 값 : 0
// i의 값 : 1
let arr = [1,2,3,4]
for(let i = 0; i < arr.length; i++){
console.log('index : ', i);
cnosole.log('element : ', arr[i]);
}
//index : 0
//element : 1
//index : 1
//element : 2
//index : 2
//element : 3
//index : 3
//element : 4
Method
let arr = [1,2,3,4];
console.log(arr.push(5)); // 결과 : 5, 요소가 추가된 배열의 길이를 출력
console.log(arr); // 결과 : [1,2,3,4,5]
let arr = [1,2,3,4];
console.log(arr.pop()); // 결과 : 4, 삭제 전 배열의 길이를 출력
console.log(arr); // 결과 : [1,2,3]
let arr = [1,2,3,4];
console.log(arr.unshift(0)); // 결과 : 5, 요소가 추가된 배열의 길이를 출력
console.log(arr); // 결과 : [0,1,2,3,4]
let arr = [1,2,3,4];
console.log(arr.shift()); // 결과 : 1, 삭제된 요소를 출력
console.log(arr); // 결과 : [2,3,4]
let arr = [1,5,6];
// 원하는 위치에 요소 추가
console.log(arr.splice(1,0,2,3,4)); // []
console.log(arr); //[1,2,3,4,5,6]
// 삭제
console.log(arr.splice(2,2)); // [3,4], 삭제된 요소들을 배열로 출력
console.log(arr); // [1,2,5,6]
let obj = { method:
function(val){
console.log(val);
}
}
console.log(obj.method(1)); // 결과 : 1
객체를 사용하는 경우
객체의 값을 사용하는 방법
let obj = {}
obj.one = 1;
console.log(obj);
// {one: 1}
let obj = {}
obj['one'] = 1;
console.log(obj);
// {one: 1}
Dot notation vs Bracket notation
let obj = {one: 1, two: 2, three: 3}
for(let key in obj){
console.log(obj.key);
}
//결과 : (3) undefined, obj 객체 안에 key라는 키값을 가지는 속성이 없기 때문이다.
for(let key in obj){
console.log(obj[key]);
}
// 결과
// 1
// 2
// 3
객체의 속성 개수를 세는 법
let obj = {one: 1, two: 2, three: 3}
let key = Object.keys(obj)
let value = Object.values(obj);
console.log(key); // 결과 : ['one','two','three']
console.log(value); // 결과 : [1,2,3]
console.log(key.length) // 결과 : 3
console.log(value.length) // 결과 : 3
let sum = 0;
for(let i = 1; i <= 10; i++){
sum += i;
}
console.log(sum); // 결과 : 15
1. Global Scope vs Local Scope
//Global Scope
==============================================
let greeting = 'Hello';
//Local Scope
---------------------------------------
function greetSomeone() {
let firstName = 'Josh';
return greeting + ' ' + firstName;
}
--------------------------------------
greetSomeone(); // => 'Hello Josh'
firstName; // => ReferenceError
==============================================
2. Function Scope vs Block Scope
Function Scope와 Block Scope의 차이점을 잘 몰랐었는데 예시를 보고 이해하게 되었다. 사실, block이라는 개념이 잘 이해되지 않았었다.if() {} // {}, block
for() {} // {}, block
// block
-----------------------
{
console.log('Block');
}
-----------------------
// 1. function scope
function foo(val){
var feed = 'orange'
if( feed === 'orange'){
var greeting = 'thanks'
}
return greeting + ' ' + val;
}
foo('mom'); // 결과 : "thanks mom"
// foo함수에는 변수가 feed, val, greeting이 있다.
// 2. Block Scope로 인한 에러
function foo(val){
var feed = val;
for(let i = 0; i < 10; i++){ // let keyword로 정의된 count 변수는 for문의 block 범위 내에서만 사용 가능하다.
let count = i;
}
console.log('final i : ', i); // i는 block scope이여서 i is defined 에러, var keyword 사용 시 10으로 출력된다.
return feed + ' ' + count; // count는 foo함수 내에서 선언된 변수가 아니고 for문의 block에 선언된 변수이다. 그래서 count의 범위는 foo함수 내의 변수인데 선언된 것이 없어 결과는 count is defined로 나온것이다.
//여기서 function scope의 차이점은 count 변수를 var keyword로 선언하면 return 값은 orange 9가 된다.
// foo 함수 내에서 var keyword로 변수 선언 시 block({})에 상관없이 사용 가능하다.
// 함수 단위라고 생각하면된다.
}
foo('orange') // 결과 : Uncaught ReferenceError: count is not defined
// 3. 함수 안의 함수일 때 var keyword의 scope
function varFunc1(){
var scope1 = 10;
function varFunc2() { // Closure
var scope2 = 20;
}
return scope1 + scope2;
}
varFunc(); // 결과 scope2 is defined, varFunc2 안의 scope2 변수 선언 시 let keyword를 사용해도 똑같은 결과지만 의미가 다르다 let keyword는 Block scope 범위({})이고 var keyword는 function scope이다.
3. 전역 변수와 window 객체
4. 변수 선언 키워드 사용없이 변수 선언시 전역 변수와 같다.
var value = 10;
window.value = value // 결과 : true
function foo(){
age = 56;
}
window.age // 56
'use strict' // JavaScript 최상단에 작성
function foo(){
age = 56;
}
foo(); // ReferrenceError : age is defined
유용한 클로저 예제
// 여러개의 전달 인자를 받는 방법
function adder(x,y){
return x + y;
}
adder(2,3) // 결과 : 5
//커링
function adder(x){
return function (y){
return x + y;
}
}
adder(2)(3) // 결과 : 5
let add100 = adder(100) // 100을 고정
add100(2) // 102
add100(3) // 103
function makeCounter() {
let privateCounter = 0; //외부에서 호출 및 수정 불가능
return {
increment: function() {
privateCounter++;
},
decrement: function() {
privateCounter--;
},
getValue: function() {
return privateCounter;
}
}
}
let counter1 = makeCounter();
counter1.increment();
counter1.increment();
counter1.getValue(); //2
counter2 = makePayment();
counter2.increment();
counter2.increment();
counter2.increment();
counter2.increment();
counter2.getValue(); // 4
// counter1의 privateCounter 변수와 counter2의 privateCounter변수는 독립적이다.
//type='장난감 동전'이라고 초기화 해도 외부(global scope)의 변수에 영향이 없도록 하는 것을 클로저 모듈 함수라고 한다.
function makePayment() {
let type = '현금'; //반드시 '현금' 또는 '카드'여야 함,
return {
payWithCash: function(amount) {
type = '현금'; // 외부 함수의 변수(type)
console.log(type + '으로 ' + amount + '만큼 지불합니다.');
},
payWithCard: function(amount) {
type = '카드'; // 외부 함수의 변수(type)
console.log(type + '으로 ' + amount + '만큼 지불합니다.');
}
}
}
let pay = makePayment()
pay.payWithCard(10) // 결과 : 카드으로 10만큼 지불합니다.
var type = '장난감 현금'
pay.payWithCash(100) // 결과 : 현금으로 100만큼 지불합니다.
//ES5
function Car(brand, name, color) {
//do run stuff
}
//ES6
class Car() {
constructor(brand, name, color) {
//do run stuff
}
}
//instance 생성
let avante = new Car('','','');
속성과 메소드
| 용어 | 정의 |
|---|---|
| prototype | 모델의 청사진을 만들 때 쓰는 원형 객체 |
| constructor | 인스턴스가 초기화 될 때 실행하는 생성자 함수 |
| this | 함수가 실행 될 때, 해당 scope마다 생성되는 고유한 실행 context (execution context) |
| new 키워드로 인스턴스를 생성했을 때에는 해당 인스턴스가 this의 값 |

//class 정의
class Car(){
constructor(brand, model, color){
this.brand = brand; // this.brand는 생성된 인스턴스의 brand이고 값으로 할당되는 brand는 constructor에서 매개변수에 있는 brand이다.
this.model = model; // this.model은 생성된 인스턴스의 model이고 값으로 할당되는 model은 constructor에서 매개변수에 있는 model이다.
this.color = color; // this.color는 생성된 인스턴스의 color이고 값으로 할당되는 color는 constructor에서 매개변수에 있는 model이다.
}
}
---------------------------------------------------------------------------
//클래스: 속성 정의
// new keyword를 사용하여 인스턴스와 속성을 정의한다.
let avanteInstance = new Car('hyundai','avante','black')
// avanteInstance가 인스턴스이고 'hyundai','avante','black'이 속성을 정의한 것이다.
---------------------------------------------------------------------------
//클래스: 메서드 정의
//ES5
function Car(brand,name,color){}
Car.prototype.refuel = function() {
do run stuff
}
//ES6
class Car() {
constructor(brand, name, color) {}
refuel() {
}
drive() {
}
}
Car.prototype.drive = function() {
console.log(this.model + ' ' + '출발')
}
avanteInstance.drive()
// 결과 : avante 출발
배열에서도 확인 가능한 class와 속성 및 메서드
let arr1 = [1,2,3,4]
let arr2 = new Array(1,2,3,4)
console.log(arr1.length) // 4
arr1.push(5)
console.log(arr1) // [1,2,3,4,5]
업데이트 예정
업데이트 예정
업데이트 예정
업데이트 예정
업데이트 예정