JS | 함수, 반복문

yeeun lee·2020년 7월 1일
0

Javascript

목록 보기
2/4

codecademy javascript 강의 벨로그에 옮기기는 중 😚

1. Function

1.1 함수 선언

How to declare a function 🤔

function identifier() { 
	function body 
} // 파라미터 비어있을 경우

identifier(); // 함수 호출 

- Parameters & Arguments

매개변수, 인자. 함수가 인풋을 받을 수 있게 하고, 인풋을 사용해 perform 할 수 있게 한다. 만약 파라미터가 있으면, 호출할 때 value 를 지정하고 이 것을 argument 라고 한다.

Function calculator (width, height) { // width, height : parameter 
	console.log (width * height) 
}

calculator (3, 5); // 3,5 : argument
  • Default parameter: 인자가 입력되지 않았을 때의 기본 값. 파라미터 1개에 하나만, 각각 지정할 수 있다.
Function greeting(name=‘stranger’) {
	console.log(`hello ${name}`)
}
greeting() // hello stranger 

- Return statement

The return keyword is powerful because it allows functions to produce an output. We can then save the output to a variable for later use.

리턴을 하게 되면, 다음 코드는 작동하지 않는다.

- Scope

the context in which our variables are declared. 

  1. Block scope: inside of curly bracket { } and variables called local variable
  2. Global scope: outside of curly bracket and variables called global variable
  • Global scope 에서 지정한 변수를 로컬에서 쓸 경우, 변수가 바뀐다.
  • Block 내에서 같은 이름으로 assign 해도 글로벌에서는 value 가 바뀌지 않는 점을 유의!

Scope pollution : 변수가 namespace에 너무 많거나 변수 이름이 중복될 때. 랜덤생성기의 경우 밖에 있으면 다른 함수에서 쓸 때 동일할 수 있다.

1.2 함수 정의

함수 표현식을 사용해서 변수를 할당하는 것. 이 때 함수의 이름은 생략된다. 변수는 const 로!

Const variable = function ( ) { } 

1.3 Arrow function

arrow fuction에서는 function이라는 단어를 생략한다.

Const variable = (parameter) => { 
	function body 
	} 

Concise body arrow function은 하나의 파라미터를, function body는 single line statement를 가진다. (), {} 가 사라짐!

Const variable = parameter => statement ;  

2. Array

Square bracket 안에 요소element들을 추가하는 것. let, const 사용 시 const 는 배열 내 요소를 바꿀 수 있으나, Reassign은 불가하다.

Nested array -> can chain bracket like [0][1] 0번째 요소의 1번째 요소

  • .length -> property
  • .push ( ) -> method that add items to the end of an array. 
  • .pop ( ) -> remove the last item <=> .shift()
  • .slice ( a, b+1 ) a 번째부터, b 번째까지
  • indexOf(value) -> find index number

3. Loops

repeats a set of instructions until a specified condition, called a stopping condition is reached.
Iterate = to repeat
Nested loop : Each time the outer loop runs, the inner loop completes all iterations.

For loop

When we know how many times the loop should run

반복할 변수를 생성한다 Iterator variable is initialized
멈출 조건을 만든다 (false 일 때 스탑 ) Stopping condition = if condition evaluates to false
반복 조건을 만든다 Iteration statement : happened after each loop
실행할 코드 블록을 만든다 Code block{}

for (let i = 5; i < 11 ; i++) {
  console.log(i);
}

While loop

when we want a loop to execute an undetermined number of times,

반복할 변수를 loop 전에 생성한다.
멈출 조건을 만든다. 내가 보고 싶은 결과와 반대로 해야 결과가 나오면 멈춤. Stopping condition, or test condition (it works until being evaluated false)
실행할 코드 블록을 만든다
반복 조건을 만든다. -> 없을 경우 infinite loop 가 생성되므로 유의

i = 0 
While ( i < 5 ) { console.log(i); i++; }

do…while

do a task once and then keep doing it until a specified condition is no longer met.
Unlike the while loop, do...while will run at least once whether or not the condition evaluates to true.

Do { code block } while ( condition );  

- break keyword

The break keyword allows programs to “break” out of the loop from within the loop’s block. we can add test conditions besides the stopping condition, and exit the loop when they’re met.

4. Higher function

JavaScript functions are first-class objects, so they have properties and methods like any object

functions as data

functions that accept other functions as arguments and/or return functions as output. 함수 이름이 길 경우 변수에다가 함수를 넣고 함수처럼 실행할 수 있다. 함수 이름은 .name property 사용

functions as parameter = callback function

const timeFuncRuntime = funcParameter => {
  let t1 = Date.now();
  funcParameter(); // 실행될 함수를 변수로 넣은 것. 그러니까 함수를 변수로 쓰는 것.
  let t2 = Date.now();
  return t2 - t1;
};
const time2p2 = timeFuncRuntime(checkThatTwoPlusTwoEqualsFourAMillionTimes);
// 2+2=4가 아니라는 것을 확인하는 함수가 걸리는 시간을 구하는 것 
profile
이사간 블로그: yenilee.github.io

0개의 댓글