React 기초반 수업을 들으면서 JavaScript 기초 지식 부족에 대한 아쉬움이 커졌다. 간단한 예시를 든 설명을 듣더라도 JavaScript에 대한 감이 전혀 없는 상태다 보니 쉬운 설명도 어렵게 느껴지기 일쑤였다. 그래서 시작한 JavaScript와 친해지기 단기 속성 이벤트(?)! 강의 듣기 바쁜 지금이지만 하루라도 짬내서 듣고 싶은 욕심이 더 컸다. 😅 오늘 TIL에서는 짧게나마 JavaScript에 대해 공부하며 알게 된 것들을 복습해보려 한다!

👀 새벽수영의 JavaScript 입문기

"JavaScript" 누구냐 넌?

1993년, Marc Andreessen에 의해 Mosaic Web Browser라는 웹브라우저가 처음 등장하게 된다. 모자이크는 컴퓨터를 잘 다루지 못하는 사람들도 쉽게 사용 가능하도록 UI 요소가 더해진 브라우저였는데, 마크 앤드리슨은 대학교를 졸업 후 Netscape라는 회사를 설립, 모자이크 브라우저를 기반으로 UI 요소가 조금 더 보완된 웹브라우저인 Netscape Navigator를 출시한다. 당시에는 HTML과 CSS를 이용해 간단한 형태의 웹페이지를 만들 수 있었는데, Netscape Navigator는 HTML 페이지 간의 이동만 가능한 매우 정적인 브라우징만 가능했다.

사용자들에게 동적인 웹사이트 경험을 보여주고 싶었던 마크 앤드리슨은 Scripting 언어를 추가하기로 결심한다. 이에 그는 Scheme Script의 제작자 Brendan Eich와 합작하여 스킴 스크립트를 기반, Java의 특징을 지닌 새로운 Scripting 언어 "LiveScript"를 개발한다. 당시 Java 언어의 인기에 편승하여 LiveScript의 인기를 얻고자 했던 마크와 브랜든은 LiveScript의 이름을 JavaScript로 변경했고, 이것이 우리가 지금껏 사용하고 있는 JavaScript의 시작이 된다.

Variables (변수)

let_ 🆚 var (feat. hoisting)

"Mutable DataType" - 값이 계속 변경될 수 있다!
"read / write" - 메모리에 읽고/쓰기 가능

var는 더 이상 사용하지 않는다!

  • hoisting(호이스팅) :어디에 선언했는지와 상관없이 선언을 항상 제일 위로 끌어올려주는 것
    보통 let으로 변수를 선언할 때, 변수의 이름을 먼저 선언한 후 값을 할당한다. 그런데 var는 선언하기 이전에 값을 할당할 수가 있다. 심지어 값을 할당하기도 전에 출력까지 할 수 있다(당연히 값은 undefine으로 출력). 이런 현상을 var hoisting 이라고 하는데, 이 같은 이유로 var를 이용하면 오류가 생길 여지가 많다.
  • block scope을 무시한다.

예전에는 위와 같은 유연성을 이용하여 프로그램을 대충 간단하게 만들었지만, 규모가 있는 서비스에서는 위와 같은 이유로 의도하지 않은 값이 할당되는 등의 예기치 못한 오류들이 생길 수 있기 때문에 더 이상 var를 사용하지 않는다.

변수를 선언할 때는 let을 사용!

Variable types

  • primitive, single item: number, string, boolean, null, undefined, symbol
    값(value) 자체가 메모리에 저장
  • object, box container
    값이 너무 크기 때문에 값이 저장된 곳의 참조(reference)가 메모리에 저장

Constant (상수)

const

"Immutable DataType" - 값이 변경될 수 없다!
"read only" - 읽기 전용

Immutable data types: primitive types, frozen objects (i.e. object.freeze())
Mutable data types: all objects by default are mutable in JS

Favor immutable data type always for a few reasons...

  • security
  • thread safety
  • reduce human mistakes

Operator (연산자)

String concatenation (문자열 병합)

console.log('1' + 2); // 12
console.log(`string literals: 1 + 2 = ${1 + 2}`);
	// string literals: 1 + 2 = 3
