03_JavaScript: Function & Arrow Function

03_JavaScript: Function & Arrow Function

·

2 min read

Ex01. Basic Function

function add(a,b) {
    return a + b;
    console.log('You should not write your code below'); //Not work
}
const sum = add(1,2);
console.log(sum); //3

Ex02. Basic Function : String

function Hello(name) {
    console.log('Hello, ' + name + '!');
}
hello('dana'); //"Hello, dana!"
// Template Literal(ES6) : Backtick + ${}
function hello(name) {
    console.log(`Hello, ${name}!`);
}
hello('dana');
  • ` = Backtick = Backquate = grave accent

Ex03. Example : Grade Calculator

// Arrow Function
// function getGrade = (score) => {
// function getGrade = score => {
function getGrade(score) {
  if (score === 100) {
    return 'A+';
  } else if (score >= 90) {
    return 'A';
  } else if (score === 89) {
    return 'B+';
  } else if (score >= 80) {
    return 'B';
  } else if (score === 79) {
    return 'C+';
  } else if (score >= 70) {
    return 'C';
  } else if (score === 69) {
    return 'D+';
  } else if (score >= 60) {
    return 'D';
  } else {
    return 'F';
  }
}

const grade = getGrade(90);
console.log(grade);

Ex04. Arrow Function

const add = (a, b) => {
    return a + b;
};
console.log(add(1,2));
const add = (a, b) => a + b;
console.log(add(1,2));
  • The big difference between the normal function and the arrow function is THIS

cf. https://learnjs.vlpt.us/basics/05-function.html