Javascript

JavaScript Fundamental part 2

mossybeach 2024. 1. 29. 15:01

strict mode?

it helps us avoid future bugs that JS might not catch such as typos.

add as string on first line of code before writing any code!

always add!


Functions

we can create reusable chunks of code using functions : keeping code dry!!

function logger() {
  console.log(`my name is roxy`);
}
//invoking/calling/running the function
logger();

 

//below are called parameters
function fruitProcessor(apples, oranges) {
  console.log(apples, oranges);
  const juice = `Juice with ${apples} apples and ${oranges} oranges`;
  return juice;
}
//the actual value that goes in parameters are called arguments
const appleJuice = fruitProcessor(5, 0);

 

function works as a skeleton for a process, like a machine that does a certain job!
but this machine cannot work until the process is called, like pressing a button . And in order to get the finished product you must always ask for a return. If we don't ask for a return the process will run but it won't give any results!

once a return is declared it will exit out of a function, so be careful of  prematurely calling it and exiting the code when there are still things to process.

console.log(appleJuice);
// Juice with 5 apples and 0 oranges

Function declarations and expressions

 

//function declaration
function calcAge1(birthYear) {
  return 2024 - birthYear;
}
const age1 = calcAge1(1999);
console.log(age1);

function declaration is where you name a function straight away, in this case: calcAge1.

const calcAge2 = function (birthYear) {
  return 2024 - birthYear; //expression
};
const age2 = calcAge2(1984);

However a function expression is where you store an anonymous function (function without  name) in a variable.

 

difference between two is declarations can be called before being declared however with expression we can't do this due to 'hoisting'. However for clean code always use expression!


Arrow functions

a simpler way to write functions, however it can't replace traditional functions completely as you can't use 'this'  keyword in arrow functions

const caclAge3 = (birthYear) => 2024 - 1999;
const age3 = caclAge3(1999);

const yearsUntilRetirement = (birthYear, firstName) => {
  const age = 2024 - birthYear;
  const retirement = 65 - age;
  return `${firstName} retires in ${retirement}`;
};

console.log(yearsUntilRetirement(1999, "roxy"));

Functions calling other functions

a function that is declared outside can be called in another function. This is important when there are a lot of components and for dry coding.

const cutPieces = function (fruit) {
  return fruit * 4;
};

const fruitProcessor = function (apples, oranges) {
  const applePieces = cutPieces(apples);
  const orangePieces = cutPieces(oranges);

  const juice = `Juice with ${applePieces} pieces of apple and ${orangePieces} pieces of orange`;

  return juice;
};

console.log(fruitProcessor(2, 3));

 


Arrays

 type of data structure  

Arrays are big containers that stores variables and later reference them

 

  • two ways to write arrays

literal syntax (more common):const friends = ["michael", "Jonas", "Theo"]

 

or

const years = new Array(1991, 1999, 1984);

  • arrays are zero based (count starts at 0, 1,2..)

.length = counts number of elements in array

ex: friends.length = 3

inside the bracket, we can put in any expression : console.log(friends[friends.length - 1]);

 

  • we can replace any element in the array 
friends[2] = `Max`;

 

  • In arrays even if the variable is set as const, you can still mutate the array, this is because its not a primitive value!!

However we can't replace the entire array, friends =['Alison' , 'Ray']

 

  • We can place variables, numbers, strings and even other arrays into an Array
const friends = ["michael", "Jonas", "Theo"];

const firstname = `Roxy`;
const me = [firstname, "Lee", 1999, friends];

 


Array methods and operations

 

methods to use for arrays

  • push : adds an element to an array at the end, it is  a methood but also a function
const friends = ["michael", "Jonas", "Theo"];
friends.push(`Jay`);
console.log(friends);
//['michael', 'Jonas', 'Theo', 'Jay']

since push is also a function, it can also return a value. to capture an array after adding or subtracting an element.

just store it in a variable

  • unshift: adds element to beginning of array
friends.unshift("John");
console.log(friends);
// ['John', 'michael', 'Jonas', 'Theo']

 

  • pop: removes element at the end of an array
friends.pop();
console.log(friends);
 //['John', 'michael', 'Jonas']

 

  • shift: removes element from the start of an array
friends.shift();
console.log(friends);//['michael', 'Jonas']

 

  • indexOf: gets the index value of an element
console.log(friends.indexOf(`Jonas`));
//1

if we search for an element that isn't there we will get -1

  • includes(ES6 grammar): gives boolean value if element is in the array = strict equality (string and math is differenciated)
console.log(friends.includes(`Ray`)); // false

 

we can use includes to write conditionals

if (friends.includes(`Ron`)) {
  console.log(`you have a friend called Ron`);
} //false

 


Objects

stored in curly braces { }

objects are consisted of key and values.

const roxy = {
  firstName: `roxy`,
  lastName: "Lee",
  age: 2024 - 1999,
  job: `jobless`,
  friends: [`Ellie`, "Elissa", "Pat"],
};

 

each key is also called a property: so object called roxy has 5 properties.

 

difference between object and array is that the order of an object doesn't matter at all when we want to retrieve value from an object.

 

array =ordered data

object = unstructured data

 

to retrive data from an object there are two methods:

 

1. dot notation

