티스토리 뷰

728x90
반응형
Javascript 기본

Javascript 기본

예전에 udemy 에서 한입 크기로 잘라 먹는 리엑트 라는 강의를 수강하게 되었는데, 최근 블로그 챌린지를 한다하여 복습 겸 다시 정리해보고자 합니다.

수업 스타일이 굉장히 재밌고 요약이 잘되어있어서 나중에 다시봐도 이해가 잘되도록 구성이 되어 있습니다.

javascript 에 대해 처음 접하는 분이나 복습 차원에서 가볍게 들으실 분들에게 추천드리고 설명이 쉽기 때문에 react 입문자들에게도 추천 드립니다. 강의는
강의 보러 가기
여기서 보실 수 있습니다.

Javascript 기본

Javascript 란 무엇인가?

  • HTML 과 CSS 로 만들어진 웹페이지를 동적으로 변경해주는 언어

Javascript 엔진

  • 개발자가 작성한 Javascript 코드를 해석하고 실행 시켜주는 프로그램 또는 인터프리터
  • 표준적인 인터프리터로 구현이 되거나, 자바스크립트 코드로 컴파일 하는 JIT 컴파일러로 구현 될 수도 있지만, 주로 웹 브라우저를 위해 사용된다.
  • 가장 잘 알려진 것은 구글 크롬의 V8 엔진 이다.
V8 엔진
- 오픈 소스 자바스크립트 엔진 중 하나, 웹어셈블리(WebAssembly) 엔진
- 하나의 힙 과 하나의 콜 스택만 존재
- 크롬 웹 브라우저, Node.js 등 에서 사용

변수와 상수

변수

  • 프로그램 실행 도중 계속해서 바뀔 수 있는 이름 붙은 저장소
  • 하나의 값을 저장 하기 위해 확보된 메모리 공간 자체 / 변할 수 있는 데이터

변수명

  • 메모리 공간을 식별하기 위한 식별자
var developer; // 식별자가 'developer' 인 변할 수 잇는 데이터를 만든다.

변수명 규칙

  1. ‘_’ 와 ‘$’ 를 제외한 특수문자 사용 불가
let &*age = 25; //error
let _$age = 25;
  1. 숫자로 시작하는 변수명 사용 불가
let 2age = 25; //error
let age2 = 25;
  1. 예약어 사용 불가
//변수명은 예약어로 사용 불가
let if = 25; //error

상수

  • const 사용
  • 선언 이후 값을 바꿀 수 없음 (read only)
const age = 25;

자료형과 형 변환

자료형

  1. Primitive Data Type (원시 타입)
    • Number
      let age = 25; //정수
      let tall = 175.9; //실수
      let inf = Infinity;
      let minusInf = -Infinity;
      let nan = Nan; //수학적 연산의 실패
    • String
      let name = "winterlood"; //큰 따음표
      let name2 = '이정환'; // 작은 따음표
      let name3 = `winterlood ${name2}`; //backtick
    • Boolean
      let isSwitchOff = false;
    • Undefined
      let a;
      console.log(a); //undefined
    • Null
      let a = null;
      console.log(a); //null
  1. Non-Primitive Data Type (비 원시 타입)
    • Object
    • Array
    • Function

형 변환

let numberA = 12;
let numberB = "2";

numberA * numberB; // 24 (묵시적 형변환)
numberA + numberB; // 122
numberA + parseInt(numberB); // 24 (명시적 형변환)

연산자

대입 연산자

let a = 1; // 대입 연산자

산술 연산자

console.log(a + b); 
console.log(a * b);
console.log(a - b);
console.log(a / b);
console.log(a % b); // 나머지

연결 연산자

let a = "1";
let b = "2"; // 숫자형이어도 묵시적 형변환으로 12 출력

console.log(a + b); // "12"

복합 연산자

let a = 5;
a += 10; // a = a + 10

console.log(a); // 15

증감 연산자

let a = 10;

console.log(a++); // 후위 연산자 10
console.log(a); // 11

let b = 10;
console.log(++b); // 전위 연산자 11
console.log(b); // 11

논리 연산자

console.log(!true); // false
console.log(true && true); // true
console.log(true && false); // false
console.log(true || false); // true
console.log(true || true); // true
console.log(false || false); // false

비교 연산자

let compareA = 1 == "1";
console.log(compareA); // true
let compareB = 1 === "1";
console.log(compareB); // false
let compareC = 1 != "1";
console.log(compareC); // false
let compareD = 1 !== "1";
console.log(compareD); // true

//> >= < <=

typeof 연산자

//변수의 자료형 출력
let compareA = 1; 
console.log(typeof compareA); // number
compareA = "1";
console.log(typeof compareA); // string

null 병합 연산자

let a;
a = a ?? 10; // a 가 null 도 아니고 undefined 도 아닐경우 10
console.log(a); // 10

조건문

if

let a = 5;

if(a >= 7){
	console.log("5 이상 입니다.");
}else if(a >= 5){
	console.log("5 이상 입니다.");
}else{
	console.log("5 미만 입니다.");
}

switch

let country = "ko";
switch(country){
	case "ko":
		console.log("한국");
	break;
	case "ch":
		console.log("중국");
	break;
	case "jp":
		console.log("일본");
	break;
	default:
		console.log("미 분류");
	break;
}

함수

함수 선언식

