티스토리 뷰

개발/javascript

함수(Function)

JH._.kim 2021. 4. 9. 20:33

노마드코더 바닐라 JS로 크롬 앱 만들기 #2.0 ~ #2.2 강의 들으며 정리.

 

 

함수 만들기 / argument

 

function sayHello(){
  console.log('hello!');
}
sayHello('you');

 

함수실행에서 you라고 넣어도 값을 받아 오지 않고 console에서는 여전히 hello라고 나온다. 이유는 인자(argument)가 없기 때문.
함수 안에 인자를 써 줘야 값을 받아 올 수 있음.

 

 

function sayHello(who){
  console.log('hello!', who);
}
sayHello('you');

 

이렇게 인자를 넣어주면 함수실행에서 넣은 값을 받아 올 수 있다.

 

 

function sayHello(name, age) {
  console.log('hello!', name, 'you are', age, 'years of age.');
  
  // 간결하게 쓰는 법 - 백틱 `` 을 이용.
  console.log(`hello! $(name) you are $(age) years old`);
};

sayHello('jh', 10);
// 결과 - hello! jh you are 10 years of age.

백틱(`)을 사용하면 더 간편하게 작성할 수도 있다.

 

 


return

함수 실행을 종료하고, 값을 제공한 경우 주어진 값을 함수 호출 지점으로 반환.

 

 

function sayHello(name, age) {
  console.log(`hello! $(name) you are $(age) years old`);
};

const greetMe = sayHello('jh', 10);
console.log(greetMe);

이렇게 하면 다음과 같은 결과가 도출된다.

 

 

왜 undefined가 떴을까?

 

greetMe는 sayHello의 출력값인데 sayHello에서는 이미 console.log로 인해 값이 출력되고 끝났다. 되돌아올 값이 없기 때문에 undefined가 나오는 것. 

 

 

function sayHello(name, age) {
  return (`hello! $(name) you are $(age) years old`);
};

const greetMe = sayHello('jh', 10);
console.log(greetMe);

return으로 바꿔주면 undefined가 뜨지 않는다.

 

 


 

계산해보기

 

const calculator = {
  plus: function(a, b){
    return a + b;
  },
  minus: function(a, b){
    return a - b;
  },
  divide: function(a, b){
    return a / b;
  },
  multiply: function(a, b){
    return a * b;
  },
  remainder: function(a, b){
    return a % b;
  },
  involution: function(a, b){
    return a ** b;
  }
}
const plus = calculator.plus(3, 5);
const minus = calculator.minus(8, 6);
const divide = calculator.divide(8, 2);
const multiply = calculator.multiply(3, 9);
const remainder = calculator.remainder(5, 2);
const involution = calculator.involution(2, 3);

console.log(plus, minus, divide, multiply, remainder, involution);

 

 


 

DOM

 

Document Object Module

자바스크립트에서 HTML 요소를 가져와서 dom 객체로 바꾼다.

 

const title = document.querySelector('#title');
// querySelector -> 노드의 첫번째 자식을 반환함.
console.log(title);
title.innerHTML('hi!');
title.style.color = 'red';

console.dir(title); 
//객체로 변경된 속성을 열람

 

 

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
250x250