본문 바로가기
Programming/JavaScript

[JavaScript] JavaScript 기초

by inyeong 2024. 9. 23.

1. Console

console은 정보를 출력해주는 사용자 인터페이스다.

console 객체의 .log( ) 메소드를 통해 console에 데이터를 출력할 수 있다. console.log( )

 console.log(22);

 

2. Comments (주석)

주석은 코드를 설명하기 위한 것으로, 프로그램 실행 시 무시된다.

  • 한 줄 주석 (single line comment) //
  • 여러 줄 주석, 코드 중간 주석 (multi line comment, middle of a line of code) /* */
// single line comment

/*
	multi
	line
	comment 
*/

 

3. Data Types (자료형)

자료형은 프로그래밍에서 사용하는 다양한 종류의 데이터에 대한 분류이다. 

자바스크립트에는 8가지 기본 타입이 있다. 


1. Number 
2. BigInt 
3. String : '...' (single quotes), "..." (double quotes)
4. Boolean : true / false 
5. Null : 값이 없음
6. Undefined : 값이 할당되지 않은 변수 
7. Symbol 
8. Object : 관련 데이터와 기능을 하나로 묶어 관리하는 것 

console.log('String');
console.log(2024);
console.log(20.24);

 

4. Arithmetic Operators (산술 연산자) 

Add  Subtract  Multiply  Remainder 

console.log(22+3.5);
console.log(2024-1969);
console.log(65/240);
console.log(0.2708*100);

 

5. String Concatenation (문자열 연결) 

Add 연산자는 String 연결에 사용할 수 있다. 

console.log('Hello'+'World'); // 공백 없이 연결 
console.log('Hello '+'World');

 

6. Properties (속성)

객체 (인스턴스)는 저장된 정보인 속성을 갖는다. 

속성은 . (dot operator)를 통해 사용할 수 있다.

 

대표적인 예시로 String 인스턴스의 lenth 프로퍼티가 있다. 

console.log('Hello World'.length);

 

7. Methods (메소드)

객체(인스턴스)는 특정한 행동을 수행할 수 있는 method를 갖는다. 

메소드는 . (dot operator)와 method 이름, ( )를 통해 사용할 수 있다. 

 

ex) console.log( ), 'string'.toUpperCase( )

console.log('Hey'.startsWith('H'));              // output : true

console.log('Codecademy'.toUpperCase());         // output : CODEACADEMY

console.log('    Remove whitespace   '.trim());  // output : Remove whitespace

 

8. Built-in Objects (내장 객체)

JavaScript에서 기본으로 제공되는 객체 메소드와 속성이 있다. 

 

ex) Math Object의 .random() .floor() .ceil() .isInteger() method

console.log(Math.random());                  // 0 이상 1 미만의 랜덤 부동소수점
console.log(Math.random() * 50);             // 0 이상 50 미만의 랜덤 부동소수점
console.log(Math.floor(Math.random() * 50)); // 0 이상 50 미만의 랜덤 정수

console.log(Math.floor(Math.random()*100));  // 0 이상 100 미만의 랜덤 정수
console.log(Math.ceil(43.8));                // 올림 -> 44
console.log(Number.isInteger(2017));         // 정수이면 true, 정수가 아니면 false

 

 

9. Variables (변수)

변수는 특정 이름으로 정보를 저장하는 메모리 공간이다. 

 

  • 변수 생성 방법 
  1. var
    var myName = 'Inyeong';
    console.log(myName);  // Output: Inyeong
    
    /*
    myName : 변수명 
    = : 할당 연산자 (assignment operator)
    'Inyeong' : 변수에 할당된 값(value) -> myName 변수는 'Inyeong'로 초기화됨
    */

  2. let
    (1) 다른 값(value)으로 재할당될 수 있다.
    (2) 초기화하지 않고 선언할 수 있으며, 자동으로 undefined로 초기화된다. 
    let meal = 'Enchiladas';
    console.log(meal); // Output: Enchiladas
    meal = 'Burrito';
    console.log(meal); // Output: Burrito
    
    let age;
    console.log(age); // Output: undefined
    age = 25;
    console.log(age); // Output: 25
    
    let changeMe = true;
    changeMe = false;
    console.log(changeMe) //false

  3. const 
    (1) 재할당이 불가능하다. 재할당을 시도하면 TypeError 발생
    (2) 선언될 때 값을 반드시 할당받아야 한다. 값을 할당하지 않고 선언하면 SyntaxError 발생
    const myName = 'Inyeong';
    console.log(myName); // Output: Inyeong
     
    값을 재할당해야 하는 경우에는 let을, 그렇지 않은 경우에는 const를 사용한다. 
  • 변수명 생성 규칙
    1. 숫자로 시작할 수 없다. 
    2. 키워드를 사용할 수 없다. 
  • Mathematical Assignment Operators : 연산 후 새로운 값을 변수에 할당
     
    Add  +=  Subtract  -=  Multiply  *=  Remainder  %=

    let w = 4;
    w += 1;
    console.log(w); // Output: 5
    
    x -= 5; // Can be written as x = x - 5
    console.log(x); // Output: 15
    
    let y = 50;
    y *= 2; // Can be written as y = y * 2
    console.log(y); // Output: 100
    
    let z = 8;
    z /= 2; // Can be written as z = z / 2
    console.log(z); // Output: 4


  • Increment and Decrement Operator : 증가 ++  감소 --

    let a = 10;
    a++;
    console.log(a); // Output: 11
    
    let b = 20;
    b--;
    console.log(b); // Output: 19


  • String Concatenation with variables : 변수에 저장된 문자열 연결
     
    let favoriteAnimal = 'dog';
    console.log('My favorite animal: '+favoriteAnimal);
    // My favorite animal: dog


  • String Interpolation : template literal로 변수를 문자열 내에서 출력
     
    let myName = 'inyeong';
    let myCity = 'Seoul';
    console.log(`My name is ${myName}. My favorite city is ${myCity}.`);
    // Output : My name is inyeong. My favorite city is Seoul.


  • typeof operator : 변수에 할당된 값의 데이터 타입을 확인한다.
     
    const data1 = 'abc';
    console.log(typeof data1); // Output: string
    
    const data2 = 10;
    console.log(typeof data2); // Output: number
    
    const data3 = true; 
    console.log(typeof data2); // Output: boolean



 

예제 코드 : https://github.com/inyeongjang/Snoopy/blob/main/week02/1-Introduction.js

 

Snoopy/week02/1-Introduction.js at main · inyeongjang/Snoopy

Contribute to inyeongjang/Snoopy development by creating an account on GitHub.

github.com

 

출처 / 참고자료https://www.codecademy.com/enrolled/courses/introduction-to-javascript

 

Learn JavaScript | Codecademy

Begin your web development journey with our JavaScript course. Explore dynamic scripting for interactive web solutions.

www.codecademy.com

'Programming > JavaScript' 카테고리의 다른 글

[JavaScript] Loops & Iterators  (0) 2024.09.28
[JavaScript] Arrays (배열)  (0) 2024.09.25
[JavaScript] Scope  (0) 2024.09.25
[JavaScript] Functions (함수)  (0) 2024.09.25
[JavaScript] Conditional Statements (조건문)  (0) 2024.09.25