JS1

KwangYong·2021년 12월 12일
0

JavaScript

목록 보기
1/3

👍 JS 공식 사이트: https://developer.mozilla.org/ko/

👨🏻‍🏫 script async 와 defer의 차이점

source : 드림코딩 js기초 2

🧷 async

head+async: async는 boolean타입의 속성값이기때문에 선언하는 것만으로 true로 실행이 된다.
html pasing중에 async가 있으면 병렬로 js를 다운을 받도록 명령을 하고 다시 html pasing을 하다가 js다운이 끝나면 pasing을 멈추고 js를 실행시킨다. 실행이 끝난 뒤 다시 나머지 html을 parsing한다.
장점: js다운로드가 병렬적으로 이루어지기 때문에 시간 절약.
단점: 하지만 html parsing이 끝나기 전에 js 실행이 되기 때문에 그 시점에 우리가 원하는 요소가 아직 정의되어있지 않을 수 있다. 또한 js실행할 때 멈추기 때문에 여전히 사용자가 페이지를 보는데 시간이 소요된다. 또한 정의된 순서와 상관없이 먼저 다운로드된 js를 실행시키기 때문에 문제가 발생 할 수 있다.

🧷 defer

head + defer : defer을 만나면 js다운 명령만 시켜두고 나머지 html을 모두 parsing하게 된다. 그리고 parsing이 모두 끝난 마지막에 다운되어진 js를 실행시킨다. 따라서 정의된 순서대로 js가 실행된다.

따라서 head안에 defer옵션이 가장 효율적이다.

순수 바닐라js를 쓸 땐 맨위에 'use strict';를 적어주자. flexible === dangerous. 상식적인 개발이 가능하다.

👨🏻‍🏫 data types, let vs var, hoisting

source : 드림코딩 js기초 3

1. use strict

2. variable, rw(read/write)

let(added in ES6)
js에서 변수를 선언할 수 있는 키워드는 mutable type의 let, immutable type의 const.

