Scribbling

JavaScript Basics 본문

Computer Science/Basics of Basics

JavaScript Basics

focalpoint 2022. 8. 25. 09:35

 

0. JavaScript Environment

https://jsbin.com/?js,console 

 

JS Bin

Sample of the bin:

jsbin.com

 

1. Variables

let x = 3;
const y = 4;
console.log(x*y);

let num = 3.14;
console.log(typeof(x))

 

2. Conditionals

2.1. If

let season = 'summer';

if (season === 'spring') {
  console.log('It\'s spring! The trees are budding!');
} else if (season === 'winter'){
  console.log('It\'s winter! Everything is covered in snow.');
} else if (season === 'fall'){
  console.log('It\'s fall! Leaves are falling!');
} else if (season === 'summer'){
  console.log('It\'s sunny and warm because it\'s summer!');
}
else {
  console.log('Invalid season.');
}

2.2. Switch

let athleteFinalPosition = 'first place';

switch (athleteFinalPosition){
  case 'first place':
    console.log('You get the gold medal!');
    break;
  case 'second place':
    console.log('You get the silver medal!');
    break;
  case 'third place':
    console.log('You get the bronze medal!');
    break;
  default:
    console.log('No medal awarded.')
    break;
}

 

3. Functions

3.1. Functions

function sayThanks(name) {
  console.log('Thank you for your purchase '+ name + '! We appreciate your business.');
}

sayThanks('Cole');

 

3.2. Arrow Functions

const plantNeedsWater = (day) => {
  if (day === 'Wednesday') {
    return true;
  } else {
    return false;
  }
};
const plantNeedsWater = day => day === 'Wednesday' ? true : false;

 

4. Arrays

4.1. length property

const objectives = ['Learn a new language', 'Read 52 books', 'Run a marathon'];

console.log(objectives.length)

4.2. push method

const chores = ['wash dishes', 'do laundry', 'take out trash'];

chores.push('dish');
chores.push('wash');
console.log(chores);

4.3. pop method

const chores = ['wash dishes', 'do laundry', 'take out trash', 'cook dinner', 'mop floor'];


chores.pop();
console.log(chores);

4.4. slice, shift, unshift, indexOf

const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];

groceryList.shift();
console.log(groceryList);

groceryList.unshift('popcorn');
console.log(groceryList);

console.log(groceryList.slice(1, 4));
console.log(groceryList);

const pastaIndex = groceryList.indexOf('pasta');
console.log(pastaIndex);

 

5. Loops

5.1. for loop

for(let i =5; i<11; i++){
  console.log(i);
}
for (let counter = 3; counter >= 0; counter--){
  console.log(counter);
}

5.2. while loop

const cards = ['diamond', 'spade', 'heart', 'club'];

// Write your code below
let currentCard;

while (currentCard !== 'spade'){
  currentCard = cards[Math.floor(Math.random() * 4)];
  console.log(currentCard);
}

5.3. do while loop

// Write your code below

let cupsOfSugarNeeded = 3;
let cupsAdded = 0;

do {
  cupsAdded += 1;
} while (cupsAdded < cupsOfSugarNeeded);

 

6. Iterators

6.1. forEach() method

const fruits = ['mango', 'papaya', 'pineapple', 'apple'];

// Iterate over fruits below
console.log(fruits.forEach(x => console.log('I want to eat a ' + x)));

6.2. map method

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

// Create the secretMessage array below
const secretMessage = animals.map(x => x[0]);

console.log(secretMessage.join(''));

const bigNumbers = [100, 200, 300, 400, 500];

// Create the smallNumbers array below
const smallNumbers = bigNumbers.map(function(x){return x/100;})

6.3. filter method

const randomNumbers = [375, 200, 3.14, 7, 13, 852];

// Call .filter() on randomNumbers below
const smallNumbers = randomNumbers.filter(x => x < 250);

const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene'];


// Call .filter() on favoriteWords below
const longFavoriteWords = favoriteWords.filter(x => x.length > 7);

6.4. findIndex method

const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

const foundAnimal = animals.findIndex(x => {return x === 'elephant';});

const startsWithS = animals.findIndex(x => {return x[0] === 's';});

6.5. reduce mthod

const newNumbers = [1, 3, 5, 7];

const newSum = newNumbers.reduce((accumulator, currentValue) => {
  console.log('The value of accumulator: ', accumulator);
  console.log('The value of currentValue: ', currentValue);
  return accumulator + currentValue}, 10);

console.log(newSum);

 

7. Objects

7.1. Properties

let spaceship = {
  'Fuel Type' : 'Turbo Fuel',
  homePlanet : 'Earth',
  color: 'silver',
  'Secret Mission' : 'Discover life outside of Earth.'
};

// Write your code below
spaceship.color = 'glorious gold';
spaceship.numEngines = 7;
delete spaceship['Secret Mission'];

 

