독서하는 개발자's Blog

반응형

바닐라(vanilla-js) JS를 공부해봅시다 - 2

1. 함수를 정의할 수 있어야한다.


-> function 을 붙힘으로써 함수를 정의할 수 있다. 여기서 함수는 "기능"을 말한다.

ex) function hello(){

console.log("안녕");

}

hello();   ==> 안녕

hello("hello my name");  ==> 안녕

왜 hello() 함수안에 "hello my name"이라고 썻는데 안녕이 출력이 될까???


* 오늘의 단어는 argument (인자)

ex) hello("괄호안에 쓰는 것이 인자");


2. 함수에게 외부 데이터를 줄 수 있어야한다.  ( 1번에 대한 이유도 함께 보자 )


argument는 변수와 같은 것.

ex) function hello(hihihihi){

console.log("안녕", hihihihi);

}


hello("hello my name");


hello함수에 hihihihi라는 인자로 hello my name이라는 String을 console.log에 hihihihi에게 보내준다.

그럼 출력은 ==> 안녕 hello my name


ex) function hello(hihihihi){

console.log("안녕", hihihihi);

}     // 참고로 여기에서의 인자값은 두개이다. "안녕" 과 hihihihi

// console.log(arg1, arg2)


3. 자바스크립트는 텍스트이고 텍스트에 변수를 쓸 수 없다.


그렇기 때문에 예전 방식을 확인해보면

ex) function hello(name, age){

console.log("안녕" + name + "is" + age + "살이야");

}            // 텍스트와 변수를 + 기호로 구분하였다.

hello("개발자" , 26);


출력하면 ==> 안녕개발자is26살이야    /// 난감하네~~~


여기서 자바스크립트에서 " "나 ' '는 둘다 String이다.


그래서 자바스크립트에서 생각해 낸 것이 백틱 ` `

백틱은 키보드 숫자 1 왼쪽에 있다.


ex) function hello(name, age){

console.log(`안녕 ${name} is ${age} 살이야`);

}

hello("개발자" , 26);


예전 방식과는 다르게 백틱을 써서 사용하면 + 기호와 띄어쓰기를 신경 쓸 필요없이 한번에 작성할 수 있다.


4. 함수안에서 return 값을 외부에서 받을 수 있어야한다.


function hello(name, age){

console.log(`안녕 ${name} is ${age} 살이야`);

}

const greet = hello("개발자" , 26);

console.log(greet);


이렇게 실행하면 undefined가 나오며 greet변수는 hello함수의 리턴 값이다.


undefined가 나오지 않게 하려면 우리는 조금만 바꾸면 된다.


function hello(name, age){

     return `안녕 ${name} is ${age} 살이야`;

}

const greet = hello("개발자" , 26);

console.log(greet);


hello함수 안에 있던 console.log를 return으로 만 바꿧더니 출력이 된다.


5. 함수 기능을 객체 안에서 구현할 수 있어야 한다.


const calculator = {

  plus : function(a,b){

  return a + b;

  }

}

const plus = calculator.plus(5,5);


console.log(plus);        ==> 10

반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band