0% found this document useful (0 votes)
4 views

JS

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JS

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

JAVASCRIPT JOURNAL

Nota: else if (season === 'summer') {


console.log('It\'s sunny and warm because it\'s summer!')

const mensgem = 'Isso é a\n \'primeira\' mensagem';


\n - nova linha/quebra de pagina
\'primeira\' - Fica entre aspas quando se faz o print
----------------------------------------------------//-------------------------------------------------------------
const myPet = 'armadillo';
console.log(`I own a pet ${myPet}.`);
// Output: I own a pet armadillo.
a template literal is wrapped by backticks ` (this key is usually located on the top of
your keyboard, left of the 1 key).
----------------------------------------------------//-------------------------------------------------------------

let myVariable = 'I Exist!';


if (myVariable) {
console.log(myVariable)
} else {
console.log('The variable does not exist.')
}
The code block in the if statement will run because myVariable has a truthy value;
even though the value of myVariable is not explicitly the value true, when used in a
boolean or conditional context, it evaluates to true because it has been assigned a
non-falsy value.
So which values are falsy— or evaluate to false when checked as a condition?

The list of falsy values includes:


0
Empty strings like "" or ''
null which represent when there is no value at all
undefined which represent when a declared variable lacks a value
NaN, or Not a Number
Here’s an example with numbers:

let numberOfApples = 0;
if (numberOfApples){
console.log('Let us eat apples!');
} else {
console.log('No apples left!');
}
// Prints 'No apples left!'
----------------------------------------------------//-------------------------------------------------------------

Check if an Object has a Property


users.hasOwnProperty('Alan');
'Alan' in users;
Both of these would return true.

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'].

Add Items Using splice()


const numbers = [10, 11, 12, 12, 15];
const startIndex = 3;
const amountToDelete = 1;

numbers.splice(startIndex, amountToDelete, 13, 14);


console.log(numbers);

The second occurrence of 12 is removed, and we add 13 and 14 at the same


index. The numbers array would now be [ 10, 11, 12, 13, 14, 15 ].

----------------------------------------------------//-------------------------------------------------------------

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
}

----------------------------------------------------//-------------------------------------------------------------

Global vs. Local Scope in Functions


It is possible to have both local and global variables with the same name. When you do
this, the local variable takes precedence over the global variable.
In this example:
var someVar = "Hat";
function myFun() {
var someVar = "Head";
return someVar;
}
The function myFun will return the string Head because the local version of the
variable is present.

----------------------------------------------------//-------------------------------------------------------------

Add New Properties to a JavaScript Object


You can add new properties to existing JavaScript objects the same way you would
modify them.
Here's how we would add a bark property to ourDog:

ourDog.bark = "bow-wow";
or
ourDog["bark"] = "bow-wow";

Delete Properties from a JavaScript Object


We can also delete properties from objects like this:
delete ourDog.bark;
----------------------------------------------------//-------------------------------------------------------------

Use the Rest Parameter with Function


Parameters
With the rest parameter, you can create functions that take a variable number of
arguments. These arguments are stored in an array that can be accessed later
from inside the function.

function howMany(...args) {
return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2));
console.log(howMany("string", null, [1, 2, 3], { }));

const arr = [6, 89, 3, 45];


const maximus = Math.max(...arr);

maximus would have a value of 89.

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];


let arr2;

arr2 = [...arr1];

console.log(arr2);

Use Destructuring Assignment to Extract Values from Objects


const user = { name: 'John Doe', age: 34 };
const name = user.name;
const age = user.age;

name would have a value of the string John Doe, and age would have the
number 34.

Here's an equivalent assignment statement using the ES6 destructuring


syntax:

const { name, age } = user;

Use Destructuring Assignment to Assign Variables from


Objects

Destructuring allows you to assign a new variable name when extracting


values. You can do this by putting the new name after a colon when
assigning the value.

Using the same object from the last example:

const user = { name: 'John Doe', age: 34 };

Here's how you can give new variable names in the assignment:

const { name: userName, age: userAge } = user;

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:

const { johnDoe: { age, email }} = user;

And here's how you can assign an object properties' values to variables with
different names:

const { johnDoe: { age: userAge, email: userEmail }} =


user

----------------------------------------------------//-------------------------------------------------------------

let a = 8, b = 6;

[a,b] = [b,a];
----------------------------------------------------//-------------------------------------------------------------
Use Destructuring Assignment with the Rest Parameter to
Reassign Array Elements

The result is similar to Array.prototype.slice(), as shown below:

const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];


console.log(a, b);
console.log(arr);

The console would display the values 1, 2 and [3, 4, 5, 7].

const source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];


function removeFirstTwo(list) {
"use strict";

const [a, b, ...arr] = list;


return arr;
}
const arr = removeFirstTwo(source);
console.log(arr); // should be [3,4,5,6,7,8,9,10]
console.log(source); // should be
[1,2,3,4,5,6,7,8,9,10];

Use Destructuring Assignment to Pass an Object as a


Function's Parameters

In some cases, you can destructure the object in a function argument itself.

const profileUpdate = (profileData) => {


const { name, age, nationality, location } =
profileData;
}

This effectively destructures the object sent into the function. This can
also be done in-place:

const profileUpdate = ({ name, age, nationality,


location }) => {
}
When profileData is passed to the above function, the values are
destructured from the function parameter for use within the function.

const stats = {
max: 56.78,
standard_deviation: 4.34,
median: 34.54,
mode: 23.87,
min: -0.75,
average: 35.85
};

const half = ({ max, min }) => (max + min) / 2.0;

----------------------------------------------------//-------------------------------------------------------------
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.

let testStr = "freeCodeCamp";


let testRegex = /Code/;
testRegex.test(testStr);//The test method here returns true.

Match a Literal String with Different


Possibilities
You can search for multiple patterns using the alternation or OR operator: |.

For example, if you wanted to match the strings yes or no, the regex you want
is /yes|no/.

let petString = "James has a pet cat.";


let petRegex = /dog|cat|bird|fish/; // Change this line
let result = petRegex.test(petString);

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);

Find More Than the First Match

So far, you have only been able to extract or search a pattern once.

let testStr = "Repeat, Repeat, Repeat";


let ourRegex = /Repeat/;
testStr.match(ourRegex);

Here match would return ["Repeat"].

To search or extract a pattern more than once, you can use the g flag.

let repeatRegex = /Repeat/g;


testStr.match(repeatRegex);
And here match returns the value ["Repeat", "Repeat", "Repeat"]

let twinkleStar = "Twinkle, twinkle, little star";


let starRegex = /Twinkle/gi; // Change this line
let result = twinkleStar.match(starRegex) // Change
this

Nota: Reparar no /gi, faz com que extraia a variedade da palavra twinkle e que
nao seja case sensitive.

Match Anything with Wildcard Period

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.

let humStr = "I'll hum a song";


let hugStr = "Bear hug";
let huRegex = /hu./;
huRegex.test(humStr);
huRegex.test(hugStr);

Match Single Character with Multiple Possibilities


For example, you want to match bag, big, and bug but not bog. You can
create the regex /b[aiu]g/ to do this. The [aiu] is the character class that
will only match the characters a, i, or u.

let bigStr = "big";


let bagStr = "bag";
let bugStr = "bug";
let bogStr = "bog";
let bgRegex = /b[aiu]g/;
bigStr.match(bgRegex);
bagStr.match(bgRegex);
bugStr.match(bgRegex);
bogStr.match(bgRegex);
In order, the four match calls would return the
values ["big"], ["bag"], ["bug"], and null.

Match Letters of the Alphabet

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].

let catStr = "cat";


let batStr = "bat";
let matStr = "mat";
let bgRegex = /[a-e]at/;
catStr.match(bgRegex);
batStr.match(bgRegex);
matStr.match(bgRegex);
In order, the three match calls would return the values ["cat"], ["bat"],
and null.

Also, it is possible to combine a range of letters and numbers in a set.

let jennyStr = "Jenny8675309";

let myRegex = /[a-z0-9]/ig;


jennyStr.match(myRegex);

Match Single Characters Not Specified


To create a negated character set, you place a caret character (^) after the
opening bracket and before the characters you do not want to match.

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.

let firstString = "Ricky is first and can be found.";


let firstRegex = /^Ricky/;
firstRegex.test(firstString);//true
let notFirst = "You can't find Ricky now.";
firstRegex.test(notFirst);//false

Match Characters that Occur One or More Times

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.

Match Characters that Occur Zero or More Times

The character to do this is the asterisk or star: *.

let soccerWord = "gooooooooal!";


let gPhrase = "gut feeling";
let oPhrase = "over the moon";
let goRegex = /go*/;
soccerWord.match(goRegex);
gPhrase.match(goRegex);
oPhrase.match(goRegex);
In order, the three match calls would return the
values ["goooooooo"], ["g"], and null.

Find Characters with Lazy Matching

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.

The match would return ["titani"].

However, you can use the ? character to change it to lazy


matching. "titanic" matched against the adjusted regex of /t[a-z]*?
i/ returns ["ti"].

Match Ending String Patterns

You can search the end of strings using the dollar sign character $ at the end of
the regex.

let theEnding = "This is a never ending story";


let storyRegex = /story$/;
storyRegex.test(theEnding);
let noEnding = "Sometimes a story will have to end";
storyRegex.test(noEnding);
The first test call would return true, while the second would return false.

Match All Letters and Numbers

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 (_).

let longHand = /[A-Za-z0-9_]+/;


let shortHand = /\w+/;
let numbers = "42";
let varNames = "important_var";
longHand.test(numbers);
shortHand.test(numbers);
longHand.test(varNames);
shortHand.test(varNames);
All four of these test calls would return true.

Match Everything But Letters and Numbers

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_].

let shortHand = /\W/;


let numbers = "42%";
let sentence = "Coding!";
numbers.match(shortHand);
sentence.match(shortHand);
The first match call would return the value ["%"] and the second would
return ["!"].

Match All Numbers

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].

let whiteSpace = "Whitespace. Whitespace everywhere!"


let spaceRegex = /\s/g;
whiteSpace.match(spaceRegex);
This match call would return [" ", " "].

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.

Specify Upper and Lower Number of Matches

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/.

Check for All or None


You can specify the possible existence of an element with a question mark, ?.
This checks for zero or one of the preceding element. You can think of this
symbol as saying the previous element is optional.
let american = "color";
let british = "colour";
let rainbowRegex= /colou?r/;
rainbowRegex.test(american);
rainbowRegex.test(british);
Both uses of the test method would return true.

Positive and Negative Lookahead

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.

let quit = "qu";


let noquit = "qt";
let quRegex= /q(?=u)/;
let qRegex = /q(?!u)/;
quit.match(quRegex);
noquit.match(qRegex);

Both of these match calls would return ["q"].

A more practical use of lookaheads is to check two or more patterns in one


string. Here is a (naively) simple password checker that looks for between 3 and
6 characters and at least one number:

let password = "abc123";


let checkPass = /(?=\w{3,6})(?=\D*\d)/;
checkPass.test(password);

Check For Mixed Grouping of Characters

Sometimes we want to check for groups of characters using a Regular


Expression and to achieve that we use parentheses ().
If you want to find either Penguin or Pumpkin in a string, you can use the
following Regular Expression: /P(engu|umpk)in/g

let testStr = "Pumpkin";


let testRegex = /P(engu|umpk)in/;
testRegex.test(testStr);
The test method here would return true.

Reuse Patterns Using Capture Groups

Say you want to match a word that occurs multiple times like below.

let repeatStr = "row row row your boat";

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.

In this case, the goal is to capture a word consisting of alphanumeric characters


so the capture group will be \w+ enclosed by parentheses: /(\w+)/.

The substring matched by the group is saved to a temporary "variable", which


can be accessed within the same regex using a backslash and the number of
the capture group (e.g. \1). Capture groups are automatically numbered by the
position of their opening parentheses (left to right), starting at 1.

The example below matches a word that occurs thrice separated by spaces:

let repeatRegex = /(\w+) \1 \1/;


repeatRegex.test(repeatStr); // Returns true
repeatStr.match(repeatRegex); // Returns ["row row row",

Use Capture Groups to Search and Replace

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.

let wrongText = "The sky is silver.";


let silverRegex = /silver/;
wrongText.replace(silverRegex, "blue");

The replace call would return the string The sky is blue..
You can also access capture groups in the replacement string with dollar signs
($).

"Code Camp".replace(/(\w+)\s(\w+)/, '$2 $1');


The replace call would return the string Camp Code.

----------------------------------------------------//-------------------------------------------------------------

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.

Write Arrow Functions with Parameters


const doubler = (item) => item * 2;
doubler(4);
doubler(4) would return the value 8.

If an arrow function has a single parameter, the parentheses enclosing the


parameter may be omitted.
const doubler = item => item * 2;
It is possible to pass more than one argument into an arrow function.
const multiplier = (item, multi) => item * multi;
multiplier(4, 2);

Set Default Parameters for Your Functions


In order to help us create more flexible functions, ES6 introduces default parameters
for functions.
const greeting = (name = "Anonymous") => "Hello " + name;
console.log(greeting("John"));
console.log(greeting());
The console will display the strings Hello John and Hello Anonymous.

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):

const timeFuncRuntime = funcParameter => {


let t1 = Date.now();
funcParameter();
let t2 = Date.now();
return t2 - t1;
}
const addOneToOne = () => 1 + 1;

timeFuncRuntime(addOneToOne);

const addTwo = num => num + 2;


const checkConsistentOutput = (func, val) => {
let firstTry = func(val);
let secondTry = func(val);
if (firstTry === secondTry) {
return firstTry
} else {
return 'This function returned inconsistent result
s'
}
};
console.log(checkConsistentOutput(addTwo, 10));

----------------------------------------------------//-------------------------------------------------------------

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}`)
}

