Variable Variables

var

  • 재선언 가능, 재할당 가능 / 함수형 변수
  • 전역에서 사용 가능
var hello="안녕";
var hello="헬로우";

if(true){
	var bye="Bye Bye";
	console.log(bye); //Bye Bye
}
console.log(bye); //Bye Bye
console.log(hello); //헬로우
  • var hello는 같은 변수명으로 재선언 되었음에도 오류가 발생하지 않음
  • 만약 if 조건문의 결과가 false면 var bye가 선언되지 않으므로 var bye는 undefined
  • var bye가 선언된 지점이 if 조건문 내부의 { }임에도 { } 밖에서 호출 가능

let

  • 재선언 불가, 재할당 가능 / 영역형 변수
let hello="오랜만";
//let hello="히사시부리"; //재선언 불가이므로 오류발생
hello="히사시부리";

if(true){
	let bye="잘 가";
	console.log(bye); //잘 가
}
//console.log(bye);
console.log(hello); //히사시부리
  • let hello는 같은 변수명으로 재선언 불가
  • let bye는 if 조건문 내부의 { }에서 선언되었으므로 밖에서 호출 불가 (if 조건문이 true임에도 undefined)

const

  • 재선언 불가, 재할당 불가 / 영역형 상수
const hello={
	message:"3th hello",
	times:4
}
console.log(hello); //{message:"3th hello",times:4}

hello.message="요렇게는 될까?";
hello.times=44;

console.log(hello); //{message:"요렇게는 될까?",times:44}
  • 일반적으로 단일 변수보다 Json같이 여러 멤버를 포함한 변수로 설정
  • const hello는 재선언, 재할당 모두 불가이므로 바꿀 수 없음
  • 다만 각각의 멤버를 하나씩 변경하는 것은 가능

Compare : var & let

var a=1;
let b=2;

function myFunction(){
    var a=3;
    let b=4;

    if(true){
        var a=5;
        let b=6;

        console.log(a); //5
        console.log(b); //6
    }
    console.log(a); //5
    console.log(b); //4
}
myFunction();

console.log(a); //1
console.log(b); //2
  • var는 재선언 될 때마다 전역의 할당 값이 변함
  • let는 다른 영역에서는 인식되지 않으므로 선언 가능(재선언 아님), 하지만 해당 영역에서 선언한 변수에 대해서만 인식 가능

Default Value of Functions

  • 인자 값으로 지정된 변수의 기본 값 설정 가능
function func1(x,y=200,z=300){
    console.log(x,y,z);
}

func1(3,4,5); //3 4 5
func1(100); //100 200 300
func1(3,4); //3 4 300
func1(); //undefined 200 300
  • 기본값이 설정된 인자 변수는 값이 할당되지 않아도 기본값을 호출

Spread Operator

  • 배열 및 컬렉션의 요소를 순서대로 나열하는 효과
let arr=[3,5,9];

func1(...arr); //3 5 9

function func2(a,b){
	return a+b;
}

let r=func2(...arr) //순서에 따라 앞의 2개 값만 넘어감
console.log(r); //8
  • 배열 arr의 요소를 일일이 열거하지 않고 배열명만으로 각 인자 값에 할당 가능
  • 배열의 요소 개수가 필요한 인자의 개수보다 많더라도, 순서에 따라 해당하는 인자만 인식
let arr1=[2,4,6];
let arr2=[9,1];
let arr3=[11,12,...arr1,22,...arr2];

console.log(arr3.length); //8
console.dir(arr3) //[11,12,2,4,6,22,9,1] : dir은 구조까지 출력

let arr4=[...[100,200],...arr2]; //변수가 아닌 실제 배열도 펼침연산자 사용가능
console.log(arr4); //[100,200,9,1]
function fsum(arr){
	let sum=0;

	for(let a in arr){
		sum+=arr[a];
	}
	console.log(sum);
}

fsum(arr3); //67

Arrow Function

  • Java의 Lambda Expression과 흡사
function f1(){
	console.log("일반함수");
}
f1(); //일반함수
let f2=()=>console.log("화살표함수");
f2(); //화살표함수
  • 화살표 함수는 일반 함수의 생략 표현
  • 일반 함수의 인자가 ( ) 안에, 로직이 ⇒ 뒤에 위치 (로직이 한 줄이면 { } 생략 가능)
function f3(a,b){
	return a+b;
}
let a=f3(3,5);
console.log(a); //8
let f4=(a,b)=>a+b;
let b=f4(11,22);
console.log(b); //33
  • 로직이 한 줄이면 return 표현 생략 가능
let f5=(x,y,z=100)=>x+y+z;
console.log(f5(1,2)); //103
  • 화살표 함수에서도 기본값 설정 가능

Literal (Back-Tick)

``

let irum="김영환";
let birth=1993;
let likefood="삼겹살";

let curYear=new Date().getFullYear(); //숫자4자리 반환

let result="이름: "+irum+"\n태어난 연도: "+birth+"\n나이: "+(curYear-birth)+"\n좋아하는 음식: "+likefood;

console.log(result);

//리터럴(백틱 ``)..중간변수 ${변수명}
let result2=`이름: ${irum}
태어난연도: ${birth}
나이: ${curYear-birth}
최애음식: ${likefood}`;
console.log(result2);
  • 기존 문자열 선언 방식에서 줄바꿈을 위해 이스케이프 문자(\n) 사용
  • 리터럴에서는 선언 시 입력대로 값 인식
  • “” 아닌 ``에 입력하며, 변수는 ${ }으로 입력

Collections

  • Set, Map 기능 포함

Set

let set=new Set("abcccdddeeeffffff"); //중복문자 걸러냄
console.log(set); //Set(6){'a','b','c','d','e','f'}
console.log(set.size); //6
  • Java의 컬렉션과 동일한 특성과 메서드
set.add("f"); //변함 없음
set.add("g");
console.log(set); //Set(7){'a','b','c','d','e','f','g'}

console.log(set.has("a")); //포함하므로 true
console.log(set.has("z")); //false
  • Java의 Set과 같이 중복 불허
console.log(...set); //a b c d e f g

set.delete("a");
console.log(...set); //b c d e f g
  • 컬렉션도 배열과 동일하게 펼침연산자 사용하여 요소 열거 가능
  • delete() 메서드는 요소 하나씩 제거
set.clear();
console.log(set.size); //0
  • clear() 메서드는 전체 요소 제거

Comparison Operator

===

let a=6;
let b="6";

console.log(a==b); //true
console.log(a===b); //false
  • == 연산자는 양항의 값만 비교하여 boolean 반환
  • === 연산자는 자료형까지 비교하여 boolean 반환

Class in ECMA 6

class Student{
	
	constructor(name){
		this.name=name;
	}

	showName(){
		console.log(`내 이름은 ${this.name}입니다`);
	}
}
  • 생성자는 변수명이 없으며, 모두 constructor 클래스명 사용
let s1=new Student("호슥");
console.log(s1.name); //호슥
s1.showName(); //내 이름은 호슥입니다
  • new로 생성
  • 멤버 변수, 멤버 메서드 호출 방식 Java와 동일
profile
초보개발자

0개의 댓글