14일차 - Javascript 문법(1) 변수

이상민·2024년 8월 13일

TIL

목록 보기
13/48

변수란 ?

  • 모든 프로그래밍 언어는 기억하고 싶은 값을 메모리에 저장하고, 저장된 값을 읽어 들여 재사용 하기 위해 사용 되는 메커니즘

변수의 5가지 주요 개념

변수 이름 : 저장된 값의 고유 이름
변수 값 : 변수에 저장된 값
변수 할당 : 변수에 값을 저장하는 행위
변수 선언 : 변수를 사용하기 위해 컴퓨터에 알리는 행위
변수 참조 : 변수에 할당된 값을 읽어오는 것

변수를 선언할 수 있는 방법에는 크게 3가지로 Var, Let, Const

1. var

var myvar = "hello world";
console.log(myvar);

2. let

let mylet = "hello world 1";
console.log(mylet);

3. const

const myconst = "hello world 2";
console.log(myconst);

데이터 타입

  • 숫자 데이터 타입

    -typeof 라는 연산자를 통해 해당되는 변수의 타입을 알 수 있다!

1. 정수형

let num1 = 10;
console.log(num1);
console.log(typeof num1);

2. 실수형

let num2 = 3.14;
console.log(num2);
console.log(typeof num2);

3. 지수형

let num3 = 2.5e5;
console.log(num3);
console.log(typeof num3);

4. NaN(Not a Number) 숫자가 아님

let num4 = "hello" / 2;
console.log(num4);
console.log(typeof num4);

5. Infinity(무한대)

let num5 = 1 / 0;
console.log(num5);
console.log(typeof num5);

  • 문자 데이터 타입(string)

1. 문자열 길이 확인하기(length)

let str = "hello world!";
console.log(str.length)

2. 문자열 결합하기(concat)

let str1 = "hello,";
let str2 = "world!";
let result = str1.concat(str2)
console.log(result)

3. 문자열 자르기(substr, slice)

let str3 = "Hello, World!";
console.log(str3.substr(7, 5)); //(시작위치, 몇개까지)
console.log(str3.slice(7, 13)); //(시작위치, 끝 위치까지)

4. 문자열 검색(search)

let str4 ="hello, world1";
console.log(str4.search("world")); //7번째 열부터 world단어 시작

5. 문자열 대체("Hello, world!"가 아닌 "Hello, JavaScript!" 바뀌어나오게 하기)

let str5 = "Hello, world!";
let result = str5.replace("world", "JavaScript");
console.log(result); // "Hello, JavaScript!"

5. 문자열 분할(split)

let str = "apple, banana, kiwi";
let result = str.split(",");
console.log(result); // ["apple", " banana", " kiwi"]

불리언(Boolean)

  • 불리언이란 참(true)과 거짓(false)을 나타내는 데이터 타입을 의미
  • 불리언은 조건문(if, else, switch 등)과 논리 연산자(&&, ||, !)와 함께 많이 사용된다.
let bool1 = true;
let bool2 = false;

console.log(bool1); // true
console.log(typeof bool1); // "boolean"
console.log(bool2); // false
console.log(typeof bool2); // "boolean"

  • x에 10의 값을 주고 y에 5의 값을 준뒤 x가y보다 크면 "x is greater than y" 를 출력
    그외에는 "x is less than or equal to y"를 출력하게 해보자
let x = 10;
let y = 5;

if (x > y) {
  console.log("x is greater than y");
} else {
  console.log("x is less than or equal to y");
}

  • undefined

  • undefined는 값이 할당되지 않은 변수를 의미
let x;
console.log(x); //x라는 변수에 아무런 값이 지정되지않음

  • null

  • null은 값이 존재하지 않음을 의미
let y = null;

객체(Object)

  • 자바스크립트에서는 객체가 매우 중요한 역할을 한다. 객체는 속성과 메소드를 가지는 컨테이너로 중괄호({})를 사용하여 객체를 생성한다.
let person = {
    name: 'Lee',
    age: 20
};
console.log(typeof person);

배열(Array)

  • 배열은 여러 개의 데이터를 순서대로 저장하는 데이터 타입으로 대괄호([])를 사용하여 배열을 생성한다.
let numbers = [1, 2, 3, 4, 5];
let fruits = ['apple', 'banana', 'orange'];

형 변환

  • 암시적 형 변환(implicit coercion)

  • 암시적 형 변환은 자바스크립트에서 자동으로 수행되는 형 변환을 의미한다.
//문자열 변환
console.log(1 + "2");   // "12"
console.log("1" + true);   // "1true"
console.log("1" + {});   // "1[object Object]"
console.log("1" + null);   // "1null"
console.log("1" + undefined);   // "1undefined"
//숫자 변환
console.log(1 - "2");   // -1
console.log("2" * "3");   // 6
console.log(4 + +"5");   // 9
// 위의 예제에서는 연산자를 사용할 때, 문자열을 숫자로 변환한다. 
// 이때, 빈 문자열("")이나 공백 문자열(" ")은 0으로 변환
//불리언 변환
console.log(Boolean(0));   // false
console.log(Boolean(""));   // false
console.log(Boolean(null));   // false
// Boolean() 함수를 사용하여 불리언 값으로 변환
  • 명시적 형 변환(explicit coercion)

  • 명시적 형 변환은 개발자가 직접 자료형을 변환하는 것을 의미한다.