The this Keyword


const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet() {
console.log(dietType);
}
};
goat.diet();
// Output will be "ReferenceError: dietType is not
defined"

That’s strange, why is dietType not defined even though it’s a


property of goat? That’s because inside the scope of
the .diet() method, we don’t automatically have access to other
properties of the goat object.

Here’s where the this keyword comes to the rescue. If we change


the .diet() method to use the this, the .diet() works! :

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');
}
}
};

 We can perform a check for what value is being assigned


to this._age.
 When we use the setter method, only values that are numbers
will reassign this._age

Then to use the setter method:

person.age = 40;
console.log(person._age); // Logs: 40
person.age = '40'; // Logs: You must assign a number to
age

Setter methods like age do not need to be called with a set of


parentheses.

Nonetheless, even with a setter method, it is still possible to directly


reassign properties. For example, in the example above, we can still
set ._age directly:
person._age = 'forty-five'
console.log(person._age); // Prints forty-five

Factory Functions

A real world factory manufactures multiple copies of an item


quickly and on a massive scale. A factory function is a function
that returns an object and can be reused to make multiple object
instances.

const monsterFactory = (name, age, energySource,


catchPhrase) => {
return {
name: name,
age: age,
energySource: energySource,
scare() {
console.log(catchPhrase);
}
}
};

