KEMBAR78
JS Refreshing | PDF | Method (Computer Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
14 views8 pages

JS Refreshing

Resumen breve de conceptos de js

Uploaded by

aex.mach
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

JS Refreshing

Resumen breve de conceptos de js

Uploaded by

aex.mach
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

0.

Adding JS to a web page

- Inline script
<button onclick='console.log('Hello Andie')'>PUSH ME</button>

- Internal Script
<button onclick='hi'>PUSH ME</button>

<script>
const hi = () => { console.log('Hello Andie') }
</script>

- External script

<srcipt src='hello.js'></script>

-------------------------------------------------------------------------------

1. Arrays

- How to create an empty array


let arr = [] or let arr = Array()

- Create an array with values, print it and it's length


let ragingCrow = ['Fischl', 'Xiao', 'Chongyung', 'Xingqui']
console.log(`This is my team! ${ragingCrow}`)
console.log(`It has ${ragingCrow.length} members`)

- Create an array using split


let archon = 'Barbatos'
archon.split('')

- Modify the values from the array ragingCrow


ragingCrow[2] = 'Eula'

- Methods to manipulate arrays

- Create an empty array and an empty array with 8 slots


let arr = Array()
let arr2 = Array(8)

- Create an array with 8 spaces and fill it with the number 0


let arr = Array(8).fill(0)

- Concatenate two arrays


let numbers = [1,2,3]
let letters = ['a','b','c','a']
let allTogether = numbers.concat(letters')

- Get the index from an element of the array


console.log(allTogether.indexOf('b'))

- Get the last index of an element


console.log(allTogether.lastIndexOf('a'))

- Make sure that an element exists in an array


ragingCrow = ['Fischl', 'Xiao', 'Chongyung', 'Xingqui']
console.log(ragingCrow.includes('Fischl'))
- Make sure it's an array and convert it into a string
console.log(Array.isArray(ragingCrow))
ragingCrow.toString()

- Join Method: Converts an array into a string and concatenate


them with the argument
ragingCrow = ['Fischl', 'Xiao', 'Chongyung', 'Xingqui']
console.log(ragingCrow.join())
//FischlXiaoChongyungXingqui

- Slice Method: Return a copy of the especified elements,


the original array is NOT modified
let numbers = [1,2,3,4]
numbers.slice() //copies all the elements

- Splice Method: It can modify the array, through 3 parameters:


starting position, no. of items to remove, items to add
let numbers = [1,2,3,4]
console.log(numbers.splice(3, 3, 7, 8, 9))

- Push/Pop
let number = [1,2,3,4,5,6]
number.push(7)
number.pop()

- Shift: Remove an item from the begining of the array


let number = [1,2,3,4,5,6]
number.shift() //[2,3,4,5,6]

- unshift: Add an item on the begining of the array


let number = [1,2,3,4,5,6]
number.unshift(0) //[0,1,2,3,4,5,6]

- reverse: reverse the order of the array


let number = [1,2,3,4,5,6]
number.reverse() //[6,5,4,3,2,1]

- sort: Arrange the items of the array in ascending order


let number = [6,5,4,3,2,1]
number.sort() //[1,2,3,4,5,6]

3. Conditionals

let age = window.prompt('how pold r u?')


age > 30
? console.log('u are old enough to drive')
: console.log('u are not old enough to drive')

let age = window.prompt('how pold r u?')


age > 25
? console.log(`u are ${age - 25} years older than me`)
: console.log(`im ${25 - age} years older than u`)

4. loops

for: We use it when we know the number of iterations we gonna go


while: We use it when we dont know the iteration we gonna go

do while: It runs when at least once when the condition is true or


false

for of: We use it to iterate an array by NOT USING it indexes

forEach: We use this METHOD when we wanna apply a callback to all the
items of the array. The callback takes 3 arguments: index,
item and the array

const countries = ['Finland', 'Sweden', 'Norway', 'Denmark',


'Iceland']
countries.forEach((country, i, arr) => {
console.log(i, country.toUpperCase())
})

for in: We use it with OBJECTS to get their keys

const user = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
skills: ['HTML', 'CSS', 'JS', 'React', 'Node',
'Python', 'D3.js'],
}

for (const key in user) {


console.log(key, user[key])
}

Interrumpting a loop

Both of these are used in for loop.

- continue: Omites one iteration


- break: Ends the whole loop

5. Objects

const person = {
firstName: 'Andres',
lastName: 'Jacinto',
age: 250,
country: 'Mexico',
city: 'Leon',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Node',
'MongoDB',
'Angular',
'Three.js',
],
isMarried: false,
getFullName: function () {
return `${this.firstName} ${this.lastName}`
},
phoneNumber: '+524774078325',
}

- Objects can be mutated, for instance we're gonna add keys and methods

person.nationality = 'English'
person.country = 'Korea'
person.title = 'Developer'
person.skills.push('Meteor')
person.skills.push('SasS')
person.isMarried = true

person.getPersonInfo = function () {
let skillsWithoutLastSkill = this.skills
.slice(0, this.skills.length - 1)
.join(', ')
let lastSkill=this.skills.slice(this.skills.length-1)[0]

let skills= `${skillsWithoutLastSkill} and ${lastSkill}`


let fullName = this.getFullName()
let statement = `${fullName} is a ${this.title}.\nHe
lives in ${this.country}.\nHe teaches
${skills}.`

return statement
}

- Methods to manipulate Objects

- assign: Copy an object without modify


let copy = Object.assign({}, person)

- keys: It returns an object keys and functions as an array


let keys = Object.keys(copy)
//['name', 'age', 'country', 'skills', 'address',
'getPersonInfo']

- values: It returns an object values as an array


let values = Object.values(copy)