var는 쓰지말자(don't even use this!)
var hoisting(move declaration from bottom to top)
선언도 하기 전에 값을 할당하고 심지어 값을 할당하기 전에도 출력할 수 있다.
hoistiong(끌어올려주다) : 어디에서 선언했는지에 상관없이 선언을 제일 위로 끌어 올려주는것을 의미한다.

블럭 밖에 쓰면 전역변수다. 블럭을 사용하면 블럭 밖에서는 더 이상 블럭 안을 볼 수 없다. 하지만 var는 블럭 scope이 없다. 철저히 무시한다. (has no block scope)

let globalName = 'global name'
{
    let myname = 'kwang'; 
    console.log(myname);
    myname = 'yong';
    console.log(myname);
}

3. constant, r(read only)

변경 할 수 없는 immutable type 변수
use const whenever possible.
favor immutable data type always for a few reason:
-security
-thread safety
-reduce human mistake

const daysInweek = 7;

⭐Note!

  • Immutable data types: primitive types, frozen Objects(i.e. object.frozen())
    데어터 자체를 절대 변경 못함. primitive type의 경우, ellie라는 string을 통채로 메모리에 올렸다가 다른 스트링으로 변경이 가능하지만 ellie 데이터 자체를 수정할 순 없다.
  • Mutable datatypes: all objects by default are mutable in JS
    ellie라는 object 선언하고 ellie안에 있는 name, age를 계속 변경가능.

4. Variable types

  • primitive, single item(더 이상 작은 단위로 나눠질 수 없는 한가지 item)
    : number, string, boolean, null, undefined, symbol
  • object(single item들을 한 단위로 한 박스로 묶어서 관리)
  • function : js에서는 function도 데이터 타입 중에 하나
    first-class function: function도 다른 데이터 타입처럼 변수에 할당이 가능하고 또 그렇기 때문에 함수의 파라미터 인자로도 전달 되고 함수의 리턴타입으로도 function을 리턴할 수 있다.

메모리에 값이 저장되는 방법은 2가지 -> primitive, object
📌 primitive: value값 자체가 메모리에 저장됨.
📌 object: object를 가리키는 reference가 메모리에 저장된다.
너무 커서 한번에 메모리에 다 올라갈 수 없음. const선언으로 object를 할당하게 되면 ellie가 가리키는 곳에는 reference가 있음. 이 ref는 실제로 object를 가리키고 있는 곳이다. 그래서 이 ref를 통해서 실제로 object가 담겨있는 메모리를 가리키게 된다. ellie가 가리키고 있는 포인터만 잠겨서 다른 object로 변경이 불가능하지만 name과 age는 계속 변경이 가능함.

number

다른 언어랑 다르게 얼마나 큰 사이즈를 할당 할 건지 생각할 필요가 전혀 없다. js에서는 타입이 다이나믹하게 결정되기 때문에 let이나 const를 쓰면 된다.

const count = 17; // integer
const size = 18.1; // decimal number
console.log(`value: ${count}, type: ${typeof count}`);
console.log(`value: ${size}, type: ${typeof size}`);

number - special numeric values: infinity, -infinity, NaN

const infinity = 1 / 0;
const negativeInfinity = -1/0;
const nAn = 'not a number' / 2;
console.log(infinity);
console.log(negativeInfinity);
console.log(nAn);

string

js에서는 char이든 string이든 모두 string으로 할당됨.
백틱, 중괄호를 이용해서 변수와 스트링을 쉽게 붙일 수 있다.

const char = 'c';
const brendan = 'brendan';
const greeting = brendan + 'hello';
console.log(`value: ${greeting}, type: ${typeof greeting}`);
const helloBob = `hi ${brendan}!`; //template literals (string)
//백틱 안에 ${}를 이용하면 변수값이 붙여져서 나온다. 
console.log(`value: ${helloBob}, value: ${typeof helloBob}`);

boolean

false: 0, null, undefined, Nan, ''
true: any other value

let nothing = null;
console.log(`value: ${nothing}, type: ${typeof nothing}`);
let x; //undefined
console.log(`value: ${x}, type: ${typeof x}`);

symbol

맵이나 다른 자료구조에서 고유한 식별자가 필요하거나 아니면 동시 다발적으로
일어날 수 있는 코드에서 우선순위를 주고 싶을 때 고유한 식별자를 쓰고 싶을 때 쓰여진다.

symbol은 동일한 string으로 작성했어도 다른 symbol로 만들어지기 때문에 주어진 스트링에 상관없이 고유한 식별자를 만들 때 사용되어진다.
string이 똑같다면 동일한 symbol를 만들고 싶다면 Symbol.for를 이용한다.
symbol은 바로 출력을 하게 되면 오류가 발생하기 때문에 .description을 이용해서 string으로 변환해서 출력해야한다.

const symbol1 = Symbol('id');
const symbol2 = Symbol('id');
console.log(symbol1 === symbol2); // false
const gSymbol1 = Symbol.for('id');
const gSymbol2 = Symbol.for('id');
console.log(gSymbol1 === gSymbol2); // true
console.log(`value : ${symbol1.description}, type: ${typeof symbol1}`);

Object, real-life object, data structure

const ellie = {name: 'ellie', age: 20};
ellie.age= 21;

지금 ellie는 const로 지정됐기때문에 다른 object로 변경이 불가.
ellie가 가리키고 있는 포인터는 잠겨있어서 다른 object로 할당이 불가하지만
object 안의 name과 age가 가리키고 있는 메모리는 다른 값으로 할당이 가능하다.

5. Dynamic typing : dynamically typed language

js는 선언할 때 어떤 타입인지 선언하지 않고 런타임 프로그램이 동작할 때
할당된 값에 따라서 타입이 변경될 수 있다.

let text = 'hello';
console.log(text.charAt(0));
console.log(`value ${text}, type: ${typeof text}`);
text = 1;
console.log(`value ${text}, type: ${typeof text}`);
text = '7' + 5 ;
console.log(`value ${text}, type: ${typeof text}`);
text = '8' / '2';
console.log(`value ${text}, type: ${typeof text}`);

따라서 js는 런타임에서 타입이 정해지기 때문에 런타임 에러가 자주 발생.
그래서 js위에 타입이 올려진 타입스크립트가 나옴.
js는 바로 브라우저가 이해할 수 있기 때문에 실시간으로 연동해서 볼 수 있지만
TS는 브라우저가 이해할 수 있도록 트랜스 컴파일러(BABEL)을 이용해야한다

👨🏻‍🏫 operator, if, for loop

source : 드림코딩 js기초4

//1. string concatenation
console.log('my' + 'cat');
console.log(`string literals: 1+2 

''''
= ${1 + 2}`);
//백틱 안의 $을 이용해서 변수 값을 계산해서 스트링으로 포함해서 문자를 생성.
//string literals 장점: 줄바꿈을 하거나, 특수기호가 그대로 출력.

// 2. numaric operators
console.log(2 ** 3);// 2^3

//3. Increment and decrement operators
let counter = 2 ;
const preIncrement = ++counter;
const postIncrement = counter++;

//4. Assignment operators
let x = 3;

//5. comparison operators

//6. logical operation: || , &&, !
//연산을 많이 하거나 express하는 조건을 가장 마지막에 둔다.
const value1 = false;
const value2 = 5< 2 ; 
console.log(`or: ${value1 || value2 || check()}`);

function check(){
    for(let i = 0 ; i < 10; i++){
        //wasting time
        console.log('😨');
    }
    return true;
}

//often used to compress long if-statement
//nullableObject && nullableObject.somthing

// 7. equility
const stringFive = '5';
const numberFive = 5;
//== loose equality, with type conversion 
//타입 상관없이 내용만 같은지 비교
console.log(stringFive == numberFive); //true
console.log(stringFive != numberFive); //false
//=== strict equality, no type conversion
//타입과 내용 모두 비교
console.log(stringFive === numberFive); //false
console.log(stringFive !== numberFive); //true
//object equality by reference
const ellie1 = {name: 'ellie'};
const ellie2 = {name: 'ellie'};
const ellie3 = ellie1;
console.log(ellie1 == ellie2);//false
//1과 2에는 각각 다른 레퍼런스가 저장되어 있기 때문에 다르다.
console.log(ellie1 === ellie2);//false
console.log(ellie1 === ellie3);//true
//3는 1과 같은 레퍼런스를 할당했기 때문에 true

console.log(0 == false); //true
console.log(0 === false); //false
console.log('' == false); //true
console.log('' === false); //false
console.log(null == undefined); //true
console.log(null === undefined); //false

//8. conditional operator: if, else if, else

//9. Ternary operator: ?
//condition ? value1 : value2;
const mname = 'coder';
console.log(mname === 'ellie' ? 'yes' : 'no');

//10. switch statement
//use for multiple if checks
//use for enum-like value check
//use for multiple type checks in TS
const browser = 'IE';
switch(browser) {
    case 'IE' :
        console.log('go away!');
        break;
    case 'Chrome':
    case 'Firefox':
        console.log('I love you!');
        break;
    default:
        console.log('default');
        break;
}

//11. Loops
//while loop, while the condition is truthy,
// body code is executed.

// do while loop, body code is executed first,
// then check the condition.

// for loop, for (begin; condition; step)

👨🏻‍🏫 function 함수의 선언과 표현

source : 드림코딩 js기초5

function
-fundamental building block in the program
-subprogram can be used multiple times
-performs a task or calculates a value

1. Fuction declaration

function name(param1, param2) {body... return;}
one function === one thing
naming: doSomething, command, verb
function is object in JS!
object로 간주되어지기 때문에 이 function을 변수에 할당이 되고, 파라미터로 전달되고, 함수의 리턴값으로 사용할 수 있다.

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

function log(message){
    console.log(message);
}
log('hello@');

js에는 타입이 없기 때문에 함수 인터페이스만 봤을 때 어떤 타입을 전달해야하는지 명확하지 않다. 타입스크립트에서는 파라미터나 리턴의 타입을 명시하도록 되어있다.

2. Parmeters

-primitive parameters: passed by value
-object parameters: passed by reference

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

object는 ref로 전달되기 때문에 함수 안에서 object의 값을 변경하게 되면 그 변경된 사항이 그대로 메모리에 적용이 된다.

3. Default parameters (added in ES6)

파라미터 옆에 default값을 지정해놓으면 사용자가 파라미터를 전달하지 않을 경우, defualt값이 사용된다.

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

4. Rest parameters(add in ES6)

파라미터가 배열형태로 전달됨.

function printAll(...args){ //3개의 원소가 있는 배열 형태로 전달받음
    for(let i = 0; i<args.length; i++){
        console.log(args[i]);
    }
    for(const arg of args){
        console.log(arg);
    }
    args.forEach((arg) => console.log(arg));
}
printAll('dream', 'coding', 'ellie');

5. Local scope

밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다.

let globalMessage = 'global';
function printMessage() {
    let message = 'hello';
    console.log(message); // local variable
    console.log(globalMessage);
    function printAnother(){
        console.log(message);
        let childMessage = 'hello';
    }
    //console.log(childMessage); -> 에러발생.
}
printMessage();

6. Return a value

function sum (a , b ){
    return a + b ;
}
const result = sum(1, 2);

7. Early return, early exit

조건이 맞지않을 때는 빨리 리턴을 하고 조건이 맞을때만 로직을 실행.
bad

function upgradeUser(user){
    if(user.point > 10){
        //long upgrade logic...
    }
}

good

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

First-class function
functions are treated like any other variable
can be assigned as a value to variable
con be passed as an argument to other functions.
can be returned by other function

1. Function expression

a function declare can be called earlier than it is define.(hoisted)
a function expression is created when the execution reaches it.

fuction declaration과 function expression의 가장 큰 차이점은 expression은 할당된 다음부터 호출이 가능한 반면에 declaration은 함수가 선언되기 전에도 호출이 가능함(hoisted)

함수를 선언함과 동시에 변수에 할당함.

const print = function(){ //anonymous function
    console.log('print');
};
print(); //함수를 할당한 변수를 함수를 호출하듯이 소괄호를 이용해서 호출한다.
const printAgain = print;
printAgain();
const sumAgain = sum;
console.log(sumAgain(1,3));

2. Callback function using function expression

함수를 인자로 전달해서 해당 함수를 부른다.

function randomQuiz(answer, printYes, printNo){
    if(answer === 'love you'){
        printYes();
    }else {
        printNo();
    }
}
const printYes = function(){
    console.log('yes!');
};

named function : 디버깅할 때 or 재귀에 사용
better debugging in debugger's stack traces
recursions


const printNo = function print(){
    console.log('no!');
}
randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo);

3. Arrow function

always anonymous
function키워드, 블럭, 세미콜론이 없어진다.
Arrow function에서 블럭 없이 한 줄로 가능할 땐 return도 안쓴다.
블럭을 쓸 땐 return 써야됨.

const simplePrint = function(){
    console.log('simplePrint');
};
const simplePrint = () => console.log('simplePrint');
const add = (a, b) => a + b; 
const add = function (a, b) {
    return a + b;
}
const simplePrint = (a, b) => {
    //do something more
    return a*b;
}

4.IIFE: Immediately Invoked Function Expression

선언함과 동시에 호출

(function hello(){
    console.log('IIFE');
})();
profile
바른 자세로 코딩합니다 👦🏻💻

0개의 댓글