//문자열 변환
console.log(String(123));       // "123"
console.log(String(true));      // "true"
console.log(String({}));        // "[object Object]"
// String() 함수를 사용하여 다른 자료형을 문자열로 변환
// 숫자 변환
console.log(Number("123"));   // 123
console.log(Number(""));      // 0
console.log(Number("  "));    // 0
console.log(Number(true));    // 1
console.log(Number(false));   // 0

연산자

  • 산술 연산자(arithmetic operators)

  • 더하기 연산자

console.log(2 + 3);       // 5
console.log("2" + "3");   // "23"
console.log("2" + 3);     // "23"
console.log(2 + "3");     // "23"
  • 빼기 연산자

console.log(5 - 2);       // 3
console.log("5" - "2");   // 3
console.log("5" - 2);     // 3
console.log(5 - "2");     // 3
console.log("five" - 2);  // NaN
  • 곱하기 연산자

console.log(2 * 3);       // 6
console.log("2" * "3");   // 6
console.log("2" * 3);     // 6
console.log(2 * "3");     // 6
console.log("two" * 3);   // NaN
  • 나누가 연산자

console.log(6 / 3);       // 2
console.log("6" / "3");   // 2
console.log("6" / 3);     // 2
console.log(6 / "3");     // 2
console.log("six" / 3);   // NaN
  • 할당 연산자(assignment operators)

    등호 연산자(=)

let x = 10;
console.log(x);   // 10

x = 5;
console.log(x);   // 5

더하기 등호 연산자(+=)

let x = 10;
console.log(x);   // 10

x += 5; // 5를 더해줌
console.log(x);   // 15

빼기 등호 연산자(-=)

let x = 10;
console.log(x);   // 10

x -= 5; // 5를 빼준다.
console.log(x);   // 5

곱하기 등호 연산자(*=)

let x = 10;
console.log(x);   // 10

x *= 5; // 5를 곱해준다.
console.log(x);   // 50

나누기 등호 연산자(/=)

let x = 10;
console.log(x);   // 10

x /= 5; // 5를 나눠줌
console.log(x);   // 2

나머지 등호 연산자(%=)

let x = 10;
console.log(x);   // 10

x %= 3; // 3으로 나누고 남은 몫 1
console.log(x);   // 1

비교 연산자(comparison operators)

  • 일치 연산자(===)

//  두 값이 같은지 자료형까지 비교
console.log(2 === 2);   // true
console.log("2" === 2);   // false
console.log(2 === "2");   // false
  • 불일치 연산자(!==)

// 두 값이 틀린게 확실한지 비교
console.log(2 !== 2);   // false
console.log("2" !== 2);   // true
console.log(2 !== "2");   // true
  • 작다(<) 연산자 , 작거나 같다 연산자 (<=)

console.log(2 < 3);   // true
console.log(2 <= 3);   // true
console.log(3 <= 3);   // true
console.log(4 <= 3);   // false

논리 연산자(logical operators)

  • 논리곱(&&) 연산자

// 모두 true 일때 true 반환
console.log(true && true);   // true
console.log(true && false);   // false
console.log(false && true);   // false
console.log(false && false);   // false
  • 논리합(||) 연산자

// 두 값중 하나라도 true 일 경우 true
console.log(true || true);   // true
console.log(true || false);   // true
console.log(false || true);   // true
console.log(false || false);   // false
  • 논리부정(!) 연산자

// true는 false 로 false 는 true로 바꿈
console.log(!true);   // false
console.log(!false);   // true
console.log(!(2 > 1));   // false
  • 삼항 연산자(ternary operator)

let x = 10;
let result = (x > 5) ? "크다" : "작다";
console.log(result);   // "크다"
let y = 20;
let answer = (y < 10) ? "작다" : "크다";
console.log(answer);  // "크다"

함수(function)

함수 선언문(function declaration)

// add라는 함수 선언
function add(x, y) {
  return x + y;
}

console.log(add(2, 3));   // 5

함수 표현식(function expression)

// add라는 변수에 함수를 할당
let add = function(x, y) {
  return x + y;
}

console.log(add(2, 3));   // 5
// 연습
let add2 = function(x, y) {
  return x + y;
};
let functionResult = add2(3, 4);  // 7
console.log(functionResult);
// 연습 2
let add3 = function (x, y) {
    return(x + y);
};
let functionresult = add3(10, 20);  // 30
console.log(functionresult);

함수 스코프(scope(범위))

  • 전역 스코프(global scope)

// 변수 x를 선언하고 함수 printX에서 변수 x를 참조
let x = 10;

function printX() {
  console.log(x);
}
printX();   // 10
  • 지역 스코프(local scope)

function printX() {
  let x = 10;
  console.log(x);
}
printX();   // 10

화살표 함수

기본적인 화살표 함수

// 화살표 함수를 사용하면 함수의 선언을 간결하게 할 수 있다.
let add = (x, y) => {
  return x + y;
}

console.log(add(2, 3));   // 5
  • 초간단 한 줄 화살표 함수

let add = (x, y) => x + y;

console.log(add(2, 3));   // 5
  • 매개변수가 하나인 화살표 함수

let square = x => x * x; // 3 곱하기 3

console.log(square(3));   // 9

0개의 댓글