- entries: It returns an object keys & values as an array


let entries = Object.entries(copy)

- hasOwnProperty: Check if an object has an specific property


console.log(copy.hasOwnProperty('name'))

6. Functions

- Functions with unlimited parameters

A function declaration provides us an array of arguments, any


thing we pass as an argument can be access from the array
"arguments". Example:

function sumAllNums() {
let sum = 0
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i]
}
return sum
}

console.log(sumAllNums(1, 2, 3, 4)) // 10
console.log(sumAllNums(10, 20, 13, 40, 10)) // 93

- Arrow fucntions with unlimited parameters

We will use the spread operator to access to any thing we pass


as an argument. Example:

const sumAllNums = (...args) => {


console.log(args)
}

7. Destructuring
Unpack an array or an object and assigning to a distinct variable.

- Destructuring nested array

let fullstack = [
[HTML, CSS, JS, React],
[Node, Express, MongoDB]
]

let [frontend, backend] = fullstack

- Skiping a value during destructuring (add a comma)

let countries = ['Mexico', 'USA', 'Spain', 'Egypt', 'Chile']


let [mx,,sp,,chi] = countries
console.log(mx, sp, chi) //['Mexico', 'Spain', 'Chile']

- Spread operator: returns an ARRAY of the rest of the array

let num = [1,2,3,4,5,6,7,8,9,10]


let [one, two, tree, ...rest] = num
console.log(one two, tree, ...rest) //[1,2,3,[4,5,6,7,8,9,10]]

- Destructuring when we loop an Array

let fullstack = [
['HTML', 'CSS', 'JS', 'React'],
['Node', 'Express', 'MongoDB']
]

for(let [One, Two, Tree, Four] of fullstack) {


console.log(`${One}, ${Two}, ${Tree}, ${Four}`)
/*
"HTML, CSS, JS, React"
"Node, Express, MongoDB, undefined"
*/
}

- Destructuring an Object

The name of the variable MUST be the same as the object property
const rectangle = {
width: 20,
height: 10,
}

let { width, height } = rectangle


console.log(width, height, perimeter) // 20, 10

const props = {
user:{
firstName:'Andres',
lastName:'Jacinto',
age:250
},
post:{
title:'Destructuring and Spread',
subtitle:'ES6',
year:2020
},
skills:['JS', 'React', 'Redux', 'Node', 'Python']

const {
user:{firstName, lastName, age},
post:{title, subtitle, year},
skills:[skillOne, skillTwo, skillThree, skillFour,
skillFive]
} = props

console.log(`${firstName} codes in ${skillOne} and ${skillTwo}`)

- Destructuring function parameter

let rectangle = {width: 20, lenght; 30}


let CalculateArea = ({width, lenght}) => {width * lenght}
let calculatePerimeter = ({width,lenght} = 2 * (width + lenght))

- Spread Operator to copy an array or Object

const user = {
name: 'Andres',
title: 'Developer',
country: 'Mexico',
city: 'Leon',
}

const copiedUser = { ...user }


console.log(copiedUser)

const frontEnd = ['HTML', 'CSS', 'JS', 'React']


const backEnd = ['Node', 'Express', 'MongoDB']
const fullStack = [...frontEnd, ...backEnd]

console.log(fullStack)
- Spread to modify whiile copying

const user = {
name: 'Andres',
title: 'Programmer',
country: 'Mexico',
city: 'Leon',
}

const copiedUser = { ...user, title: 'Developer' }


console.log(copiedUser)

8. Functional Programming

- Map vs ForEach vs. Reduce vs filter

Map creates a new array, forEach no


Filter creates a new array, forEach no
Reduce returns ONLY one result

- find

Returns the first item of the array that matches the specified
condition, for Example:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


const firstEvenNum = numbers.find((n) => n % 2 === 0)
console.log(firstEvenNum) // 0

- findIndex

Return the index of the FIRST matching item of the array

const numbers = [2, 4, 5, 6, 7, 8, 9, 10]


const firstEvenNum = numbers.find((n) => n % 2 === 0)
console.log(firstEvenNum) // 2

- some

Returns a boolean if one or some of the items satify teh


criteria it will return true, otherwise, false, Example:

const evens = [0, 2, 4, 6, 8, 10]


const someAreEvens = evens.some((n) => n % 2 === 0)
const someAreOdds = evens.some((n) => n % 2 !== 0)
console.log(someAreEvens) // true
console.log(someAreOdds) // false

- every

Similar to some, but every item must satify the criteria to


return true. Example:

const evens = [0, 2, 4, 6, 8, 10]


const allAreEven = evens.every((n) => n % 2 === 0)
console.log(allAreEven) // true
9. Clases

Js is an objkect oriented language, EVERYTHING is an object, to create


an object we create a class. A class is like a blueprint for objects, it
defines attributes and behavior of the object.

Intantiation: Create an object from a class

Rules:

- We instanciate the class ALWAYS type new before the class name

Class Constructor

Is a built-in function that acts like a blueprint for our object


where we define the object properties (within the parenthesis)
and attach them to the class (inside the function using the
keyword this). Example:

class Person {
constructor(firstName, lastName) {
console.log(this) // Check the output from here
this.firstName = firstName
this.lastName = lastName
}
}

const person = new Person('Andres', 'Jacinto')


console.log(person)

Getter/setters

- Getter
Method that allow us to ACCESS a value from the object

- Setter
Method that allow us to DEFINE and EDIT a value from the
object

Inherintance

By inherintance we can access to all attributes and methods


of a parent class from a child class using the keyword extends

Overriding Methods

To access to the attributes and methods of a parent class from a


child class, we type super(attributes to access) inside the
constructor.

We can override methods of the parent class inside the child


class defining them under the same name

You might also like