본문 바로가기

Web Development/TypeScript

Section 4: Next-generation JavaScript & TypeScript

"let" and "const" 

  • Define constants
  • variables defined with const cannot be changed 
  • TypeScript throws error before runtime (as opposed to JavaScript)
  • you shouldn't use var anymore 
  • let --> scope in which this variable is available 
  • variables = global and function scope 
if (age > 20) {
	var isOld = true;
}

console.log(isOld); // error
function add(a: number, b: number) {
	let result;
    result = a + b;
    return result; 
}
  • let and const introduce block scope --> variable you defined is accessible in the block (inside curly braces) you define it or any lower blocks
  • clearner code 

 

Arrow function 

  • bit shorter
  • has some variations 
const add = (a: number, b: number) => {
	return a + b;
};

const addShorter = (a: number, b: number) => a + b;

const printOutput: (a: number | string) => void = output => console.log(output);

const button = document.querySelector('button');
if (button) {
	button.addEventListener('click', event => console.log(event)); 
}

 

Default function parameters

always define default value to later parameter 

const add = (a: number, b: number = 1) => a + b; 

console.log(add(5));

 

The Spread Operator (...) 

const hobbies = ['Sports', 'Cooking']; 
const activeHobbies = ['Hiking']; 

// pull out all elements off the array and add them as list of individual values to push
activeHobbies.push(...hobbies);

const activeHobbies2 = ['Hiking', ...hobbies];

// also exists on an object 
const person = {
	name: 'Max',
	age: 30
}

const copiedPerson = { ...person };

 

 

Rest Parameters

// add as many values as user passes in 
// merge all incoming parameters (comma separated list of values) 
const add = (...numbers: number[]) => {
	let result = 0; 
	return numbers.reduce((curResult, curValue) => {
    	return curResult + vurValue; 
    }, 0);
};


const addedNumbers = add(5,10,2,3.7);

 

Array & Object Destructuring 

// destructure = pull elements out of the array 
const [hobby1, hobby2, ...remainingHobbies] = hobbies; 

const person = {
	firstName = 'Max',
	age = 30
}

const { firstName, age } = person;