const ghost = monsterFactory('Ghouly', 251, 'ectoplasm',


'BOO!');
ghost.scare(); // 'BOO!'

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'

const { residence } = vampire;


console.log(residence); // Prints 'Transylvania'

const { day } = vampire.preferences;


console.log(day); // Prints 'stay inside'

Examples
Using Object.keys
// simple array

const arr = ['a', 'b', 'c'];

console.log(Object.keys(arr)); // console: ['0', '1', '2']


// array-like object

const obj = { 0: 'a', 1: 'b', 2: 'c' };

console.log(Object.keys(obj)); // console: ['0', '1', '2']

// array-like object with random key ordering

const anObj = { 100: 'a', 2: 'b', 7: 'c' };

console.log(Object.keys(anObj)); // console: ['2', '7', '100']

OBJECT.ENTRIES()
const obj = { foo: 'bar', baz: 42 };

console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

// array like object

const obj = { 0: 'a', 1: 'b', 2: 'c' };

console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2',


'c'] ]

// array like object with random key ordering

const anObj = { 100: 'a', 2: 'b', 7: 'c' };

console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'],


['100', 'a'] ]
Cloning an object
const obj = { a: 1 };

const copy = Object.assign({}, obj);

console.log(copy); // { a: 1 }

const newRobot = Object.assign({laserBlaster : true, voiceRecognition


: true}, robot);

