자바스크립트 잡으러 바다로 갈까요

차곡·2022년 3월 14일
0

1. Variable

Variable : 변수를 선언할 수 있는 유일한 키워드
(변경될 수 있는 값 읽고 쓰기 가능)

let (added in ES6)

let name = 'hello';
console.log(name);
hello

js에서 변수는 하나

block scope { }
모든 코드 블록 내에서 선언된 변수는
코드 블록 내에서만 유효하며 코드 블록 외부에서는 참조할 수 없다

let 키워드로 선언된 변수는 블록 레벨 스코프를 따른다.

hoisting (호이스팅)
어디에 선언했느냐와 상관없이 항상 제일 위로 선언을 끌어올려 준다
함수 안에 있는 선언들을 모두 끌어올려서 해당 함수 유효 범위의 최상단에 선언하는 것

2. constant

constant
한 번 값을 할당하면 그 값이 절대 바뀌지 않는다 (읽기만 가능)

mutable data type: 값 변경 가능
immutable data type : 값 변경 불가능

security
thread safety
reduce human mistakes

3. variable types

primitive single item
number, string, boolean, null, undefined, symbol
더 이상 작은 단위로 나눠질수없는 한가지 싱글 아이템

boolean (참/거짓)
false: 0, null, undefined, NaN, ''
true : any other value

null (값이 비어있는 상태)
let nothing = null;

undefined (값이 초기화된 상태)
lex x;

Symbol (고유하고 변경할 수 없는 기본 값)

object, box coatainer
싱글 단위를 여러개 묶어서 한 단위로 관리할 수 있게 해주는 것

function, first-class function

5. Dynamic typing

동적 타이핑
변수를 지정할 때 명시하지 않아도 컴퓨터가 알아서 해석
프로그램이 동작할 때 할당된 값에 따라서 타입이 변경될 수 있다

function

하나의 특별한 목적의 작업을 수행하도록 설계됐으며
여러번 재사용이 가능하다.

1. Function declaration 함수 선언
하나의 함수는 한가지의 일만 하도록 만들어야 함
JS에서 function은 object

function name(patam1, 2) {body.. return;}

function printHello() {
    console.log('Hello');
}
printHello();

Parameters 인수
premitive: passed by value (값이 그대로 전달)
object: passed by reference (reference 값이 전달)

function changeName(obj) {
    obj.name = 'coder';
}
const ellie = { name: ''};
changeName();
console.log();

Default parameters
ES6에서 추가됨

function showMessage(message, from) {
  console.log(`${message} by ${from}`);
}
showMessage('Hi!');

파라미터 값이 전달이 안돼도 undefined이라고 출력된다
최신에는 파라미터 옆에 undefined일 때 원하는 default 값을 지정해놓는다

Rest parameters
ES6에서 추가됨
dot 3개를 작성하면 (...) rest parameters 배열 형태로 전달됨

for loop 

function printAll(...args) {
  // for loop 사용법
  for(let i = 0; i < args.length; i++) {
    console.log(args[i]);
  }
}
printAll('dream', 'coding', 'ellie'); 


for of

function printAll(...args) {
   // for of 문법 사용
  for (const arg of args) {
    console.log(arg);
  }
}
printAll('dream', 'coding', 'ellie'); 


for each

function printAll(...args) {
  // 배열의 forEach 함수 사용
  args.forEach((arg) => console.log(arg));
}

Local scope
밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다
global variable (block scope 밖에 쓰여진 변수)
local variable (block scope 안에 쓰여진 변수)

let globalMessage = 'global'; // global variable
function printMessage() {
  let message = 'hello'; // local variable
  console.log(message); 
  console.log(globalMessage);
}
printMessage();

function printMessage() {
  let message = 'hello'; // global variable
  console.log(message); 
  console.log(globalMessage);
  function printAnother() {
    console.log(message);
    let childMessage = 'hello'; // local variable
  }
}

Return a value

function sum(a, b) {
  return a + b;
}
const result = sum(1, 2); // 3
console.log(`sum: ${sum(1, 2)}`);

모든 함수는 리턴 값이 undefined이거나 우리가 값을 지정할 수가 있다

Early return, early exit

function upgradeUser(user) {
  if(user.point <= 10) {
    return;
  }
 // long upgrade logic...
}

return을 빨리하여 함수를 종료
조건이 맞을 때만 필요한 로직 실행

arrow function
함수를 매우 간결하게 만들어준다

const simplePrint = function () {
  console.log('simplePrint!');
} // 1번

const simplePrint = () => console.log('simplePrint!'); // 2번

const add = function (a, b) {
  return a + b;
} // 1번

const add = (a, b) => a + b; // 2번

1번 방식을 화살표 함수를 이용해 2번처럼 작성 가능
블럭을 사용하게 되면 return 키워드를 사용해서 값을 리턴해야함

IIFE
선언과 동시에 바로 송출

function hello() {
  console.log('IIFE');
}
hello(); // hello // 1번

(function hello() {
  console.log('IIFE');
})(); // 2번

1번처럼 함수를 선언하고 hello(); 함수를 호출하는 방식을 원래 사용했지만
함수를 ()로 감싸고, 끝에 함수를 호출 하듯이 ()를 적어주면 바로 함수가 호출

class

Class declarations

class Person {
  // constructor
  constructor(name, age) {
    // field
    this.name = name;
    this.age = age;
  }

  // methods
  speak() {
    console.log(`${this.name}: hello!`);
  }
}

class라는 키워드를 이용해서 클래스를 생성

// 오브젝트 생성
const ellie = new Person('ellie', 20);
console.log(ellie);
console.log(ellie.name);
console.log(ellie.age);
ellie.speak();

새로운 오브젝트를 만들 때 키워드 new

Getter and Setters

class Emp{
    constructor(name, age, job){
        this.name = name;
        this.age = age;
        this.job = job;
    }

    get age(){
        return this._age;
    }

    set age(value){
        this._age = value < 0 ? 0 : value;
    }
}

const emp1 = new Emp('', -100, 'frontend developer');
console.log(`${emp1.name}(${emp1.age}) is ${emp1.job}`);

Fields

class Experiment {
  publicField = 2;
  #privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField); // 2
console.log(experiment.privateField); // undefined

object

const obj1 = {}; // 1. 'object literal' syntax
const obj2 = new Object(); // 2. 'object constructor' syntax

Computed properties
object 안의 값을 접근

console.log(me.job);

// Computed properties
console.log(me['name']); // key는 string type으로 지정해야됨

Property value shorthand

function makePerson(name, age) {
     return {
         name, // name: name
         age // age: age
     };
 }

Constructor Function

 function Person(name, age) {
     this.name = name;
     this.age = age;
 }

in operator
object안에 key가 있는지 없는지 확인

console.log('name' in '');

json

object to json

let json = JSON.stringify(true);
console.log(json);

json = JSON.stringify("apple")
console.log(json);

json = JSON.stringify(123)
console.log(json);

json to object

const rabbit = {
    name: 'tory',
    color: 'white',
    size: null,
    birthDate: new Date(),
    jump: () => {
        console.log(`${this.name} can jump!`)
    },
    symbol: Symbol('id')
}
json = JSON.stringify(rabbit);
console.log(json)

callback

console.log('1');
setTimeout(() => console.log('2'), 1000); //비동기적 실행 1초 후 실행됨
console.log('3');
//1, 3, 2 순서대로 출력

promise

const Promise = new Promise((resolve, reject) => {
    // doing some heavy work(network, read files)})
profile
기획과 개발을 배워요.

0개의 댓글

관련 채용 정보