언어/node.js

[개념] JS와 ES6 문법

뭉지(moonz) 2021. 7. 20. 14:34
반응형

Node.js란?

  • 구글에서 만든 Chrome V8 JavaScript 엔진으로 빌드된 JavaScript 런타임 (V8은 구글이 만들었지만 node는 'Ryan Lienhart' 님이 만들었다는 사실)
  • javascript는 기존에 브라우저 내에서만 실행할 수 있는 언어였지만, 브라우저가 없이 로컬에서 혹은 서버에서 실행할 수 있도록 만든 것이다.
  • 서버 환경으로 유명한 Node.js에서는 express 모듈을 사용해서 웹 서버를 구축할 수 있다.
쉽게 말해서, Node.js란 자바스크립트를 브라우저가 아닌 컴퓨터에서 로컬 혹은 서버에서 실행하도록 도와주는 환경이라 생각하면 된다.

 

npm이란?

나중에 실습할 때 나올 아이로, 웹 개발을 진행하는데 필요한 여러 라이브러리를 설치해야할 때 'npm' 을 사용하게 된다.

  • node.js의 package manager(세계에서 가장 큰 오픈 소스 library 생태계)
  • node를 사용하는데 필요한 패키지들을 설치할 때 사용한다.

 

ES6란?

원래 javascript는 기존 HTML로 만들어진 정적인 element들을 역동적으로 구현하기 위해 생성된 언어이다. (made by 넷스케이프)

  • 이후에 넷스케이프 외에도 IE같은 다른 브라우저들도 비슷한 언어를 개발하기 시작하여, 이들을 표준화하기 위해 나온 것이 ECMAScript이다.
  • ES6란 ECMAScript의 6번째 버전을 의미한다. (2015년에 발표되어 ECMAScript 2015라고도 불린다)
  • 아직까지 많은 곳에서 ES6를 표준으로 쓰고있다고 한다!

 

 

기존 JS 문법 + ES6 버전에 추가된 새로운 문법들을 확인해보겠다.

JS의 기본 문법

조건문

if (조건문) {
	실행문
} elseif (조건문) {
	실행문
} else {
	실행문
}

 

반복문 (+조건문, 함수정의)

function isValidAge(person) {
	if (person["age"] > 19) {
		return true
	} else {
		return false
	}
}

var personArray = {
	"name": "Moon", "age":23, 
	"name": "Younji", "age": 23,
}

for (var i=0; i< personArray; i++) {
	console.log(personArray[i]['age']);
	if (isValidAge(personArrayi[i]) {
		console.log("Here is your Beer!");
	} else {
		console.log("Get out!");
	}
}

 

예시) 연령 평균 구하기

function getAgeAverage(personArray) {
	var average = 0;
    for (var i=0; i<personArray.length; i++) {
        average += personArray[i]['age']
    }
    average /= personArray.length
	// 연령 평균을 구해주는 함수를 만들어 봅시다.
	// 평균은 총합을 갯수로 나눠주면 됩니다.

	return average;
}

var personArray = [
										{"name": "John Doe", "age": 20},
										{"name": "Jane Doe", "age": 19},
										{"name": "Fred Doe", "age": 32},
										{"name": "Chris Doe", "age": 45},
										{"name": "Layla Doe", "age": 37},
									];

console.log(getAgeAverage(personArray)); // 30.6

 

ES6의 새로운 문법

1) var, let, const

2) 호이스팅(Hoisting)

3) 반복문의 변형

4) arrow function (화살표 함수)

5) Promises (다음 글에서!)

var

기존에 변수를 할당해줄 때는 var를 이용해주었다.

  • var의 문제점은 범위의 개념이 없다는 것이다.
var num = 10;
if (num==10) {
	var num = 20;
	console.log("num in if : ", num);  // 20이 출력
}

console.log(num);   // if문 밖에서 정의한 10이 찍힐 줄 알았지만 20이 찍힘

 

let

ES6부터는 scope 라는 개념이 추가된 let 을 사용할 수 있다.

  • 재선언(같은 범위 안에서 같은 변수명으로 선언)은 할 수 없지만 재할당은 할 수 있다.
let num = 10;
if (num==10) {
	let num = 20;
	console.log("num in if : ", num);  // 20이 출력
}