console.log('shawn's book'); // 안 나옴
console.log('shawn\'s book'); // shawn's book
	// 중간에 \(backSlash)를 넣어줘야 한다.

줄 바꿈: \n
tab: \t

Numeric (숫자 연산자)

// 2. Numeric operators
console.log(1 + 1); // add
console.log(1 - 1); // substract
console.log(1 / 1); // divide
console.log(1 * 1); // multiply
console.log(5 % 2); // remainder
console.log(2 ** 3); // exponentiation

Increment and decrement (증감 연산자)

// 3. Increment and decrement operators
let counter = 2;

const preIncrement = ++counter;
// counter = counter + 1;
// preIncrement = counter;
console.log(`preIncrement: ${preIncrement}, counter: ${counter}`);
// preIncrement: 3, counter: 3

const postIncrement = counter++;
// postIncrement = counter;
// counter = counter + 1;
console.log(`postIncrement: ${postIncrement}, counter: ${counter}`);
// postIncrement: 3, counter: 4

const preDecrement = --counter;
console.log(`preDecrement: ${preDecrement}, counter: ${counter}`);
// preDecrement: 3, counter: 3

const postDecrement = counter--;
console.log(`postDecrement: ${postDecrement}, counter: ${counter}`);
// postDecrement: 3, counter: 2

Assignment (할당 연산자)

// 4. Assignment operators
let x = 3;
let y = 6;
x += y; // x = x + y;
x -= y;
x *= y;
x /= y;

Comparison (비교 연산자)

// 5. Comparison operators
console.log(10 < 6); // less than
console.log(10 <= 6); // less than or equal
console.log(10 > 6); // greater than
console.log(10 >= 6); // greater than or equal

Logical (논리 연산자)

||(or) 연산자는 value나 expressions 중에 하나라도 true면 true를 return한다. || 연산자는 처음으로 true를 마주하는 순간 멈추고 true를 리턴한다. 그러므로 비교적 간단한 value들이 먼저 앞에 오고, 아래의 check()와 같은 연산이 많고 무거운 함수, 또는 표현식(expression) 같은 것들은 되도록 맨 마지막에 위치하게 만드는 것이 바람직하다. (&&(and) 연산자도 마찬가지!)

// 6. Logical operators: || (or), && (and), ! (not)
const value1 = true;
const value2 = 4 < 2;

// || (or), finds the first truthy value
console.log(`or: ${value1 || value2 || check()}`);

// && (and), finds the first falsy value
console.log(`and: ${value1 && value2 && check()}`);

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

// ! (not) // 값을 반대로 바꿔준다.
console.log(!value1); // false

&& 는 간단한 null check 같은 것을 할 때도 자주 쓰인다.

// often used to compress long if-statement
// nullableObject && nullableObject.something
if (nullableObject != null) {
	nullableObject.something;
}

Equality (동등 연산자)

// 7. Equality
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
// object는 값이 저장된 주소(reference)를 저장
const ellie1 = { name: 'ellie' };
const ellie2 = { name: 'ellie' };
const ellie3 = ellie1;
console.log(ellie1 == ellie2); // false
console.log(ellie1 === ellie2); // false
console.log(ellie1 === ellie3); // true

// equality - puzzler
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

Conditional operators (조건 연산자): if 문

// 8. Conditional operators: if
// if, else if, else
const name = 'df';
if (name === 'ellie') {
  console.log('Welcome, Ellie!');
} else if (name === 'coder') {
  console.log('You are amazing coder');
} else {
  console.log('unknown');
}
// unknown

Ternary operators (삼항 연산자)

? 왼쪽의 식이 true일 때는 :를 기준으로 왼쪽의 값을 출력, 아니라면 오른쪽의 값을 출력한다. 형식이 길어지면 가독성이 떨어지기 때문에 간단한 형식의 문장일 때만 사용하는 것을 추천한다.

// 9. Ternary operator: ?
// condition ? value1 : value2;
console.log(name === 'ellie' ? 'yes' : 'no');
// 위에서 이름이 df로 되어있기 때문에 no가 출력

Switch statement (Switch 문)

if / else if / else 가 반복되는 상황에는 switch 문의 사용을 고려해보는 것이 좋다.

// 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('love you!');
    break;
  default:
    console.log('same all!');
    break;
}

Loops (반복문)

while
// while loop, while the condition is truthy,
// body code is executed.
let i = 3;
while (i > 0) {
  console.log(`while: ${i}`);
  i--;
}
do while
// do while loop, body code is executed first,
// then check the condition.
do {
  console.log(`do while: ${i}`);
  i--;
} while (i > 0);
for
// for loop, for(begin; condition; step)
for (i = 3; i > 0; i--) {
  console.log(`for: ${i}`);
}

for (let i = 3; i > 0; i = i - 2) {
  // inline variable declaration
  console.log(`inline variable for: ${i}`);
}
nested loops
// nested loops
for (let i = 0; i < 10; i++) {
  for (let j = 0; j < 10; j++) {
    console.log(`i: ${i}, j:${j}`);
  }
}
quiz
// break, continue
// Q1. iterate from 0 to 10 and print only even numbers (use continue)
for (let i = 0; i < 11; i++) {
  if (i % 2 !== 0) {
    continue;
  }
  console.log(`q1. ${i}`);
}

for (let i = 0; i < 11; i++) {
  if (i % 2 === 0) {
    console.log(`q1. ${i}`);
  }
}

// Q2. iterate from 0 to 10 and print numbers until reaching 8 (use break)
for (let i = 0; i < 11; i++) {
  if (i > 8) {
    break;
  }
  console.log(`q2. ${i}`);
}
profile
그는 특히 요리 실력을 갖춘 상태에서 다른 사람의 도움을 받아

0개의 댓글