LoginSignup
0
0

More than 5 years have passed since last update.

함수선언식과 함수 표현식,화살표함수

Posted at
filename.js
    let name = 'john';
    alert(`hello,${name}`);
    alert(`the result is ${1+2}`);
    // 백틱안에서는 내부표현식을 사용할수 있다.

    alert( "the result is ${1 + 2}" ); // the result is ${1 + 2} 
    // 내부 표현식은 백틱에서만 사용할수 있다
filename.js
// 콜백함수
function ask (question,yes,no) {
    if(confirm(question)){
        yes()
    } else {
        no()
    }
}

function showOk() {
    alert('You agreed')
}

function showCancel() {
    alert('You canceled the excution')
}

ask("Dou you agree?",showOk, showCancel);


// 함수포현식을 이용하여 코드양을 줄임

function ask (question, yes, no) {
    if(confirm(question)) yes();
    else no();
}

ask('Do you agree',
    function() {alert('You agreed')},
    function() {alert('You canceled the excution')}
);

함수선언식과 함수 표현식

filename.js
// 함수선언식과 함수 표현식 Function Expression vs Function Declaration
// 함수선언식
function sum(a, b) {
    return a + b;
}
// 함수표현식
let sum = function() {
    return a + b
}

let age = prompt('what is your age', 18);
let welcome;

if(age < 18) {
    welcome = function() {
        alert('Hello');
    }
} else {
    welcome = function() {
        alert('Greetiong!');
    }
}

welcome();
-----------------------------------------------------------------
// 삼항연산자를 이용하여 표현
let age = prompt('What is your age?',18);
let welcome = age < 18 ? 
    function() {alert('hello')}:
    function() {alert('Greeting!')}

welcome();
-----------------------------------------------------------------
// 화살표 함수
let func = function(arg1, arg2, ...argN) {
    return expression;
}

let sum = (a, b) => a + b;

let double = n => n * 2;
alert(double(3)); // 6

let sayHi = () => alert('Hello');
sayHi();
-----------------------------------------------------------------
// 삼항연산자 + 화살표함수
let age = prompt("What your age?", 18);
welcome = age < 18 ?
    () => alert('Hello'):
    () => alert('Greetiong!');
welcome();
-----------------------------------------------------------------
// 여러줄 화살표함수
let sum = (a, b) => {
    let result =  a + b;
    return result;
}
alert(sum(3,3)); //6

화살표함수로 변환하기

filename.js
// 문제
function ask(question, yes, no) {
  if (confirm(question)) yes()
  else no();
}

ask(
  "Do you agree?",
  function() { alert("You agreed."); },
  function() { alert("You canceled the execution."); }
);

// 화살표 함수로 변환

function agree(quesetion, yes, no) {
    if (confirm(question)) {
        yes();
    } else {
        no()
    }
}

ask('do you agree?',
    () => alert("You agreed."),
    () => alert("You canceled the execution.")
);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0