NOTA: O que está entre {} [e acrescentado ao objecto


----------------------------------------------------//-------------------------------------------------------------

ITERATORS

The .forEach() Method


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

fruits.forEach(fruitsList =>
console.log('I want to eat a ' + fruitsList));
//OU
fruits.forEach(function(fruitsList) {
console.log('I want to eat a ' + fruitsList)
})

The .map() Method


const numbers = [1, 2, 3, 4, 5];

const bigNumbers = numbers.map(number => {


return number * 10;
});

 numbers.map will iterate through each element in


the numbers array and pass the element into the callback
function.

console.log(numbers); // Output: [1, 2, 3, 4, 5]


console.log(bigNumbers); // Output: [10, 20, 30, 40,
50]

The .filter() Method


The elements that cause the callback function to return true are
added to the new array.

const words = ['chair', 'music', 'pillow', 'brick', 'pen',


'door'];

const shortWords = words.filter(word => {


return word.length < 6;
});
console.log(words); // Output: ['chair', 'music',
'pillow', 'brick', 'pen', 'door'];
console.log(shortWords); // Output: ['chair', 'music',
'brick', 'pen', 'door']

The .findIndex() Method


Calling .findIndex() on an array will return the index of the
first element that evaluates to true in the callback function.

const jumbledNums = [123, 25, 78, 5, 9];

