본문 바로가기
ONLINE COURSES/JavaScript

Basics-3 function // loops // iterations

by jono 2021. 6. 13.

0. FUNCTION DECLARATIONS

//FUNCTION DECLARATIONS 

function greet(firstname, lastname){
  return 'hello '+ firstname + lastname;
}
console.log(greet('nick', ' james'));             // hello nick james


function greet(firstname = 'nick', lastname = ' james'){
  return 'hello '+ firstname + lastname;
}
console.log(greet());                      //hello nick james      

 

1. FUNCTION EXPRESSIONS

const 제곱 = function(x){
  return x*x;
};
console.log(제곱(5));     //25

 

2. IMMIDIATLY INVOKABLE FUNCTION EXPRESSIONS == IIFEs
(function( ) { } ) ( );

(function(){
  console.log('IIFE Ran..');
})();                               //IIFE Ran..

(function(name){
  console.log('hello ' +name);
})('richard');                   //hello richard

 

3. PROPERTY METHODS

const todo={
  add: function(){
    console.log('add todo...');
  },
  edit: function(id){
    console.log(`edit todo ${id}`);
  }
}

todo.add();            //add todo...
todo.edit(22);         //edit todo 22


todo.delete = function(){
  console.log('delete todo...');
}
todo.delete();         //delete todo...

4. LOOP

-for loop

for(let i =0; i<10 ;i++){
  console.log('number: '+ i);
}


for(let i =0; i<10 ;i++){
  if(i === 2){
    console.log('2 is my favorite number');
  }
  
  if(i === 5){
    console.log('stop the loop');
    break;
  }
  console.log(i);
}

 

-while loop

//WHILE LOOP   { } 안에 i++들어간다

let i = 0;
while (i<10){
  console.log('number '+i);
  i++;
}

 

- do while  : always gonna run no matter what

let i =100;
do {
  console.log('number '+i);
  i++;
}
while(i<10);            //number 100

 

- loop through array

const cars = ['ford', 'chevy', 'honda', 'toyota'];
for (let i=0; i<cars.length; i++){
  console.log(i);
}                             // 0,1,2,3 한줄씩 출력


//cars[i]
const cars = ['ford', 'chevy', 'honda', 'toyota'];
for (let i=0; i<cars.length; i++){
  console.log(cars[i]);
}                           //ford, chevy, honda, toyota 한줄씩 출력

-> 대신 forEach( ) 를 사용하면 깔끔하다

cars.forEach(function(car){
  console.log(car);
});

//또는
cars.forEach(function(car, index){
  console.log(`${index} : ${car}`);
});

 

-MAP

const users = [
  {id:1, name:'richard'},
  {id:2, name:'james'},
  {id:3, name:'jolie'},
  {id:4, name:'kara'}
];

const ids = users.map(function(user){
  return user.id;
});

console.log(ids);         //(4) [1,2,3,4]

 

-for (in)

const user = {
  firstname: 'richard',
  lastname: 'kim',
  age:35
}

for(let x in user){
  console.log(x);
}                   //key에 해당하는 firstname, lastname, age 를 한줄씩 반환함

for(let x in user){
  console.log(`${x} : ${user[x]}`);
}            
// firstname : richard , lastname : kim , age : 35를 한줄씩 반환함

'ONLINE COURSES > JavaScript' 카테고리의 다른 글

DOM-1  (0) 2021.06.14
Basics-4  (0) 2021.06.13
Basics-2  (0) 2021.06.12
Basics-1  (0) 2021.06.12
Object 객체 { }  (0) 2021.05.31

댓글