console.log(num); // 10이 찍힘
  • scope는 변수의 접근을 결정한다. 위 예제처럼 if문 안에서 선언된 num은 if문 밖에서 접근이 불가능하다.

 

const

변하지 않는 상수 를 선언할 때 쓰인다.

재선언도, 재할당도 할 수 없다.

const PI = 2.1415;
PI = 3.141592;   // Error

 

 

Hoisting(호이스팅)

ES6에서 가장 크게 변화된 요소 중 하나

  • 함수 안에 있는 선언들을 모두 끌어올려서 해당 함수 내의 최상단에 선언하는 것을 의미한다.
  • 변수나 함수를 미리 선언해놓고, 순차적으로 사용하는 것이다. (실제 코드가 변동되는 것이 아닌, 자바스크립트 parser 내부적으로 이루어진다.)
  • Hoisting에서는 var 변수를 쓸 경우 문제가 발생할 수 있다.

 

이제 var 대신 const, let을 쓰는 습관을 들이자!

 

 

반복문의 변형

기존의 반복문은 for 루트!

  • 변형된 for of 반복문
    • 편리한 점은 반복문의 길이를 명시해주지 않아도 된다는 점이다.
const students = ["Moon", "Younji", "Kim"];
for (let student of students) {   // students 배열에서 student를 하나씩 접근
	console.log(student);
}

배열의 원소를 꺼내주는 게 for of라면, for in은 배열의 원소의 위치를 출력해준다.

 

  • 변형된 for in 반복문
    • 배열의 원소 위치(index)를 출력한다.
const students = ["Moon", "Younji", "Kim"];

for (let index in students) {
	console.log(student);   // 0 1 2
	console.log(students[index]);
}

 

  • 변형된 for each 반복문
    • 해당 배열의 원소에 하나씩 접근하여 Callback함수를 실행시킨다.
    • 형식은 students.forEach(Callback함수 선언);
const students = ["Moon", "Younji", "Kim"];

students.forEach(student) => {
	console.log(student);  //Moon Younji Kim
})
웹 개발 관련 코드를 볼 때 forEach를 사용하는 것을 많이 볼 수 있었는데 이 의미였군..

 

 

arrow function (화살표 함수)

기존의 함수와 기능은 비슷하지만, 화살표(⇒)가 있다 하여 arrow function이라 한다.

  • 형식은 const 함수명 = (인자) => {}; 로, 상수에 함수를 담아주는 것이다.
  • 함수명(); 으로 호출해줄 수 있다.
const arrowFunction = () => {
	console.log("Hello arrow function");
}

arrowFunction();  //"Hello arrow function" 출력
  • 만약 함수 내부 실행문이 한 줄 일 때는 중간 괄호 없이 선언해줄 수 있다.const arrowFunction = () => console.log("Hello arrow function");

 

기존 함수와 Arrow Function은 완전히 같은 함수일까?
몇가지 차이가 있으나, 대표적으로 this가 가리키는 곳이 다르다.
화살표 함수에서의 this는 자신을 감싼 정적 범위이다.
[참고]

 

예시) arrow function과 forEach를 사용한 연령 평균 구하기

let personArray = [
    {"name": "John Doe", "age": 20},
    {"name": "Jane Doe", "age": 19},
    {"name": "Fred Doe", "age": 32},
    {"name": "Chris Doe", "age": 45},
    {"name": "Layla Doe", "age": 37},
];

// personArray의 나이 평균을 구해주는 Arrow Function을 작성해봅시다.
const getAgeAverage = (personArray) => {
    let sum = 0;
    for (person of personArray) {
        sum += person['age'];
    }
    const average= sum / personArray.length;
    return average;
}

console.log(getAgeAverage(personArray));

 


코딩 퀴즈 (쉽습니다ㅎㅎ) 

스파르타 코딩클럽 1주차 코딩 퀴즈

1. 객체 내용 출력하기

var personArray = [
	{"name": "John Doe", "age": 20},
	{"name": "Jane Doe", "age": 19},
];

// 위에서 배운 4가지 for문을 이용해서 아래 문장을 출력해봅시다 (console.log)

// His/her name is John Doe. He/She is 20 years old.
// His/her name is Jane Doe. He/She is 19 years old.
더보기

