Javascript - 기초개념1

죠랭이·2021년 2월 8일
0

Javascript

목록 보기
1/1
post-thumbnail

[Intro to Javascript]

  • Javascript Engine이라는 웹 브라우저별(V8, Chakra, Spidermonkey, JavaScriptCore 등) 컴파일러가 존재하여 페이지 로딩 혹은 사용자 이벤트 호출 시 실행됨.
  • Javascript debugging을 위해서는 웹 브라우저의 'Inspect Element' 기능을 활용해야 함. 웹 브라우저마다 각각 다른 디버깅 기능을 제공하므로 자신에게 맞는 디버깅 툴을 활용할 수 있는 웹 브라우저로 개발하는 것이 좋음.(Node.js로도 디버깅이 가능하다고 함)
  • 자바스크립트 표준(ECMAScript, 통칭 ES6)에 맞는 문법 활용할 수 있도록 해당 스펙 문서(ECMAScript) 참고 => 더 자세한 경험담은 우아한 형제들 기술블로그에서 확인하기

[Javascript 문법]

  • Javascript의 경우 parseInt(), parseFloat()함수는 String type도 변환이 가능. 단, OOP언어에서 정의하는 메소드와는 기능이 조금 다름

let str_1 = '123Hello';
let str_2 = '12.3Hello';
console.log(parseInt(str_1)); // only the number is extracted(123)
console.log(parseFloat(str_2)); // only the number is extracted(12.3)

console.log('1' === 1); // expected output: false
console.log('1' == 1): // expected output : true

const object1 = {
name: "hello"
}
const object2 = {
name: "hello"
}
console.log(object1 === object2); // false
console.log(object1 === object1); // true

console.log(-11 % 3); // output: -2

console.log(!!'0') //

  • 반복문에서 for(var index in arr), for(var val of arr) 새로운 문법이 등장. 해당 문법 기능은 아래 코드와 같음

var arr = [1, 2, 3, 4, 5];
for (var index in arr) {
console.log(index);
// 배열의 인덱스(0, 1, 2, 3, 4) 출력
}

var arr = [1, 2, 3, 4, 5];
for (var index of arr) {
console.log(index);
// 배열의 값(1, 2, 3, 4, 5) 순차적으로 출력
}

[배열(Array)]

  • 자바스크립트에도 배열의 개념이 존재. 단, 타 언어에서와의 차이점은 자바스크립트 배열은 여러 타입의 변수를 한꺼번에 가지고 있을 수 있음(배열의 배열값을 가지는 것도 가능)

    var arr = [1, 2, 0.3, 4.1, "5", [1,2,3]];
    console.log(arr); // [1, 2, 0.3, 4.1, "5", Array(3)]

  • 배열에서 값을 맨 마지막에 추가하고자 할 적에는 .push(x), 맨 처음에 추가하고자 할 적에는 unshift(x) 명령어를 활용(반대로 맨 마지막 원소를 제거하고자 할 적에는 .pop(), 맨 처음 원소를 제거하고자 할 적에는 .shift() 명령어를 활용)

  • splice(start idx, count, (option)): Add & Remove element(s)

var numbers = [1, 2, 3, 4, 5];
// Removes 2 elements starting from index 0 and adds 2 new elements
numbers.splice(0, 2, "one", "two");
console.log(numbers);
var names = ["John", "Jack"];
//Inserts element(s) at position index
names.splice(0, 0, "Jill", "Jim", "Jacob");
console.log(names);
//removes element(s) at position index, 0 is the index and 2 is the number of items removed
names.splice(0, 2);
console.log(names);

  • every(func): func에 해당하는 모든 조건을 배열에 만족하는지 검사(return value: true/false), some(func): func에 해당하는 조건을 배열의 요소 중에 만족하는게 있는지 검사(return value: true/false)

// MethodsForConditionsExample.js
var arr1 = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
var arr2 = [10, 12, 14, 16, 18, 20];
function isEvenNumber(number) {
return number % 2 == 0;
}
// arrayname.every()
console.log(arr1.every(isEvenNumber));
console.log(arr2.every(isEvenNumber));
// arrayname.some()
console.log(arr1.some(isEvenNumber));
console.log(arr2.some(isEvenNumber));

  • 기타 배열 Object가 가진 여러 함수들

// MethodsForTransformationExample.js
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function isEvenNumber(number) {
return number % 2 == 0;
}
// arrayname.filter(): 매개조건에 맞는 새로운 배열을 return
console.log(arr1.filter(isEvenNumber)); // Extract the even numbers from the array
// arrayname.reduce(): 0(initial)부터 시작하여 function에 맞는 값을 return
var sum = arr1.reduce(function (sum, number) { // Calculates the sum of the numbers
return sum + number;
}, 0);
console.log(sum) // 55
// arrayname.map(): 주어진 배열과 동일한 사이트이면서 function 조건을 만족시키는 새로운 배열을 return
var squares = arr1.map(function (number) { // Calculates the squares of the numbers
return number * number;
});
console.log(squares); // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

  • 배열에서 for-in, for-of 명령어와 유사하게 기능하는 함수

