김숭늉 마음대로

왕초보 자바스크립트(코딩앙마) #10 함수(function) 본문

IT/JavaScript

왕초보 자바스크립트(코딩앙마) #10 함수(function)

김숭늉이 2023. 3. 12. 14:46
728x90

 

 

 

1. 브라우저가 가지고있는 내장함수

    ex) console. alert. confirm... 등

 

// 함수작성
// 매개변수가 없는 함수

function showError(){
  alert('에러가 발생했습니다. 다시 시도해주세요')
}

showError(); //함수 호출

 

//함수 작성

function sayhello(name){
  const msg = `hello, ${name}`;
  console.log(msg)
}

sayhello('seungyeon')  // 함수 호출
sayhello('minyhyeok')  // 함수 호출
//함수 작성
function guenyang(name){
  const altmsg = 'hello ' + name + ', welcome!';
  console.log(altmsg)
}

guenyang('seungyeon')
function sayhello(name){
  let msg = `hello,`;   // let으로 수정!
  if(name){   // 만약에 name이 있으면
    msg = `hello, ${name}`;
  }
  console.log(msg)
}

sayhello()
sayhello('seungyeon')

 

function sayhello(name){
  let msg = `hello`;
  if(name){
    msg += ', ' + name;
  }
  console.log(msg)
}

sayhello()
sayhello('seungyeon')

함수 안에서의 변수는 지역 변수로, 함수 안에서만 사용할수 있음 

 

전역변수화지역변수는 서로 영향을 받지 않음!

let msg = 'hello';    // 전역변수(global varable)
console.log('함수 호출전')
console.log(msg)

function sayhello(name){
  let msg = `hello`;
  if(name){
    msg += ', ' + name;
  }
  console.log('함수 내부!')
    // 지역 변수 (local varable)
  console.log(msg)
}

sayhello('seungyeon')
console.log('함수 호출 후')
console.log(msg)

 

 

 

function sayHello(name){
  let newName = name || 'friend';
    let msg =`Hello, ${newName}`
  console.log(msg)
}

sayHello()   // hello, friend
sayHello('jane')    // hello, jane
 
 
깔끔하게는 아래와같이 이렇게도 작성!
function sayHello(name = 'friend'){   // name에 디폴트값 설정
    let msg =`Hello, ${name}`
  console.log(msg)
}

sayHello()   // hello, friend
sayHello('jane')   // hello, jane

 

//return으로 값 반환
function add(num1, num2) {
  return num1 + num2;
}

const result = add(2,3);    
console.log(result)

return문이 없어도 값을 반환하는 경우도 있음!

return 문이 있으면 그 즉시 값을 반환하고 종료하게 됨!

 

function showError(){
  alert('에러가 발생했습니다');
  return;
  alert('이코드는 절대 실행되지 않음 ');
}

const result = showError();
console.log(result);

 

 

728x90
반응형