정답

// for문 종류로는 일반 for문, forOf, forIn, forEach가 있었죠!

//일반 for문
for (let i=0;i<personArray.length;i++) {
    person = personArray[i]
    console.log(`His/her name is ${person['name']}. He/She is ${person['age']} years old.`);
}

// forIn : 원소 위치 출력!
for (let idx in personArray) {
    person = personArray[idx];
    console.log(`His/her name is ${person['name']}. He/She is ${person['age']} years old.`);
}

// forOf
for (let person of personArray){
    console.log(`His/her name is ${person['name']}. He/She is ${person['age']} years old.`);
}

// forEach : 각 원소에 함수 적용
personArray.forEach((person) => {console.log(`His/her name is ${person['name']}. He/She is ${person['age']} years old.`);
});

 

2. 홀수/짝수 구분 함수 만들어보기

function isEven(n) { 
  // n이 짝수면 true, 홀수면 false 를 반환하는 함수를 만들어 봅시다
}
function isOdd(n) { 
  // 반대로 n이 홀수면 true, 짝수면 false 를 반환하는 함수를 만들어 봅시다
}

console.log(isEven(10)); // true
console.log(isEven(3)); // false
console.log(isOdd(5)); // true
console.log(isOdd(8)); // false
더보기

정답

function isEven(n) { 
    if (n%2 == 0){
        return true;
    } else if (n%2 !=0) {
        return false;
    }
    // n이 짝수면 true, 홀수면 false 를 반환하는 함수를 만들어 봅시다
}
function isOdd(n) { 
    if (n%2 !=0) {
        return true;// 반대로 n이 홀수면 true, 짝수면 false 를 반환하는 함수를 만들어 봅시다
    } else if (n%2 == 0) {
        return false;
    }
}
  
  console.log(isEven(10)); // true
  console.log(isEven(3)); // false
  console.log(isOdd(5)); // true
  console.log(isOdd(8)); // false

 

3. John Doe만 마실 수 있는 맥주

function checkName(person) {
	// 사람의 이름이 "John Doe" 일때만 true 를 리턴해주도록 합시다.
    
}

var personArray = [
                    {"name": "Mark Bae", "age": 30},
                    {"name": "John Doe", "age": 20},
                    {"name": "Jane Doe", "age": 19},
                ];

for (var person of personArray) {
	if (checkName(person)) {
		console.log("Here is your beer! ", person["name"]);
	} else {
		console.log("Get out! ", person["name"]);
	}
}
더보기

정답

function checkName(person) {
    if (person["name"] == "John Doe") {
        return true;
    } else {
        return false;
    }    
}

var personArray = [
                    {"name": "Mark Bae", "age": 30},
                    {"name": "John Doe", "age": 20},
                    {"name": "Jane Doe", "age": 19},
                ];

for (var person of personArray) {
	if (checkName(person)) {
		console.log("Here is your beer! ", person["name"]);
	} else {
		console.log("Get out! ", person["name"]);
	}
}

 

4. 미성년자만 찾아보기

function getChildrens(personArray) {
	// 20세이하의 사람들만 배열로 반환해봅시다
}

var personArray = [
    {"name": "John Doe", "age": 10},
    {"name": "Jane Doe", "age": 29},
    {"name": "Fred Doe", "age": 13},
    {"name": "Chris Doe", "age": 22},
    {"name": "Layla Doe", "age": 8},
];

console.log(getChildrens(personArray)); 
// [
// 	{"name": "John Doe", "age": 10},
// 	{"name": "Fred Doe", "age": 13},
//  {"name": "Layla Doe", "age": 8},
// ]
더보기

정답

function getChildrens(personArray) {
    child = [];
	for (person of personArray) {
        if (person["age"] < 20) {
            child.push(person)
        }
    }
    return child;
}

var personArray = [
    {"name": "John Doe", "age": 10},
    {"name": "Jane Doe", "age": 29},
    {"name": "Fred Doe", "age": 13},
    {"name": "Chris Doe", "age": 22},
    {"name": "Layla Doe", "age": 8},
];
console.log(getChildrens(personArray));

 

공부하면서 정리한 내용이라 잘못된 내용이 있을 수 있습니다.
따뜻한 피드백은 환영입니다♥
반응형