//함수 선언식, 함수 선언 방식의 함수 생성
//호이스팅
function getArea(width, height){
	let area = width * height;
	return area;
}  

let area1 = getArea(100, 200);
console.log('area1 : ', area1);

함수 표현식

//호이스팅 X
let hello = function (){
	return '안녕하세요';
}

const helloText = hello();
console.log(helloText);

화살표 함수

//호이스팅 X
let hello = () => '안녕하세요';

콜백 함수

function checkMood (mood, goodCallback, badCallback){
	if(mood === 'good') {
		goodCallback();
	}else {
		badCallback();
	}
}

function cry() {
	console.log('ACTION :: CRY');
}

function sing() {
	console.log('ACTION :: SING');
}

function dance() {
	console.log('ACTION :: DANCE');
}

checkMood('sad', sing, cry);

객체

객체 생성

let person = new Object(); // 생성자
let person = {}; // 객체 리터럴
let person2 = {
	key: 'value', //key, value로 값을 저장
	key1: 'value2',
	key2: true,
	key3: undefined,
	key4: [1, 2],
	key5: function () {}
};

객체 접근

let person = {
	name: 'jin',
	age: 25
}
console.log(person.name); // 점 표기법
console.log(person['age']); // 괄호 표기법

객체 삽입/수정/삭제

let person = {
	name: 'jin',
	age: 25
}

// 삽입
person.location = '한국'; // or person['location'] = '한국'
// 수정
person.name = 'jins'; // or person['name'] = 'jins'
// 삭제
delete person.age; // or delete person['age']
person.name = null; //메모리에서 삭제 (추천)

객체 메서드 사용

let person = {
	name: 'jin',
	say: function() {
		console.log("안녕 나는 ${this['name']}");
	}
}

person["say"]();

undefined 확인

const person = {
	name: 'jin',
	age: 25,
}

console.log(person.gender); // undefined
console.log(`name : ${"name" in person}`); // true
console.log(`age : ${"age" in person}`); // true
console.log(`gender : ${"gender" in person}`); // false

배열

배열 생성

//배열 리터럴
let arr = [1, "2", true, null, undefined, {}, [], function() {}]; // 자료형 상관 X

배열 접근

let arr = [1, 2, 3, 4, 5];
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);

배열 삽입

let arr = [1, 2, 3, 4, 5];
arr.push(6);

반복문

for

for(let i = 1; i <= 100; i++){ // 초기식; 조건식; 증감식
	console.log('winterlood');
}

//배열 순회
const arr = ["a", "b", "c"];

for(let i = 0; i < arr.length; i++) {
	//반복 수행할 명칭
	console.log(arr[i]);
}

//객체 순회
let person = {
	name: 'jin',
	age: 25,
}

const personKeys = Object.keys(person);
for(let i=0; i<personKeys.length; i++){
	const curKey = personKeys[i];
	const curValue = person[curKey];

	console.log(`${curKey} : ${curValue}`);
}

배열 내장 함수

forEach

const arr = [1, 2, 3, 4];
arr.forEach((elm)=>console.log(elm));

map

const arr = [1, 2, 3, 4];
const newArr = arr.map((elm) => elm * 2);

includes

const arr = [1, 2, 3, 4];
let number = 3;

console.log(arr.includes(number)); // number 존재 여부 확인

indexOf

const arr = [1, 2, 3, 4];
let number = 3;

console.log(arr.indexOf(number)); // 2 배열의 index 반환 

findIndex

const arr = [
	{ color: 'red' },
	{ color: 'black' },
	{ color: 'blue' },
	{ color: 'green' },
];
let number = 3;

arr.findIndex((elm) => elm.color === 'red'); //callBack 함수가 true를 반환 하는 첫번째 index

find

const arr = [
	{ color: 'red' },
	{ color: 'black' },
	{ color: 'blue' },
	{ color: 'green' },
];
let number = 3;

arr.find((elm) => elm.color === 'red'); //callBack 함수가 true를 반환 하는 첫번째 요소

filter

const arr = [
	{ num: 1, color: 'red' },
	{ num: 2, color: 'black' },
	{ num: 3, color: 'blue' },
	{ num: 4, color: 'green' },
	{ num: 5, color: 'blue' },
];

arr.filter((elm) => elm.color === 'blue');

slice

const arr = [
	{ num: 1, color: 'red' },
	{ num: 2, color: 'black' },
	{ num: 3, color: 'blue' },
	{ num: 4, color: 'green' },
	{ num: 5, color: 'blue' },
];

arr.slice(0, 4); // index가 0 ~ 3 인 요소 반환

concat

const arr1 = [
	{ num: 1, color: 'red' },
	{ num: 2, color: 'black' },
	{ num: 3, color: 'blue' },
]

const arr2 = [
	{ num: 4, color: 'green' },
	{ num: 5, color: 'blue' },
]

arr1.concat(arr2); // 하나의 배열로 return 

sort

let chars = ['나', '다', '가'];
chars.sort(); // 원본 배열 정렬 (문자열, 사전순 으로 정렬)

let numbers = [0, 1, 3, 2, 10, 30, 20];
const compare = (a, b) => {
	if(a>b){
		return 1;
	}
	if(a<b){
		return - 1;
	}
	return 0;
}
numbers.sort(compare);

join

const arr = ['안녕', '하세요', '또', '오셨군요');

arr.join();
arr.join('_');
arr.join('===');
728x90
댓글
반응형
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2026/01   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함