본문 바로가기
ONLINE COURSES/JavaScript

Basics-1

by jono 2021. 6. 12.

0. Basics

//log to console
console.log('hello world ');
console.log(123);
console.log('true');
var greeting = 'hello';
console.log(greeting);
console.log([1,2,3,4,5]);
console.log({a:1, b:2});
console.table({a:1, b:2});

console.error('this is some error');
console.clear();
console.warn('this is a warning');
console.time('hello');
  console.log('hello world ');
  console.log(123);
  console.log('true');
  var greeting = 'hello';
console.timeEnd('hello');

1. Data Types in js

- primitive data types
: stored directly in the location the variables accesses
 stored on the stack

  1. string
  2. number
  3. boolean
  4. null
  5. undefined
  6. symbols(es6)

 

- reference data types
: accessed by reference
objects that are stored on the heap
a pointer to a location in memory

  1. arrays
  2. object literals
  3. functions
  4. dates
  5. anything else

 

# javascript is dynamically typed language

- types are associated with values not variables
- the same variable can hold multiple types
- we do not need to specify types
- most other languages are statically typed (java, c#, c++)
- there are supersets of js and addons to allow static typing(typescript, flow)

# example code

// primitive

// string
const name = 'john doe';

//number
const age = 50;


//boolean
const hasKids = true;

// Null
const car = null;

//undefined
let test;

//symbol
const sym = Symbol();

console.log(typeof name);
console.log(typeof age);
console.log(typeof hasKids);
console.log(typeof car);
console.log(typeof test);
console.log(typeof sym);


// reference types - objects

// array
const hobbies = ['movies', 'music'];
console.log(typeof hobbies);

//object literal
const address = {
  city: 'london',
  state: 'ma'
}
console.log(typeof address);

//
const today = new Date();
console.log(typeof today);

2. Data Conversion

//number to string
val = String(50+5); 
// output
console.log(val);            //55
console.log(typeof val);     // string
console.log(val.length);      //2


//boolean to string
val = String(true);
console.log(val);           //true
console.log(typeof val);    //string
console.log(val.length);    //4

// date to string
val = String(new Date());
console.log(val);
console.log(typeof val);
console.log(val.length);


//array to string
val = String([1,2,3,4,5]);
console.log(val);           // 1,2,3,4,5
console.log(typeof val);    // string
console.log(val.length);    // 9


// toString()
val = (5).toString();
console.log(val);          // 5
console.log(typeof val);   //string
console.log(val.length);   // 1

val = (true).toString();
console.log(val);          //true
console.log(typeof val);   //string
console.log(val.length);   //4



// string to numbers
val = Number('5');
console.log(val);       // 5
console.log(typeof val);   //number
console.log(val.toFixed(2));   //5.00

val = Number(true);
console.log(val);       //1
console.log(typeof val);  //number
console.log(val.toFixed(2));   // 1.00

val= Number(false);    
console.log(val);         // 0
console.log(typeof val);
console.log(val.toFixed());


val = Number(null);
console.log(val);     // 0
console.log(typeof val);
console.log(val.toFixed());


val =Number('hello');
console.log(val);             //NaN : not a number
console.log(typeof val);
console.log(val.toFixed());

val = parseInt('100');
console.log(val);
console.log(typeof val);
console.log(val.toFixed());

val = parseFloat('100.566');
console.log(val);
console.log(typeof val);        //number
console.log(val.toFixed(2));    // 100.57


let val;

// number
val = 5;
// output
console.log(val);          //5
console.log(typeof val);   //number
console.log(val.length);   //undefined


//number to string
val = String(555);
// output
console.log(val);           // 555
console.log(typeof val);    // string
console.log(val.length);    // 3


// type coersion
const val1 = 5;
const val2 = 10;
const sum = val1 + val2;

console.log(sum);       //15
console.log(typeof sum);  //number



3. Math Objects

const num1 = 100;
const num2 = 50;
let val;

// simple math with numbers
val = num1 + num2;
val = num1 * num2;
val = num1 % num2;    // % : remainder


//math objects
val = Math.PI;           //Math 는 프로그램자체 기능임
val = Math.E;
val = Math.round(2.8)    //Math.round() :  괄호안에 있는 수를 반올림함
val = Math.ceil(3.4);     //Math.ceil() : 괄호안에 있는 수를 올림
val = Math.floor(2.3);    //Math.floor() : 괄호안에 있는 수를 내림

val = Math.sqrt(16);    //Math.sqrt(): squar-제곱근을 구함
val = Math.abs(-3);      //Math.abs() : absolute number = 절대값을 구함
val = Math.pow(8,2);   //Math.pow(x,y): x의 y승
val = Math.min(2,55,65,33,1,8,3,-5)       // minimum
val = Math.max(2,55,65,33,1,8,3,-5)       //maximum
val = Math.random(); // Math.random(); random number 반환한다
val = Math.floor(Math.random() * 20 + 1);    //랜덤값에 20곱해서 1더한 값을 내림



console.log(val);

4. String Methods, Concatenation

const firstName = 'Mike';
const lastName = "Johnson";
const age = 35;
const str = 'Hello my name is Joho';
const tags = 'web design, web programming, machine learning, web development'

let val;

val = firstName + lastName;

//concatenation 문자 연결하기 with 띄어쓰기
val = firstName + ' ' + lastName;

//Append  +=
val = 'Lady ';
val += 'gaga';

val = 'Hello my name is ' + firstName + ' and I am ' + age;

//Escaping
val = 'That\'s awesome I can\'t wait';   //  문자에서 작은따옴표를 써야한다면 앞에 \를 붙여 wrap이 아니게 만든다.

//Length
val = firstName.length;

// concat(a,b) : a=붙일 문자 사이에 들어갈 문자 / b=이어질 문자
val = firstName.concat(' ', lastName); //concatenation의 다른 방법. 

// Change Case
val = firstName.toUpperCase();
val = firstName.toLowerCase();

val = firstName[0];  //R

//indexof()
val = firstName.indexOf('i');  //1
val = lastName.lastIndexOf('d');  //3

//charAt()
val = firstName.charAt('2');  // c

//Get last char
val = firstName.charAt(firstName.length -1);

//substring(a,b) a번째 자리부터 b개의 문자를 추출한다
val = firstName.substring(0,4);   //Rich

//slice()
val = firstName.slice(0,4);
val = firstName.slice(-3);   //slice(-n) 뒤에서부터 n개의 문자를 추출함

//split(x)  x는 문자를 나누는 기준이 된다.
val = str.split(' ');
val = tags.split(',');

//replace(a,b)   a=교체될 원래값  b=바꾸고싶은 값
val = str.replace('Joho', 'Mike');

//includes(a)  지정하는 문자열에 a가 포함되어있는지 t/f로 출력함.   
val = str.includes('Hello')



console.log(val);

'ONLINE COURSES > JavaScript' 카테고리의 다른 글

Basics-3 function // loops // iterations  (0) 2021.06.13
Basics-2  (0) 2021.06.12
Object 객체 { }  (0) 2021.05.31
Function / Parameter & Argument  (0) 2021.05.30
조건문, 반복문while을 활용해 화면모드 바꾸기  (0) 2021.05.29

댓글