// Print the elements of an array with their index
var numbers = ['One', 'Two', 'Three', 'Four', 'Five'];
numbers.forEach(function(item, index) {
console.log('Item at index ' + index + ' has the value ' + item);
});
// "Item at index 0 has the value One"
// "Item at index 1 has the value Two"
// "Item at index 2 has the value Three"
// "Item at index 3 has the value Four"
// "Item at index 4 has the value Five"

[Hoisting이란?]

  • JavaScript에서 실제로 어떻게 코드가 동작하는지에 대한 일반적인 컨텍스트(생성 및 실행 단계) 이해라고 보면 됨
  • Java, C++ 언어의 경우 변수 혹은 함수 활용을 위해선 반드시 변수 선언이 먼저 이루어져야 함.

Java, C++
int test;
test = 0;

  • JavaScript의 경우 함수 혹은 변수 선언이 컨텍스트상 나중에 등장하더라도 초기화만 되어있으면에러가 발생하지않고 실행됨

function catName(name) {
console.log("My cat's name is " + name);
}
catName("Tigger");
// 위 코드의 결과는: "My cat's name is Tigger"

catName("Chloe");
function catName(name) {
console.log("My cat's name is " + name);
}
// 위 코드의 결과는: "My cat's name is Chloe"

  • 변수 타입에도 함수와 마찬가지로 동작함. 다음 예제 코드를 참조하자.

num = 0;
num += 7;
console.log(num);
// 에러없이 실행되는 코드

[Symbol타입]

  • ES6부터 새롭게 등장하기 시작한 원시 타입(primitive type). null, undefined, number, string, boolean 다음으로 추가됨. 이외의 타입은 모두 Object
  • new 생성자로 생성할 수 없고 Symbol() 함수로 생성해야 함
  • 중복 값의 충돌의 걱정 없이 객체 프로퍼티 키로 사용 가능한 '유일한' 값

[값-복사 VS 레퍼런스-복사]

  • 원시 타입에 의한 변수는 값-복사(Copy-Value), 그 외의 객체 타입에는 레퍼런스-복사(Copy-Reference)가 일어남
  • 자바스크립트에서는 포인터의 개념이 없음. 따라서, 여기서 말하는 레퍼런스-복사란 여러 변수가 하나의 '공유된' 값을 사용한다는 의미

var a = 2;
var b = a;
b++;
console.log(a); // a = 2
console.log(b); // b = 3 (값-복사)
var a = [1,2,3,4];
var b = a;
a.push(5);
console.log(a); // a = [1,2,3,4,5]
console.log(b); // b = [1,2,3,4,5]

  • 자바스크립트는 데이터 타입을 보고 값-복사, 레퍼런스-복사를 결정. 또한, 하나의 공유된 값만을 레퍼런스-복사함

var a = [1,2,3,4];
var b = a;
b = [5,6,7];
a.push(5);
console.log(a); // a = [1,2,3,4,5]
console.log(b); // b = [5,6,7]

  • 함수도 변수와 유사하나 아래의 경우 헷갈릴 때가 많음

function foo(x) {
x.push(5);
console.log(x); // x = [1,2,3,5]
x = [5,6,7];
x.push(8);
console.log(x); // x = [5,6,7,8]
}
var a = [1,2,3];
foo(a);
console.log(a); // a = [1,2,3,5]

  • 따라서, 매개변수로 받고 있는 객체 a를 변경하고 싶을 적에는 다음과 같이 바꿔줘야 함

function foo(x) {
x.push(5);
console.log(x); // x = [1,2,3,5]
x.length = 0;
x.push(5,6,7,8);
console.log(x); // x = [5,6,7,8]
}
var a = [1,2,3];
foo(a);
console.log(a); // a = [5,6,7,8]

  • 대부분의 래퍼(Wrapper) 객체가 가지고 있는 스칼라 원시 값들은 레퍼런스 복사로 바꿀 수 있지만 Number와 같은 스칼라 원시 값 객체 클래스의 경우 값-복사밖에 일어나지 않음

var a = 2;
var b = Number(a);
var c = new Number(a);
console.log(typeof b); // number
console.log(typeof c); // object
function foo(x) {
x += 1;
}
foo(b);
foo(c);
console.log(b); // b = 2
console.log(c); // c = 2

참고자료(출처): EXLSkills 공식 홈페이지, [MDN Web Docs](https://developer.mozilla.org/ko/docs/Glossary/Hoisting)
You don't know JS(도서)
profile
슈퍼 개발자를 목표로 하는 주니어

0개의 댓글