const roxy = {
  firstName: `roxy`,
  lastName: "Lee",
  age: 2024 - 1999,
  job: `jobless`,
  friends: [`Ellie`, "Elissa", "Pat"],
};

console.log(roxy.firstName); //roxy

 

2. bracket notation

const roxy = {
  firstName: `roxy`,
  lastName: "Lee",
  age: 2024 - 1999,
  job: `jobless`,
  friends: [`Ellie`, "Elissa", "Pat"],
};

console.log(roxy[`age`]);//25

 

brackets notations are useful when storing a result in a variable and using said variable to search a certain value within an object as dot notation can only fetch back info if we use the correct key

 

For example:

const interest = prompt(
  `what do you want to know about Roxy? Choose from firstName, lastName, age, job and friends`
);

console.log(roxy.interest); //undefined as there is no interest key in roxy

 

so we do this instead!!

console.log(roxy[interest]); //age

 

we can also add more keys and values to the object using both dot and bracket notations

roxy.talent = `rot`;
roxy[`aura`] = `bad bitch`;

 


object methods

 we can store functions in objects as a key and value form because functions count as values! 

like this:

const roxy = {
  firstName: `roxy`,
  lastName: "Lee",
  birthYear: 1999,
  job: `jobless`,
  friends: [`Ellie`, "Elissa", "Pat"],
  hasDriversLicense: false,
  calcAge: function (birthYear) {
    return 2024 - birthYear;
  },
};

we call calcAge a method!

 

to use brackets to get result: 

console.log(roxy[`calcAge`](1999));

 

HOWEVER since 1999 is already stored in key birthYear we can source this directly by using this.

this is equal to the object calling the method!!

 

for example:

  calcAge: function () {
    return 2024 - this.birthYear;
  },

here this is referencing the object roxy

  giveSummary: function () {
    return `${this.firstName} is a ${this.calcAge()} year old. She has ${
      this.hasDriversLicense ? "a" : "no"
    } driver's license`;
  }

 


The for Loop

  • a control structure like if, else

Loop help us automate repetitve tasks!

 

a loop statement has 3 parts!

1.) counter called rep 

2.) logical condition evaluated before each iteration of the loop, if the condition is true the next rep will run

3.) counter increaser

 

for loops keep running while condition is true!

for (let rep = 1; rep <= 10; rep++) {
  console.log(`lifting weights repetition ${rep}`);
}

using the for loop with an array

const roxyArray = [
  `Roxy`,
  `Lee`,
  2024 - 1999,
  `student`,
  [`Ellie`, `Elissa`, `Pat`],
  true,
];

for (let i = 0; i < roxyArray.length; i++) {
  console.log(roxyArray[ i ], typeof roxyArray[ i ]);
}
 

 

we can also create an empty array and fill it using the for loop

const types = [];
const roxyArray = [
  `Roxy`,
  `Lee`,
  2024 - 1999,
  `student`,
  [`Ellie`, `Elissa`, `Pat`],
  true,
];

for (let i = 0; i < roxyArray.length; i++) {
  //reading from roxyArray
  console.log(roxyArray[i], typeof roxyArray[i]);

  //filling in types array
  types[i] = typeof roxyArray[i];
}

 

however a cleaner version of the above will be

types.push(typeof roxyArray[i]);

 

 


continue and break in for loops

 

  • we use continue when we want to skip some parts of the loop

 

for example, if we only want to get results for string, we can write an if statement in the for loop

const roxyArray = [
  `Roxy`,
  `Lee`,
  2024 - 1999,
  `student`,
  [`Ellie`, `Elissa`, `Pat`],
  true,
];

for (let i = 0; i < roxyArray.length; i++) {
 
  if (typeof roxyArray[i] !== `string`) continue;
  console.log(roxyArray[i], typeof roxyArray[i]);
}

 

  • break terminates the entire loop (similar to break in switch statement)
for (let i = 0; i < roxyArray.length; i++) {
  if (typeof roxyArray[i] === `number`) break;
  console.log(roxyArray[i], typeof roxyArray[i]);
}

 

so the loop will only print twice, Roxy and Lee before terminating at 2024-1999 (25)

 


looping backwards and loop within a loop

 

  • looping backwards

we can also print out an array in the opposite direction by doing this:

 
const roxyArray = [
  `Roxy`,
  `Lee`,
  2024 - 1999,
  `student`,
  [`Ellie`, `Elissa`, `Pat`],
];

for (let i = roxyArray.length - 1; i >= 0; i--) {
  console.log(i, roxyArray[i]);
}

 

  • loop inside a loop
  • for (let excercise = 1; excercise <= 3; excercise++) {
      console.log(`starting excercise number ${excercise}`);

      for (let rep = 1; rep <= 5; rep++) {
        console.log(` excercise ${excercise} lifting weight repetion ${rep}`);

        for (let breath = 1; breath <= 1; breath++) {
          console.log(`breathe in, breathe out`);
        }
      }
    }

'Javascript' 카테고리의 다른 글

Data structures, Moden operators and strings  (0) 2024.04.23
JavaScript: Behind the scenes  (0) 2024.04.04
DOM and Events Fundamentals  (0) 2024.04.03
JavaScript fundamental notes 1  (0) 2024.01.23