const lessThanTen = jumbledNums.findIndex(num => {


return num < 10;
});
console.log(lessThanTen); // Output: 3

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.

const greaterThan1000 = jumbledNums.findIndex(num => {


return num > 1000;
});

console.log(greaterThan1000); // Output: -1

The .reduce() Method


The .reduce() method returns a single value after iterating
through the elements of an array, thereby reducing the array.

const numbers = [1, 2, 4, 10];

const summedNums = numbers.reduce((accumulator,


currentValue) => {
return accumulator + currentValue
})

console.log(summedNums) // Output: 17

Iteration accumulator currentValue return value


First 1 2 3
Second 3 4 7
Third 7 10 17
The .reduce() method can also take an optional second
parameter to set an initial value for accumulator (remember,
the first argument is the callback function!). For instance:
const numbers = [1, 2, 4, 10];

const summedNums = numbers.reduce((accumulator,


currentValue) => {
return accumulator + currentValue
}, 100) // <- Second argument for .reduce()

console.log(summedNums); // Output: 117

Iteration # accumulator currentValue return value


First 100 1 101
Second 101 2 103
Third 103 4 107
Fourth 107 10 117
const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra'
, 'Denver', 'Eskisehir', 'Medellin', 'Yokohama'];

const word = cities.reduce((acc, currVal) => {


return acc + currVal[0]
}, "C");
console.log(word)

THE SOME() METHOD


The some() method tests whether at least one element in the array passes the
test implemented by the provided function. It returns true if, in the array, it
finds an element for which the provided function returns true; otherwise
it returns false. It doesn't modify the array.

const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];


// Something is missing in the method call below
console.log(words.some((word) => {
return word.length < 6;
}));

THE EVERY() METHOD


The every() method tests whether all elements in the array pass the test
implemented by the provided function. It returns a Boolean value.

const interestingWords = words.filter(word => {


return word.length > 5
})
console.log(interestingWords.every((word) => {
return word.length > 5
} ));

----------------------------------------------------//-------------------------------------------------------------

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.

Below, we use a instance to call the class Dog

const halley = new Dog('Halley');


console.log(halley.name); // Print name value to console
console.log(halley.behavior); // Print behavior value to console
halley.incrementBehavior(); // Add one to behavior
console.log(halley.name); // Print name value to console
console.log(halley.behavior); // Print behavior value to console

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.

 Dog is the name of our class. By convention, we capitalize


and CamelCase class names.
 Inside of the constructor() method, we use the this keyword.
In the context of a class, this refers to an instance of that
class. In the Dog class, we use this to set the value of the
Dog instance’s name property to the name argument.

Class method and getter syntax is the same as it is for


objects except you can not include commas between
methods.

Notice, we also prepended our property names with


underscores (_name and _behavior), which indicate these
properties should not be accessed directly.

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++;
}
}

In the example above, the Animal class contains the


properties and methods that the Cat and Dog classes share
(name, behavior, .incrementBehavior()).

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.

class Cat extends Animal {


constructor(name, usesLitter) {
super(name);
this._usesLitter = usesLitter;
}
}

 The extends keyword makes the methods of the animal class


available inside the cat class.
 The super keyword calls the constructor of the parent
class. In this case, super(name) passes the name argument of
the Cat class to the constructor of the Animal class. When
the Animal constructor runs, it sets this._name =
name; for new Cat instances.
 _usesLitter is a new property that is unique to
the Cat class, so we set it in the Cat constructor.

Notice, we call super on the first line of our constructor(),


then set the usesLitter property on the second line. In
a constructor(), you must always call the super method
before you can use the this keyword — if you do not,
JavaScript will throw a reference error.

Below, we create a new Cat instance and call its name with the same
syntax as we did with the Dog class:

const bryceCat = new Cat('Bryce', false);


console.log(bryceCat._name); // output: Bryce

Inheritance IV
As a result, the Cat class has access to the Animal getters and
the .incrementBehavior() method.

