TIL JavaScript from Dream Coding(5)

조수경·2022년 5월 27일
0

DreamCoding

목록 보기
5/9
post-thumbnail

1. Literals and properties

Objects
one of the JavaScript's data types.
a collection of related data and/or functionality.
Nearly all objects in JavaScript are instances of Object
object = { key : value };

const obj1 = {}; // 'object literal' syntax
const obj2 = new Object(); // 'object constructor' syntax

function print(person) {
  console.log(person.name); // amanda
  consoel.log(person.age); // 29
}

const amanda = { name: 'amanda', age: 29 };
print(amanda);

amanda.hasJob = true;
console.log(amanda.hasJob); // true

delete amanda.hasJob;
console.log(amanda.hasJob); // undefined

2. Computed properties

key should be always string type

console.log(amanda.name); // amanda
// * 코딩하는 순간 그 키에 해당하는 값을 받아오고 싶을 때 사용
console.log(amanda['name']); // amanda
// * 정확하게 어떤 키가 필요한 지 모를 때(런타임에서 결정될 때) computed properties	사용
// * 실시간으로 값을 받아오고 싶을 때
amanda['hasJob'] = true;
console.log(amanda.hasJob); // true

function printValue(obj, key) {
  console.log(obj.key);
}
printValue(amanda, 'name'); // undefined

function printValue(obj, key) {
  console.log(obj.[key]);
}
printValue(amanda, 'name'); // amanda
printValue(amanda, 'age'); // 29

3. Property value shorthand

const person1 = { name: 'bob', age: 2 };
const person2 = { name: 'steve', age: 3 };
const person3 = { name: 'dave', age: 4 };
const person4 = new Person('amanda', 29);

console.log(person4); // { name: "amanda", age: 29}

4. Constructor Function

function Person(name, age) {
  // this = {};
  this.name = name;
  this.age = age;
 // return this;
}

5. in operator : property existence check ( key in obj )

console.log('name' in amanda); // true
console.log('age' in amanda); // true
console.log('random' in amanda); // false
console.log(amanda.random); // undefined

6. for..in vs for..of

for ( key in obj ) 모든 key를 받아올 때 사용

console.clear(); // 이전 로그 삭제

for (key in amanda) {
  console.log(key);
}

for ( value of iterable )

const array = [1, 2, 3, 4];
for (let i = 0; i < array.length; i++) {
  console.log(array[i]);
}

for(value of array) {
  console.log(value);
}

7. Fun cloning

Object.assign(dest, [obj1, obj2, obj3...])

const user = { name: 'amanda', age: '29' };
const user2 = user;
user2.name = 'coder';
console.log(user); // coder

// old way
const user3 = {};
for (key in user) {
  user3[key] = user[key];
}
console.log(user3);

// the other way
const user4 = Object.assign({}, user);
console.log(user4);

// another example
const fruit1 = { color: 'red' };
const fruit2 = { color: 'blue', size: 'big' };
const mixed = Object.assign({}, fruit1, fruit2); 
// * 동일한 프로퍼티가 있을 때 뒤에 나온 프로퍼티가 값을 계속 덮어준다. 
console.log(mixed.color); // blue
console.log(mixed.size); // big

0개의 댓글