eajni IT 초보사전 💦💦

[JavaScript] 자바스크립트 기초 (함수)

2023-07-28

Functions

  • a block of code designed to perform a particular task in a brackets({})
  • inside the function, the arguments behave as local variables

define

function funcName(){
	//act when it called
	return value; //하나의 반환 값 저장 후 함수 중단
}

function funcName(arguments...){
	//act when it called
}

run

funcName();
funcName();

다차함수

  • 다른 함수 내부에서 함께 작동하는 함수
    • 다른 함수를 인수로 받음
    • 함수를 반환

반환함수

  • return에서 연산

Factory 함수

  • 재활용 가능한 구조를 가진 함수

Scope

Block Scope

Lexical Scope

  • 중첩 함수 내부의 함수는 외부 함수에 접근 가능
  • 외부 함수는 내부에 접근 불가

Arrow Functions (ES6~)

  • with arrow functions there are no binding of this ```js //without parameter greeting = function() {
    return ”Hello World!”;
    }

greeting = () =>{ return “Hello World!”; }

//암시적 반환 : 단 하나의 값만 반환 가능 greeting = () => “Hello World!”;

//with parameter greeting = (val) => “Hello” + val;

greeting = val => “Hello” + val;




---

### ex.

#### 배열의 마지막 인덱스 값 출력

```js
function lastElement(array){   
    let lastIndex = array.length-1;

    if(!array.length){
        return null;
    }else{
        return array.slice(lastIndex)[0];
        
    }

첫문자만 대문자 만들기

function capitalize(word){
    const newWord = word.charAt(0).toUpperCase() + word.slice(1);
    
    return newWord;
}

배열 값 합계 구하기

function sumArray(arrayN){
    let total =0;
    for(let i=0;i<arrayN.length;i++){
         total += arrayN[i] ;
    }
    return total;
}

요일 계산

function returnDay(num){
    switch (num) {
        case 1:
            return "Monday";
        case 2:
            return "Tuesday";
        case 3:
            return "Wednesday";
        case 4:
            return "Thursday";
        case 5:
            return "Friday";
        case 6:
            return "Saturday";
        case 7:
            return "Sunday";
        default:
            return null;
    }
}

Comments

Content