Also in the code above, we create a Cat instance named bryceCat.


Because bryceCat has access to the name getter, the code
below logs 'Bryce' to the console.

console.log(bryceCat.name);
Inheritance V

In addition to the inherited features, child classes can contain


their own properties, getters, setters, and methods.

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.

class Cat extends Animal {


constructor(name, usesLitter) {
super(name);
this._usesLitter = usesLitter;
}
get usesLitter() {
return this._usesLitter;
}
}

One benefit is that when you need to change a method or property


that multiple classes share, you can change the parent class,
instead of each subclass.

STATIC METHODS

Take the Date class, for example — you can both


create Date instances to represent whatever date you want, and
call static methods, like Date.now() which returns the current date,
directly from the class. The .now() method is static, so you can
call it directly from the class, but not from an instance of the
class.
Let’s see how to use the static keyword to create a static method
called generateName method in our Animal class:

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];
}
}

In the example above, we create a static method


called .generateName() that returns a random name when it’s called.
Because of the static keyword, we can only
access .generateName() by appending it to the Animal class.

We call the .generateName() method with the following syntax:

console.log(Animal.generateName()); // returns a name

You cannot access the .generateName() method from instances


of the Animal class or instances of its subclasses (See below).

const tyson = new Animal('Tyson');


tyson.generateName(); // TypeError

----------------------------------------------------//-------------------------------------------------------

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;

return square(a) + square(b);

}
a = addSquares(2,3); // retorna 13

b = addSquares(3,4); // retorna 25

c = addSquares(4,5); // retorna 41

function Carro(marca, modelo, ano) {

this.marca = marca;

this.modelo = modelo;

this.ano = ano;

var meucarro = new Carro("Eagle", "Talon TSi", 1993);

Definindo getters e setters

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

Conditional operator ‘?’

let accessAllowed;
let age = prompt('How old are you?', '');

if (age > 18) {


accessAllowed = true;
} else {
accessAllowed = false;
}
alert(accessAllowed);
let accessAllowed = (age > 18) ? true : false;

----------------------------------------------------//-------------------------------------------------------------
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}`
}

SLEEP DEBT CALCULATOR


const getSleepHours = (day) => {
switch(day) {
case 'monday':
return 8;
break;
case 'tuesday':
return 8;
break;
case 'wednesday':
return 7;
break;
case 'thursday':
return 8;
break;
case 'friday':
return 6;
break;
case 'saturday':
return 9;
break;
case 'sunday':
return 7;
break;
}
}
const getActualSleepHours = () => {
return getSleepHours('monday') + getSleepHours('tuesday') +
getSleepHours('wednesday') + getSleepHours('thursday') +
getSleepHours('friday') + getSleepHours('saturday') +
getSleepHours('sunday')
}

const getIdealSleepHours = () => {


const idealHours = 8;
return idealHours * 7;
}
const calculateSleepDebt = () => {
const actualSleepHours = getActualSleepHours();
const idealSleepHours = getIdealSleepHours();

if(actualSleepHours === idealSleepHours) {


console.log(`You got the perfect ${actualSleepHours}hours of
sleep`)
} else if(actualSleepHours > idealSleepHours) {
console.log(`You sleep more ${actualSleepHours -
idealSleepHours} than you used to`)
} else {
console.log(`You should rest ${idealSleepHours -
actualSleepHours} more hours`)
}
};

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.'

const unnecessaryWords = ['precisa', 'entendido', 'conhecimentos'];


const overusedWords = ['ideias', 'texto', 'ainda']
const storyWords = story.split(' ')

console.log(storyWords.length)

const betterWords = storyWords.filter(word => {


for(let i =0; i <unnecessaryWords.length; i++) {
if(!unnecessaryWords[i].includes(word)) {
return word
}
}
})
console.log(betterWords.length)
const checkOverused = (arr1, arr2) => {
let count = 0;
arr1.forEach(element => {
for(let j = 0; j< arr2.length; j++) {
if(element === arr2[j]) {
count++;
}
}
})
return count
}
checkOverused(betterWords, overusedWords)

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));

Return Largest Numbers in Arrays

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]]));

Slice and Splice


frankenSplice([1, 2, 3], [4, 5], 1) should return [4, 1, 2,
3, 5].

function frankenSplice(arr1, arr2, n) {


let localArr = arr2.slice()
localArr.splice(n, 0, ...arr1)
return localArr
}

You might also like