7.2. Methods

let retreatMessage = 'We no longer wish to conquer your planet. It is full of dogs, which we do not care for.';

// Write your code below
const alienShip = {
  retreat () {
    console.log(retreatMessage);
  },
  takeOff () {
    console.log('Spim... Borp... Glix... Blastoff!');
  },
};

alienShip.retreat();
alienShip.takeOff();

 

7.3. Nested Objects

let spaceship = {
  passengers: null,
  telescope: {
    yearBuilt: 2018,
    model: "91031-XLT",
    focalLength: 2032 
  },
  crew: {
    captain: { 
      name: 'Sandra', 
      degree: 'Computer Engineering', 
      encourageTeam() { console.log('We got this!') },
     'favorite foods': ['cookies', 'cakes', 'candy', 'spinach'] }
  },
  engine: {
    model: "Nimbus2000"
  },
  nanoelectronics: {
    computer: {
      terabytes: 100,
      monitors: "HD"
    },
    'back-up': {
      battery: "Lithium",
      terabytes: 50
    }
  }
}; 

let capFave = spaceship['crew']['captain']['favorite foods'][0];
spaceship['passengers'] = [{'dog': 'bok'}, {'cat': 'kitty'}, ];
let firstPassenger = spaceship['passengers'][0];

 

7.4. looping through objects

let spaceship = {
    crew: {
    captain: { 
        name: 'Lily', 
        degree: 'Computer Engineering', 
        cheerTeam() { console.log('You got this!') } 
        },
    'chief officer': { 
        name: 'Dan', 
        degree: 'Aerospace Engineering', 
        agree() { console.log('I agree, captain!') } 
        },
    medic: { 
        name: 'Clementine', 
        degree: 'Physics', 
        announce() { console.log(`Jets on!`) } },
    translator: {
        name: 'Shauna', 
        degree: 'Conservation Science', 
        powerFuel() { console.log('The tank is full!') } 
        }
    }
}; 

// Write your code below
for (let member in spaceship.crew){
  console.log(`${member}: ${spaceship['crew'][member].name}`);
}

for (let member in spaceship.crew){
  console.log(`${spaceship['crew'][member]['name']}: ${spaceship['crew'][member]['degree']}`);
}

 

8. Advanced Topics

8.1. this

const robot = {
  model: '1E78V2',
  energyLevel: 100,
  provideInfo() { 
    return `I am ${this.model} and my current energy level is ${this.energyLevel}.`
  }
};

console.log(robot.provideInfo());

 

8.2. getter method

const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  get energyLevel () {
    if (typeof(this._energyLevel)==='number'){
      return `My current energy level is ${this._energyLevel}`;
    } else{
      return 'System malfunction: cannot retrieve energy level';
    }
  }
};

console.log(robot.energyLevel);

8.3. setter method

const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  _numOfSensors: 15,
  get numOfSensors(){
    if(typeof this._numOfSensors === 'number'){
      return this._numOfSensors;
    } else {
      return 'Sensors are currently down.'
    }
  },
  set numOfSensors(num){
    if (typeof(num)==='number' && num >= 0){
      this._numOfSensors = num;
    }
    else{
      console.log('Pass in a number that is greater than or equal to 0');
    }
  }
  
};

robot.numOfSensors = 100;
console.log(robot.numOfSensors);

8.4. Factory Functions

const robotFactory = (model, mobile) => {
  return {
  model: model,
  mobile: mobile,
  beep () {
    console.log('Beep Boop');
  }
  }
}

const tinCan = robotFactory('P-500', true);
tinCan.beep();

8.5. Destructured Assignment

const robot = {
  model: '1E78V2',
  energyLevel: 100,
  functionality: {
    beep() {
      console.log('Beep Boop');
    },
    fireLaser() {
      console.log('Pew Pew');
    },
  }
};

const {functionality} = robot;
functionality.beep();

8.6. Methods

const robot = {
	model: 'SAL-1000',
  mobile: true,
  sentient: false,
  armor: 'Steel-plated',
  energyLevel: 75
};

// What is missing in the following method call?
const robotKeys = Object.keys(robot);

console.log(robotKeys);

// Declare robotEntries below this line:
const robotEntries = Object.entries(robot)
console.log(robotEntries);

// Declare newRobot below this line:
const newRobot = Object.assign({laserBlaster: true, voiceRecognition: true}, robot);

console.log(newRobot);

 

9. Bind

this.school = 'gatech'

var stu1 = {
	'school': "snu",
	'getSchool': function (){
		return this.school;
	}
}


var func1 = stu1.getSchool;
var func2 = stu1.getSchool.bind(stu1);
console.log(func1());
console.log(func2());

 

 

 

'Computer Science > Basics of Basics' 카테고리의 다른 글

Pandas Basics  (0) 2022.08.27