JS
JS
let numberOfApples = 0;
if (numberOfApples){
console.log('Let us eat apples!');
} else {
console.log('No apples left!');
}
// Prints 'No apples left!'
----------------------------------------------------//-------------------------------------------------------------
let users = {
Alan: {
age: 27,
online: true
},
Jeff: {
age: 32,
online: true
},
Sarah: {
age: 48,
online: true
},
Ryan: {
age: 19,
online: true
}
};
function isEveryoneHere(userObj) {
// Only change code below this line
if(
userObj.hasOwnProperty('Alan') &&
userObj.hasOwnProperty('Jeff') &&
userObj.hasOwnProperty('Sarah') &&
userObj.hasOwnProperty('Ryan')) {
return true
} else {
return false
}
// Only change code above this line
}
console.log(isEveryoneHere(users));
OU
function isEveryoneHere(userObj) {
return ["Alan", "Jeff", "Sarah", "Ryan"].every(name =>
userObj.hasOwnProperty(name)
)};
----------------------------------------------------//-------------------------------------------------------------
SPLICE
let array = ['today', 'was', 'not', 'so', 'great'];
array.splice(2, 2);
Here we remove 2 elements, beginning with the third element (at index 2). array
would have the value ['today', 'was', 'great'].
splice() not only modifies the array it's being called on, but it also returns a new array
containing the value of the removed elements:
let array = ['I', 'am', 'feeling', 'really', 'happy'];
let newArray = array.splice(3, 2);
newArray has the value ['really', 'happy'].
----------------------------------------------------//-------------------------------------------------------------
REPLACE
let txt = "Hello World";
txt = txt.replace("Hello", "Welcome");
----------------------------------------------------//-------------------------------------------------------------
FOR IN
for (let user in users) {
console.log(user);
}
This would log Alan, Jeff, Sarah, and Ryan - each value on its own
line.
{
Alan: {
online: false
},
Jeff: {
online: true
},
Sarah: {
online: false
}
}
function countOnline(usersObj) {
let onlineUsers = 0
for( let users in usersObj) {
if(usersObj[users].online === true) {
onlineUsers++
}
}
return onlineUsers
}
----------------------------------------------------//-------------------------------------------------------------
----------------------------------------------------//-------------------------------------------------------------
ourDog.bark = "bow-wow";
or
ourDog["bark"] = "bow-wow";
function howMany(...args) {
return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2));
console.log(howMany("string", null, [1, 2, 3], { }));
arr2 = [...arr1];
console.log(arr2);
name would have a value of the string John Doe, and age would have the
number 34.
Here's how you can give new variable names in the assignment:
You may read it as "get the value of user.name and assign it to a new variable
named userName" and so on. The value of userName would be the
string John Doe, and the value of userAge would be the number 34.
const user = {
johnDoe: {
age: 34,
email: '[email protected]'
}
};
Here's how to extract the values of object properties and assign them to
variables with the same name:
And here's how you can assign an object properties' values to variables with
different names:
----------------------------------------------------//-------------------------------------------------------------
let a = 8, b = 6;
[a,b] = [b,a];
----------------------------------------------------//-------------------------------------------------------------
Use Destructuring Assignment with the Rest Parameter to
Reassign Array Elements
In some cases, you can destructure the object in a function argument itself.
This effectively destructures the object sent into the function. This can
also be done in-place:
const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85
};
----------------------------------------------------//-------------------------------------------------------------
Using the Test Method(REGEX)
If you want to find the word the in the string The dog chased the cat, you
could use the following regular expression: /the/. Notice that quote marks are
not required within the regular expression.
One way to test a regex is using the .test() method. The .test() method
takes the regex, applies it to a string (which is placed inside the parentheses),
and returns true or false if your pattern finds something or not.
For example, if you wanted to match the strings yes or no, the regex you want
is /yes|no/.
You can match both cases using what is called a flag. There are other
flags but here you'll focus on the flag that ignores case - the i flag. You
can use it by appending it to the regex. An example of using this flag
is /ignorecase/i.
Extract Matches
To use the .match() method, apply the method on a string and pass in the
regex inside the parentheses.
"Hello, World!".match(/Hello/);
let ourStr = "Regular expressions";
let ourRegex = /expressions/;
ourStr.match(ourRegex);
So far, you have only been able to extract or search a pattern once.
To search or extract a pattern more than once, you can use the g flag.
Nota: Reparar no /gi, faz com que extraia a variedade da palavra twinkle e que
nao seja case sensitive.
The wildcard character . will match any one character. For example, if you
wanted to match hug, huh, hut, and hum, you can use the regex /hu./ to
match all four words.
Inside a character set, you can define a range of characters to match using a
hyphen character: -.
For example, to match lowercase letters a through e you would use [a-e].
For example, /[^aeiou]/gi matches all characters that are not a vowel.
OR
Outside of a character set, the caret is used to search for patterns at the
beginning of strings.
You can use the + character to check if that is the case. Remember, the
character or pattern has to be present consecutively. That is, the character has
to repeat one after the other.
For example, /a+/g would find one match in abc and return ["a"].
Because of the +, it would also find a single match in aabc and
return ["aa"].
If it were instead checking the string abab, it would find two matches and
return ["a", "a"] because the a characters are not in a row - there is
a b between them. Finally, since there is no a in the string bcd, it wouldn't find a
match.
You can apply the regex /t[a-z]*i/ to the string "titanic". This regex is
basically a pattern that starts with t, ends with i, and has some letters in
between.
You can search the end of strings using the dollar sign character $ at the end of
the regex.
The closest character class in JavaScript to match the alphabet is \w. This
shortcut is equal to [A-Za-z0-9_]. This character class matches upper
and lowercase letters plus numbers. Note, this character class also includes
the underscore character (_).
You can search for the opposite of the \w with \W. Note, the opposite pattern
uses a capital letter. This shortcut is the same as [^A-Za-z0-9_].
The shortcut to look for digit characters is \d, with a lowercase d. This is
equal to the character class [0-9].
let movieName = "2001: A Space Odyssey";
let numRegex = /\d/; // Change this line
let result = movieName.match(numRegex).length;
The shortcut to look for non-digit characters is \D. This is equal to the
character class [^0-9], which looks for a single character that is not a
number between zero and nine.
Match Whitespace
You can search for whitespace using \s, which is a lowercase s. This pattern
not only matches whitespace, but also carriage return, tab, form feed, and new
line characters. You can think of it as similar to the character class [ \r\t\f\
n\v].
Search for non-whitespace using \S, which is an uppercase s. This pattern will
not match whitespace, carriage return, tab, form feed, and new line characters.
You can think of it being similar to the character class [^ \r\t\f\n\v].
let whiteSpace = "Whitespace. Whitespace everywhere!"
let nonSpaceRegex = /\S/g;
whiteSpace.match(nonSpaceRegex).length;
The value returned by the .length method would be 32.
Recall that you use the plus sign + to look for one or more characters and
the asterisk * to look for zero or more characters. You can specify the lower
and upper number of patterns with quantity specifiers. Quantity specifiers are
used with curly brackets ({ and }). You put two numbers between the curly
brackets - for the lower and upper number of patterns.
For example, to match only the letter a appearing between 3 and 5 times
in the string ah, your regex would be /a{3,5}h/.
let A4 = "aaaah";
let A2 = "aah";
let multipleA = /a{3,5}h/;
multipleA.test(A4);
multipleA.test(A2);
The first test call would return true, while the second would return false.
For example, to match only the string hah with the letter a appearing at
least 3 times, your regex would be /ha{3,}h/.
let A4 = "haaaah";
let A2 = "haah";
let A100 = "h" + "a".repeat(100) + "h";
let multipleA = /ha{3,}h/;
multipleA.test(A4);
multipleA.test(A2);
multipleA.test(A100);
In order, the three test calls would return true, false, and true.
For example, to match only the word hah with the letter a 3 times,
your regex would be /ha{3}h/.
A positive lookahead will look to make sure the element in the search pattern is
there, but won't actually match it. A positive lookahead is used as (?
=...) where the ... is the required part that is not matched.
A negative lookahead will look to make sure the element in the search pattern is
not there. A negative lookahead is used as (?!...) where the ... is the
pattern that you do not want to be there. The rest of the pattern is returned if the
negative lookahead part is not present.
Say you want to match a word that occurs multiple times like below.
You could use /row row row/, but what if you don't know the specific word
repeated? Capture groups can be used to find repeated substrings.
The example below matches a word that occurs thrice separated by spaces:
You can search and replace text in a string using .replace() on a string. The
inputs for .replace() is first the regex pattern you want to search for. The
second parameter is the string to replace the match or a function to do
something.
The replace call would return the string The sky is blue..
You can also access capture groups in the replacement string with dollar signs
($).
----------------------------------------------------//-------------------------------------------------------------
Arrow Functions
const myFunc = function() {
const myVar = "value";
return myVar;
}
const myFunc = () => {
const myVar = "value";
return myVar;
}
When there is no function body, and only a return value, arrow function syntax
allows you to omit the keyword return as well as the brackets surrounding the code.
This helps simplify smaller functions into one-line statements:
const myFunc = () => "value";
This code will still return the string value by default.
HIGHER-ORDER FUNCTIONS/CALLBACKS
Higher-order functions are functions that accept other functions as
arguments and/or return functions as output. This enables us to build
abstractions on other abstractions, just like “We hosted a birthday
party” is an abstraction that may build on the abstraction “We made
a cake.”
When we pass a function in as an argument to another
function, we don’t invoke it. Invoking the function would
evaluate to the return value of that function call. With
callbacks, we pass in the function itself by typing the function
name without the parentheses (that would evaluate to the
result of calling the function):
timeFuncRuntime(addOneToOne);
----------------------------------------------------//-------------------------------------------------------------
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 crewRoles in spaceship.crew) {
console.log(`${crewRoles} : ${spaceship.crew[crewRoles].name}`)
}
for (let crewNames in spaceship.crew) {
console.log(`${spaceship.crew[crewNames].name} : $
{spaceship.crew[crewNames].degree}`)
}
const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet() {
console.log(this.dietType);
}
};
goat.diet();
// Output: herbivore
In the example above, the calling object is goat and by
using this we’re accessing the goat object itself, and then
the dietType property of goat by using property dot notation.
const robot = {
model : '1E78V2',
energyLevel : 100,
provideInfo () {
return `I am ${this.model} and my current energy level is $
{this.energyLevel}`
}
};
console.log(robot.provideInfo())
NOTE : The key takeaway from the example above is
to avoid using arrow functions when using this in a method!
Privacy
One common convention is to place an underscore _ before the name
of a property to mean that the property should not be altered. Here’s
an example of using _ to prepend a property.
const bankAccount = {
_amount: 1000
}
Getters
Getters are methods that get and return the internal properties of an
object. But they can do more than just retrieve the value of a
property!
const person = {
_firstName: 'John',
_lastName: 'Doe',
get fullName() {
if (this._firstName && this._lastName){
return `${this._firstName} ${this._lastName}`;
} else {
return 'Missing a first name or a last name.';
}
}
}
// To call the getter method:
person.fullName; // 'John Doe'
In the last line we call fullName on person. In general, getter
methods do not need to be called with a set of parentheses.
Another thing to keep in mind when using getter (and setter) methods
is that properties cannot share the same name as the getter/setter
function. If we do so, then calling the method will result in an infinite
call stack error. One workaround is to add an underscore before the
property name like we did in the example above.
Setters
Along with getter methods, we can also create setter methods which
reassign values of existing properties within an object.
const person = {
_age: 37,
set age(newAge){
if (typeof newAge === 'number'){
this._age = newAge;
} else {
console.log('You must assign a number to age');
}
}
};
person.age = 40;
console.log(person._age); // Logs: 40
person.age = '40'; // Logs: You must assign a number to
age
Factory Functions
Destructured Assignment
We often want to extract key-value pairs from objects and save them
as variables.
const vampire = {
name: 'Dracula',
residence: 'Transylvania',
preferences: {
day: 'stay inside',
night: 'satisfy appetite'
}
};
const residence = vampire.residence;
console.log(residence); // Prints 'Transylvania'
Examples
Using Object.keys
// simple array
OBJECT.ENTRIES()
const obj = { foo: 'bar', baz: 42 };
console.log(copy); // { a: 1 }
ITERATORS
fruits.forEach(fruitsList =>
console.log('I want to eat a ' + fruitsList));
//OU
fruits.forEach(function(fruitsList) {
console.log('I want to eat a ' + fruitsList)
})
console.log(jumbledNums[3]); // Output: 5
If there isn’t a single element in the array that satisfies the
condition in the callback, then .findIndex() will return -1.
console.log(greaterThan1000); // Output: -1
console.log(summedNums) // Output: 17
----------------------------------------------------//-------------------------------------------------------------
Classes
class Dog {
constructor(name) {
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior ++;
}
}
Instead of using the syntax above for every dog that joins the
daycare, we can create a Dog class that serves as a template for
creating new Dog objects. As you can see, classes are a great
way to reduce duplicate code and debugging time.
Constructor
Although you may see similarities between class and object syntax,
It’s called the constructor method. JavaScript calls
the constructor() method every time it creates a new instance of
a class.
EXERCICIO CODECADEMY:
class Surgeon {
constructor(name, department) {
this._name = name;
this._department = department;
this._remainingVacationDays = 20;
}
get name() {
return this._name;
}
get department() {
return this._department;
}
get remainingVacationDays() {
return this._remainingVacationDays;
}
takeVacationDays(daysOff) {
this._remainingVacationDays -= daysOff;
}
}
const surgeonRomero = new Surgeon('Francisco Romero', 'Cardiovascul
ar');
const surgeonJackson = new Surgeon('Ruth Jackson', 'Orthopedics');
console.log(surgeonRomero.name);
surgeonRomero.takeVacationDays(3);
console.log(surgeonRomero.remainingVacationDays);
EXERCICIO
class Thermostat {
constructor(fahrenheit) {
this.fahrenheit = fahrenheit;
}
get temperature() {
return (5 / 9) * (this.fahrenheit - 32);
}
set temperature(celsius) {
this.fahrenheit = (celsius * 9.0) / 5 + 32;
}
}
const thermos = new Thermostat(76); // Setting in
Fahrenheit scale
let temp = thermos.temperature; // 24.44 in Celsius
thermos.temperature = 26;
temp = thermos.temperature; // 26 in Celsius
----------------------------------------------------//-------------------------------------------------------------
Inheritance I
When multiple classes share properties or methods, they become
candidates for inheritance — a tool developers use to decrease
the amount of code they need to write.
With inheritance, you can create a parent class (also known
as a superclass) with properties and methods that
multiple child classes (also known as subclasses) share. The
child classes inherit the properties and methods from their parent
class.
class Animal {
constructor(name) {
this._name = name;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
incrementBehavior() {
this._behavior++;
}
}
Inheritance II
The code below shows the Cat class that will inherit information from
the Animal class.
class Cat {
constructor(name, usesLitter) {
this._name = name;
this._usesLitter = usesLitter;
this._behavior = 0;
}
get name() {
return this._name;
}
get behavior() {
return this._behavior;
}
get usesLitter() {
return this._usesLitter;
}
incrementBehavior() {
this._behavior++;
}
}
Inheritance III
Now that we have these shared properties and methods in the
parent Animal class, we can extend them to the subclass, Cat.
Below, we create a new Cat instance and call its name with the same
syntax as we did with the Dog class:
Inheritance IV
As a result, the Cat class has access to the Animal getters and
the .incrementBehavior() method.
console.log(bryceCat.name);
Inheritance V
Below, we will add a usesLitter getter. The syntax for creating getters,
setters, and methods is the same as it is in any other class.
STATIC METHODS
class Animal {
constructor(name) {
this._name = name;
this._behavior = 0;
}
static generateName() {
const names = ['Angel', 'Spike', 'Buffy', 'Willow',
'Tara'];
const randomNumber = Math.floor(Math.random()*5);
return names[randomNumber];
}
}
----------------------------------------------------//-------------------------------------------------------
EX 54
function getValidPassword(loggedPasscodes) {
let codes = [];
for (let i = 0; loggedPasscodes.length > i; i++) {
let passcode = loggedPasscodes[i];
let temImpar = false;
for (let j = 0; passcode.length > j; j++) {
if (passcode[j] % 2 !== 0) { // ímpar
temImpar = true;
// se encontrou um ímpar, sai do loop (não precisa verificar os demais
números)
break;
}
}
if (! temImpar) {
codes.push(passcode); // não tem ímpar, adiciona nos resultados
}
}
return codes;
};
let loggedPasscodes =[
[1, 4, 4, 1],
[1, 2, 3, 1],
[2, 6, 0, 8],
[5, 5, 5, 5],
[10, 2, 4, 42],
[4, 3, 4, 3]
];
OU
var getValidPassword = function (array) {
var x = [];
var temp = [];
for (var i in array) {
for (var j in array[i]) {
if (array[i][j] % 2 !== 0) {
break;
} else {
temp.push(array[i][j]);
}
if(temp.length == array[i].length)
x = temp.slice();
}
}
return x;
};
var loggedPasscodes = [
[1, 4, 4, 1],
[1, 2, 3, 1],
[2, 6, 0, 8],
[5, 5, 5, 5],
[4, 3, 4, 3]
];
console.log(getValidPassword(loggedPasscodes));
OU
function getValidPassword(loggedPasscodes) {
return loggedPasscodes.filter(passcode => passcode.every(n => n % 2 === 0));
};
function addSquares(a,b) {
function square(x) {
return x * x;
}
a = addSquares(2,3); // retorna 13
b = addSquares(3,4); // retorna 25
c = addSquares(4,5); // retorna 41
this.marca = marca;
this.modelo = modelo;
this.ano = ano;
var o = {
a: 7,
get b() {
return this.a + 1;
},
set c(x) {
this.a = x / 2
};
console.log(o.a); // 7
console.log(o.b); // 8
o.c = 50;
console.log(o.a); // 25
console.log(o.b); // 26
let accessAllowed;
let age = prompt('How old are you?', '');
----------------------------------------------------//-------------------------------------------------------------
function processData(myArray) {
var max = myArray[0];
var secondMax;
for(var i=1; i<myArray.length; i++){
if(myArray[i]>max){
secondMax = max;
max = myArray[i];
}else if(myArray[i]>secondMax && myArray[i]<max){
secondMax = myArray[i];
}
}
console.log(secondMax);
}
----------------------------------------------------//-------------------------------------------------------------
DATE TYPES
const howOld = (age, year) => {
let dateToday = new Date();
let thisYear = dateToday.getFullYear();
const yearDifference = year - thisYear
const newAge = age + yearDifference
if (newAge > age) {
return `You will be ${newAge} in the year ${year}`
} else if (newAge < 0) {
return `The year ${year} was ${-newAge} years before you we
re born`
} else {
return `You were ${newAge} in the year ${year}`
}
calculateSleepDebt()
ITERATORS PROJECT
let story = 'Em linguística, a noção de texto é ampla e ainda
aberta a uma definição de ideias mais precisa. Grosso modo! Pode
ser entendido como manifestação linguística das ideias de um autor,
que serão interpretadas ainda pelo leitor de acordo com seus
conhecimentos linguísticos e ainda culturais. Seu tamanho de texto
é variável.'
console.log(storyWords.length)
Chunky Monkey
function chunkArray(arr, size) {
let newArr = [];
for (let i = 0; i < arr.length; i += size) {
newArr.push(arr.slice(i, i + size));
}
return newArr;
}
console.log(chunkArray(["a", "b", "c", "d"], 2));
function largestOfFour(arr) {
let newArr = []
for(let i = 0; i< arr.length; i++) {
let largestNum = arr[i][0]
for(let j = 0; j< arr[i].length; j++) {
if(arr[i][j] > largestNum) {
largestNum = arr[i][j]
}
}
newArr.push(largestNum)// results[i] = largestNumber;
}
return newArr;
}
console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26],
[32, 35, 37, 39], [1000, 1001, 857, 1]]));