Learn JavaScript Flashcards

1
Q

How can you access a specific character in a string?

A

const language = “JavaScript”;

language[0]; //first character
language[ language.length - 1 ]; //last character

OR

language.at(-1);
The primary use case for the .at() method is negative indices, making it easier than relying on the .length property. However, you can use whichever approach you prefer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the output of
a. language.substring(1, 4);
b. language.substring(4);
if const language = “JavaScript”;?

A

a. console.log(‘ava’)
b. console.log(‘Script’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is interpolation?

A

This means you could write a variable in your string, and get its value. You wrap your variable name with a dollar sign and curly braces.

Example: let language = “JavaScript”;
I am learning ${language};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to convert from a string to a number?
eg: let str = “42”;

A

Number.parseInt(str, 10); //42
(Number.parseInt(string, radix))

The radix is the base of the numerical system that you’d like to use. For most use cases the radix you’d like to use is 10 which represents the way we count numbers in our everyday lives. This system is called the decimal system (because we have 10 fingers, so we use the digits from 0 to 9).

Another example of radix is 2 which represents binary (a numerical system used by computers).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What scope are let, const and var?

A

let and const are ‘block scoped’ but var is ‘function scoped’, meaning it will be accessible anywhere inside the nearest function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why can we push new data into arrays even if they’re defined with const?

A

Because const doesn’t mean that the variable is immutable. It’s content can change. However, it will always be an array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What’s the basic definition of a callback function?

A

It’s a function definition passed as an argument to another function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Where do you place the return true?

Would it be:

function logUserIds(userIds) {
userIds.forEach(function(userId) {
console.log(userId);
return true; // does this work as expected?
});
}
or:

function logUserIds(userIds) {
userIds.forEach(function(userId) {
console.log(userId);
});
return true; // or is this the correct way?
}

A

The second.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the difference between .filter() and .find()?

A

The .filter() method always returns an array.
The .find() method returns the first array item that matches the callback function or undefined.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is an object?

A

An object is a data type that allows you to group several variables together into one variable that contains keys and values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the benefits of arrow functions?

A
  • It’s shorter to write.
  • It uses lexical scope (this will be explained in a later chapter as we need to learn about classes first).
  • It can benefit from implicit return (covered in the next chapter).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you empty an array?

A

You can do that by setting its length to 0:

const items = [“Pen”, “Paper”];
items.length = 0;

console.log(items); // []

Also, .splice(0)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Use splice to:
- Delete first element of array
- Delete 3 elements starting from the 2nd position of array
- Delete all buy first element from array

A
  • To delete the 1st element of an array, you call .splice(0, 1).
  • To delete 3 elements starting from the 2nd position, you call .splice(1, 3).
  • If you call .splice(1), then it will remove all the items starting from the 2nd position (index 1).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does reduce do?

A

The reduce() method is used to calculate a single value from an array. In other terms, you reduce an array into a single value.

So is the reduce method a sum or a multiplication?
It’s neither. That’s because the reduce() method accepts the reducer which is a callback that you have to write. That callback can be sum, multiplication, or some other logic that you may think of.

So reduce is a generic function that will reduce an array into a single value. The way it will reduce that array into a single value is configurable by you, the developer. You can configure that in the reducer callback.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you identify array destructuring?

A

You can identify destructuring when you see the square brackets [] on the left side of the equal sign.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you identify array destructuring?

A

You can identify destructuring when you see the square brackets [] on the left side of the equal sign.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How can you concatenate/merge several arrays’ content into a new array?

A

You can concatenate/merge several arrays’ content into a new array using the … spread syntax.

const lat = [5.234];
const lng = [1.412];
const point = […lat, …lng];
console.log(point); // [5.234, 1.412];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

const user = {
id: 1,
name: “Sam Green”,
age: 20
};

const key = “id”;
user[key]; // 1

The example above uses dynamic properties. This looks overcomplicated, but what’s a good use of this?

A

const getValue = (user, keyToRead) => {
return user[keyToRead];
}

// Sample usage
getValue({id: 2, name: “Sam”}, “name”); // “Sam”
getValue({id: 2, name: “Sam”}, “id”); // 2

In this case, getValue accepts an object user and then the keyToRead. So, to be able to implement the function, we had to access the property dynamically with user[keyToRead].
This allows the function to be dynamic and accept any key on the user object, and its value will be returned!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How can you return an array of all the keys on an object?

A

const user = {
id: 1,
name: “Sam Green”,
age: 20
};

const keys = Object.keys(user);
console.log(keys); // [“id”, “name”, “age”]

Note that we have Object here, which is a global variable available in JavaScript. It is similar to Number on which we called Number.parseInt() before.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Dynamically log the keys of the following object:

const settings = {
theme: “Dark”,
version: “2.4.1”,
beta: false
};

A

const settings = {
theme: “Dark”,
version: “2.4.1”,
beta: false
};

const keys = Object.keys(settings);
console.log(keys); // [“theme”, “version”, “beta”]
keys.forEach(key => {
// log the value of every key dynamically
console.log(settings[key]);
});

“Dark”
“2.4.1”
false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

When can’t you use dot notation?

A

You cannot use the dot syntax when the property you’re trying to read is stored in a variable or the result of an expression (dynamic).

Instead, you should use square brackets with the name of the variable inside. For example [key].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What does [object Object] mean?

A

It means that the .toString() method has been automatically called on an object which will result in [object Object].

For example:
const person = {
id: 1,
firstName: “Sam”
};
console.log(Hello ${person}); // “Hello [object Object]”

In this case, we should probably replace ${person} with ${person.firstName}.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How do you make an array of the values of an object?

A

const user = {
id: 1,
name: “Sam Green”,
age: 20
};

const values = Object.values(user);
console.log(values); // [1, “Sam Green”, 20]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do you get the key/value pairs from an object?

A

const user = {
id: 1,
name: “Sam Green”,
age: 20
};

const entries = Object.entries(user);
The entries variable will return the following array of arrays:
[
[“id”, 1],
[“name”, “Sam Green”],
[“age”, 20]
]

This is especially useful in combination with for..in and array destructuring which is covered in a later chapter.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

a. What happens if you access a property that does not exist on an object?
b. What happens if you try to access a property or call a method on this?

A

a. When you access a property that does not exist on an object, you will get undefined.
b. When you try to access a property or call a method on undefined (or an expression that evaluates to undefined), you will get an error Uncaught TypeError: Cannot read property ‘X’ of undefined.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How do you destructure an object with a default value?

A

const user = {
id: 1,
name: “Sam”
};

const {name, isAdmin = false} = user;
console.log(isAdmin); // false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

How do you merge two objects?

A

Use spread operator: …

const firstPerson = {
name: “Sam”,
age: 18
}

const secondPerson = {
age: 25,
type: “admin”
}

const mergedObjects = {…firstPerson, …secondPerson};
console.log(mergedObjects); // {name: “Sam”, age: 25, type: “admin”}
Notice how the new object ended up with the name and type from both objects. However, regarding the age, since it exists in both objects, only the 2nd one persisted.
This is why the order of the objects matters when spreading them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What is optional chaining?

A

This is called optional chaining which allows you to access a property deep within an object without risking an error if one of the properties is null or undefined.

const user = {
details: {
name: {
firstName: “Sam”
}
},
data: null
}

user.details?.name?.firstName; // “Sam”
user.data?.id; // undefined
user.children?.names; // undefined
user.details?.parent?.firstName; // undefined

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is an edge case of optional chaining?

A

You cannot use optional chaining on an object that may not exist. The object has to exist. Optional chaining is only used to access a property that may or may not exist.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Refactor this using optional chaining:

const data = {
temperatures: [-3, 14, 4]
}

let firstValue = undefined;
if (data.temperatures) {
firstValue = data.temperatures[0];
}

A

const firstValue = data.temperatures?.[0];

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Refactor this using optional chaining:

const person = {
age: 43,
name: “Sam”
};

let upperCasedName = person.name; // might be undefined
if (person.name) {
upperCasedName = person.name.toUpperCase();
}

A

const upperCasedName = person.name?.toUpperCase();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is nullish coalescing?

A

The nullish coalescing ?? operator is a new operator introduced in JavaScript that allows you to default to a certain value when the left-hand side is a nullish value.

A nullish value is a value that is either null or undefined.

const getName = name => {
return name ?? “N/A”;
}

console.log(getName(“Sam”)); // “Sam”
console.log(getName(undefined)); // “N/A”
console.log(getName(null)); // “N/A”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Use optional chaining and nullish coalescing to refactor the following code:

let name = undefined;
if (user.details && user.details.name && user.details.name.firstName) {
name = user.details.name.firstName;
} else {
name = “N/A”;
}

A

const name = user.details?.name?.firstName ?? “N/A”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What’s the difference between null and undefined?

A

undefined means that the property has not been defined yet. Whereas, null means that the property has been defined but is empty.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Refactor the following:

const getPushMessage = status => {
if (status === “received”) {
return “Restaurant started working on your order.”;
} else if (status === “prepared”) {
return “Driver is picking up your food.”
} else if (status === “en_route”) {
return “Driver is cycling your way!”;
} else if (status === “arrived”) {
return “Enjoy your food!”;
} else {
return “Unknown status”;
}
}

A

const getPushMessage = status => {
const messages = {
received: “Restaurant started working on your order.”,
prepared: “Driver is picking up your food.”,
en_route: “Driver is cycling your way!”,
arrived: “Enjoy your food!”
};

return messages[status] ?? "Unknown status"; }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What are the falsy values?

A

false (is already a boolean)
null
undefined
0
NaN
“” (empty string)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

How do you convert a boolean to its opposite?

A

Logical NOT operator (!)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

a. How do you create an HTML element?
b. Set the background to blue?
c. Set the class of the element to: container?
d. Set multiple classes on the element?

A

a. const element = document.createElement(tagName)
b. element.style = “background-color: blue”
c. element.className = “container”
d. element.className = “container center”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What do most APIs (for example, a weather API, Twitter API, etc.) return?

A

An array of objects. Arrays of objects are the most common data type that you will encounter when working in web development.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What’s a very important tip when working with arrays of objects, especially when iterating over an array of objects?

A

Add console.log() throughout your code to visualise the object that you receive in the callback.

Eg (tweets is an array of objects):
tweets.forEach(tweet => {
console.log(tweet);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What does .map() do?

A

.map() array method allows you to transform an array into another array of the same size.

42
Q

What is it recommended to do if a function might fail?

A

You should wrap it in a try…catch block.

console.log(“Step 1”);
try {
nonExistentFunction();
} catch (error) {
console.error(error); // Uncaught ReferenceError: nonExistentFunction is not defined
}
console.log(“Step 2”);
The code above will log the following to the console:

“Step 1”
Uncaught ReferenceError: nonExistentFunction is not defined
“Step 2”

43
Q

Explain minification.

A
  • JavaScript has semi-colons because it’s common to minify the code before publishing the website.
  • Automated tools will minify your code. You should never minify it yourself or write minified code.
  • Minification works by removing the comments and removing all the blank spaces (thus putting all your code on 1 line).
44
Q

What’s the most common example of Automatic Semi-colon Insertion?

A

The most common example of ASI is with the return keyword (mostly while writing React code with JSX).

45
Q

Why do [] === [] and {} === {} return false?

A

Because each array and object is a new instance. JS is checking if they are the same instance, so here === returns false.

46
Q

Why does secondArray contain 10?

const firstArray = [];
const secondArray = firstArray; // secondArray now points to firstArray
console.log(firstArray); // []
console.log(secondArray); // []

firstArray.push(10);
console.log(firstArray); // [10]
console.log(secondArray); // [10]

A

Because when we created secondArray = firstArray, we are not copying firstArray, but rather only creating a reference to it.

This means firstArray and secondArray are now referring to the same value. Technically we say they are referencing the same place in the memory.

47
Q

What is Immutability?

A

An immutable object is an object that cannot be changed. Every update creates a new value, leaving the old one untouched.

48
Q

What happens when you assign a variable to an object or array?

A

It does NOT copy it. It will only reference its value.

49
Q

How do you make a shallow copy of an object or array?

Why is it called a shallow copy?

A

By using the spread operator

Eg:
const grades = [10, 20];
const gradesCopy = […grades];
console.log(gradesCopy); // [10, 20] (new array, not linked to ‘grades’)

This technique covers most scenarios for array immutability as with this new array, you will be able to manipulate it without affecting the original array.

50
Q

Which array methods are immutable?

A

The ones that are immutable are .filter() and .map() because these methods return a new array (rather than modifying the old one). The .reduce() method is also immutable since it returns a new value computed from an array.

This copy is called shallow copy because it only goes 1 level deep. This means that for an array of objects if you make an update to the objects in the new array, the objects in the old array will still be updated.

51
Q

How do you immutably add an item to an array?

A

You can do that in one line also using the … syntax:

const grades = [10, 20];
const updated = […grades, 15];
console.log(updated); // [10, 20, 15] (new array, not related to ‘grades’)

The reason why this works is that you’re creating a new array with the [ ] syntax, and inside this array, you’re spreading the items from grades and adding to it a new value which is 15.

52
Q

How do you immutably add a property to an object?

A

To immutably update an object, you need to make a copy of it and then add the new key: value that will override the previous one.

const user = {
id: 1,
age: 23
};
const clonedUser = {
…user,
age: user.age + 1
};
console.log(clonedUser); // {id: 1, age: 24} (new object not related to ‘user’)
Notice how the age: user.age + 1 overrides the previous value of the age property.

53
Q

How do you delete a property from an object?

A

Though less used, here’s how you can immutably delete a property from an object. It’s a combination of object destructuring and the … operator:

const book = {
id: 1,
title: “Harry Potter”,
year: 2017,
rating: 4.5
}

// GOOD: immutable
const {year, …rest} = book;
console.log(rest); // { id: 1, title: “Harry Potter”, rating: 4.5}
The reason why this works is because {year, …rest} = book is destructuring the value of the key year from the book object. This is similar to reading book.year.

However, notice how we ask JavaScript to destructure the rest of the object with …rest. This means combining all the other key/values in a new object called rest. So we end up with rest which is an immutable copy of book excluding the year property!

54
Q

Why use classes?

A

Classes allow you to better organise your code by grouping your code (variables & functions) into a single class. Classes promote reusability.

55
Q

What’s the difference between a class and an instance?

A

A class is a factory that is able to create instances. Every instance created from a class is unique, therefore

const person1 = new Person(“Sam Doe”);
const person2 = new Person(“Charley Bron”);

person1 === person2; // false (they are not the same)

56
Q

Create a class for Person, capture two instance variables for fName and lName, and set an instance variable for age.

A

// class definition
class Person {
constructor(firstName, lastName) {
// capture firstName param into this.firstName instance variable
this.firstName = firstName;
// capture lastName param into this.lastName instance variable
this.lastName = lastName;
// set an instance variable (without capturing a constructor param)
this.votingAge = 18;
}
}

57
Q

Why do we capture constructor params?

A

We capture constructor params so that we can access them outside the constructor (in instance methods).

58
Q

What are instance methods?

A

Instance methods are functions that can be called on an instance of a class. Let’s take an example:

// class definition
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

getFullName() {
    return `${this.firstName} ${this.lastName}`;
} }

// class usage
const person = new Person(“Sam”, “Green”);
console.log(person.getFullName()); // “Sam Green”

59
Q

Why doesn’t the following work?

class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

getFullName() {
    // ❌ this does NOT work
    return `${firstName} ${lastName}`;
} }
A

Because firstName and lastName are not defined using the ‘this’ keyword. It’s referring to the current instance of the class.

60
Q

What is Object-Oriented Programming (OOP)?

A

Object-Oriented Programming (OOP) is when you describe the real world with classes (that you can then instantiate which creates objects).

Eg:
class User {
constructor(firstName, lastName, prefix, age) {
this.firstName = firstName;
this.lastName = lastName;
this.prefix = prefix;
this.age = age;
}

getFullName() {
    return `${this.prefix}. ${this.firstName} ${this.lastName}`;
}

canVote() {
    return this.age >= 18;
} }

// Sample usage
const user1 = new User(“Sam”, “Doe”, “Mrs”, 20);
console.log(user1.getFullName()); // “Mrs. Sam Doe”
console.log(user1.canVote()); // true
const user2 = new User(“Alex”, “Green”, “Mr”, 17);
console.log(user2.getFullName()); // “Mr. Alex Green”
console.log(user2.canVote()); // false

61
Q

An instance method has access to the instance variables defined on the class, but do they also have access to other instance methods on the class?

A

Yes, they also have access to other instance methods on the class.
This means that an instance method can call another instance method using the this.functionName() syntax. For example:

class User {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

getFullName() {
    return `${this.firstName} ${this.lastName}`;
}

getGreeting() {
    const fullName = this.getFullName(); // call an instance method
    return `Hello ${fullName}`
} }
62
Q

How can you make a class DRY?

A

You can use class inheritance, such as using extends. This gives the child class all the methods defined on the parent class. (Inheritance can also be used to override methods if you want a method from the parent to implement something different in the child) For example:

class Employee {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

getFullName() {
    return `${this.firstName} ${this.lastName}`;
}

getInitials() {
    return this.firstName[0] + this.lastName[0];
} }

class Manager extends Employee {
sendPerformanceReview() {
console.log(Sent performance review for current quarter);
}
}

63
Q

How can you add constructors to a child class?

A

By using super inside child class, followed by new constructor. (If the parent has no constructors, call super(). You can also call functions on the parent class also using the super keyword, for example super.parentMethodName().). Eg:

class Employee {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

getFullName() {
    return `${this.firstName} ${this.lastName}`;
}

getInitials() {
    return this.firstName[0] + this.lastName[0];
} }

class Manager extends Employee {
constructor(firstName, lastName, department) {
super(firstName, lastName); // super must be called first
this.department = department;
}

sendPerformanceReview() {
    console.log(`Sent performance review for current quarter in ${this.department}`);
}    }
64
Q

Revision material on Prototypical Inheritance.

A
  • The class syntax was added in 2015 and should be used because it makes the syntax easier to read.
  • A class is creating a function with the constructor pattern (has to be called with new)
  • Adding a function to the prototype of a function, allows us to add a new custom method to the instances of that function.
  • You will most likely not write this syntax yourself, but it’s important to understand it and be able to recognize it.
  • With classical inheritance, you inherit all of the parent’s methods
  • With prototypal inheritance (the one in JavaScript), you can inherit specific functions by adding them to the .prototype.
  • The .prototype holds all the methods that can be called on instances of that class/function.
  • Prototypal inheritance is more powerful than classical inheritance in most cases, however, it is more complicated, and fewer developers are experienced with it.
  • The extends keyword, inherits all the methods from the parent. So, it uses prototypal inheritance to simulate classical inheritance.
  • If you need to inherit a specific function, you can still do that by adding to the .prototype object.
  • The most common use case is to use extends and inherit all the methods.
  • Every object in JavaScript inherits the prototype of Object.
  • Inheritance works in JavaScript because of the prototype chain.
  • When you call child.parentMethod(), JavaScript will walk up the prototype chain until it finds parentMethod() or null which signifies the end of the prototype chain.
65
Q

What can be defined in the constructor function?

A

An instance variable. It is a variable that belongs to a specific instance of a class.

class User {
constructor() {
this.votingAge = 18;
}
}

66
Q

What do public class fields do?

A

Public class fields allows you to define instance variables on a class without having to override the constructor.

class BookSale {
amount = 1000; // US cents
currency = “usd”;
isStudent = false;

applyStudentDiscount() {
    this.isStudent = true;
    this.amount = 800;
    return this;
}

setCurrency(currency) {
    this.currency = currency;
    return this;
}

applyPercentageDiscount(percent) {
    this.amount = this.amount - this.amount * percent / 100;
    return this;
} }

// Sample usage - do not modify
const bookSale = new BookSale;
bookSale.applyStudentDiscount().setCurrency(“eur”).applyPercentageDiscount(5);

67
Q

How do you mark an instance variable or method as private?

A

To mark an instance variable or method as private, you have to prefix it with the # (hash sign). For example:

class User {
#votingAge = 18;
}

Now, #votingAge is a private class field that cannot be accessed from outside of the class. It can only be accessed from inside the class with this.#votingAge.

Note that private class fields have to be defined outside of the constructor first. Then, you can decide to re-use them in the constructor. For example, the code below is invalid:

class User {
constructor() {
// ❌ this does NOT work
this.#votingAge = 18;
}
}

You can fix the code above by defining #votingAge as a class field and then you can change its value in the constructor if necessary:

class User {
#votingAge;

constructor() {
    // this works ✅
    this.#votingAge = 18;
} }
68
Q

Why are private class fields a great addition to the language?

A

One of the main reasons why private class fields are a great addition to the language is because they prevent them from being changed by the outside world (outside of the class).

69
Q

How does setTimeout work?

What kind of callback does it use?

setTimeout(() => {
console.log(“One second has elapsed.”);
}, 1000);

A

What the setTimeout function does is that it queues the callback function that you specify in the future. It will wait the milliseconds that you specified. In this example, we specified 1000 milliseconds which is the equivalent of 1 second.

This callback is similar to the previous callbacks that we saw in the array chapters, except that this one is running somewhere in the future. In this example, 1 second in the future. Because it runs somewhere in the future, we call it an asynchronous callback.

70
Q

What kind of conversations are synchronous and asynchronous code?

A
  • A face-to-face conversation is synchronous because people are talking and replying immediately one after the other.
  • However, a conversation over text message is asynchronous because the recipients can reply at a later time in the future.
71
Q

What’s the purpose of the callback pattern?

A
  • The callback pattern is a programming pattern where you pass a function definition as a parameter to a function. That callback will then be automatically called once the function call has been completed successfully.
  • We have callbacks (and later promises) as they allow the browser to continue responding to user input instead of blocking and waiting until a function has finished executing.
72
Q

What is the callback pattern?

Why do we have callbacks?

A
  • The callback pattern is a programming pattern where you pass a function definition as a parameter to a function. That callback will then be automatically called once the function call has been completed successfully.
  • We have callbacks (and later promises) as they allow the browser to continue responding to user input instead of blocking and waiting until a function has finished executing.
73
Q

What do promises let you do with callbacks?

A

Promises let you run a callback sometime in the future when the promise has been completed successfully.

74
Q

What does a promise ‘resolving data’ mean?

A

This means that the promise is giving us an answer after it has been completed. This will be especially important when we work with fetch.

Eg:

const temperatures = [10, 5, 3];

sumTemperatures(temperatures).then(data => {
console.log(data); // 18 (the sum of temperatures)
});

75
Q

Why will the following code not work?

/* ❌ this does NOT work as expected */
const data = getWeatherIn(“Amsterdam”);

console.log(data); // Promise <pending></pending>

A

You have to add a .then() callback and you will only be able to access the data inside the .then callback. This is because the promise callback will only run in the future (once the promise has been completed).

If JavaScript were to support this syntax, then the user would not be able to interact with the browser for the entire duration that getWeatherIn needs to complete. If that were the case, no one would use browsers because they would be terribly slow.

76
Q

Does the try…catch statement work with promises?

A

The try…catch statement does not work with promises. That’s because the promises are asynchronous meaning that they are happening at a later stage.

So, if a promise fails, this is going to be sometime in the future. And, by that time, the try…catch statement has already been completed a long time ago.

Also, you don’t need try…catch because promises have .then() and .catch() that act similarly to the try…catch statement.

77
Q

What are the stages of implementing a promise that returns a function?

A
  • When implementing a function that returns a promise, you have to return new Promise(() => {}).
  • The () => {} function inside the Promise constructor is called executor.
  • The executor receives as the first argument the resolve function. You should call the resolve() function when the promise needs to move from pending to fulfilled.
  • Calling resolve() with a certain value will make that value available in the .then(callback).
78
Q

What’s an API?

A

An API is a means for a website or an application to communicate with another one. For example:

  • Your website needs to know the currency exchange for Euro and USD. You use an API for that.
  • LearnJavaScript.online wants to get your verified email to log you in. We’ve used the GitHub API for that.
79
Q

Why is this JS object not a JSON object?

const user = {
firstName: “Sam”,
lastName: “Green”,
getFullName: function() {
return ${this.firstName} ${this.lastName}
}
}

A

The reason why this object is not a JSON object is that it contains a function.

80
Q

Why do you need to convert a JSON string into a JSON object (in JavaScript) and vice versa?

A

The reason why this is the most frequent use case is that when you communicate with an API, you cannot send an object. You will have to convert it to a string. Similarly, the API cannot send you an object, it will send you a string. But, that string is not any string. It’s a JSON string. That means that it can be converted back into a JSON object.

81
Q

What is JSON?

A
  • JSON (JavaScript Object Notation) is a format for storing and sending data. It’s very commonly used on the web because it’s lightweight.
  • JSON is a subset of JavaScript objects. This means that every JSON object is a JavaScript object whereas not every JavaScript object is a JSON object.
82
Q

How do you convert from a JSON string into a JSON object?

A

const string = ‘{“firstName”:”Sam”,”lastName”:”Green”,”age”: 32}’;
const person = JSON.parse(string); // {firstName: “Sam”, lastName: “Green”, age: 32}
console.log(person.firstName); // “Sam”

83
Q

How do you convert from an object into a JSON string?

A

const person = {
firstName: “Sam”,
lastName: “Green”,
age: 32
};
const string = JSON.stringify(person);
console.log(string); //’{“firstName”:”Sam”,”lastName”:”Green”,”age”:32}’

84
Q

What does fetch do? What does it return?

A

a. We use the fetch Web API (or fetch API) to make a request to a server (which could be ours or an external one, for example, a Weather API) to retrieve some information without reloading the page.

b. Fetch always returns a promise.
This is because fetch has to go to the network, this could take anywhere between a couple of milliseconds and a second (on average). So, we cannot freeze the entire browser while the fetch request is working.
Thus, by design, fetch returns a promise that we can resolve once the request has finished.

85
Q

What’s the difference between JSON.parse(string) .json() method on response in the code below?

fetch(URL)
.then(res => res.json());

A

The only difference is that response.json() is non-blocking and asynchronous meaning that it returns a promise.

86
Q

What is data in the code below?

fetch(URL)
.then(res => res.json())
.then(data => {
console.log(data);
});

A

The data variable will be the information that the API returns.

If we go back to the previous example of the Twitter notifications, data will contain an object with the number of new notifications. It will look like this:

{
count: 3,
message: “You’ve got 3 new notifications”
}

87
Q

What are four common methods that you should know about?

A
  • GET: read data
  • POST: create data
  • PUT: update data
  • DELETE: delete data
88
Q

Why do we have to use JSON.stringify in the body in the code below?

fetch(“https://example.com/api/tweets”, {
method: “POST”,
body: JSON.stringify({
tweet: “Your tweet here…”
})
})
.then(res => res.json())
.then(data => {
console.log(data); // read the server response
});

A

We cannot send objects directly to the API, thus we have to convert them to a string with JSON.stringify.

89
Q

Why do some endpoints require headers?

A

The reason why some endpoints require this header is that they don’t know that you’re sending them JSON (since they support other formats too). Here’s what the code looks like:

fetch(URL, {
method: “POST”, // or PUT or DELETE
headers: {
“Content-Type”: “application/json”
},
body: JSON.stringify({
key1: ‘value1’, // replace with key/value based on documentation
key2: ‘value2’, // same as above (if needed)
})
})
.then(response => response.json())
.then(data => {
console.log(data); // read server response
});

90
Q

How do you create a div with a class of ‘card’, append an image to it and then append it to the DOM?

A

const propertiesContainer = document.querySelector(‘.properties’)

for(let i = 0; i < properties.length; i++){
const card = document.createElement(‘div’)
card.classList.add(‘card’)
card.innerHTML = properties[i].title
const image = document.createElement(‘img’)
image.setAttribute(‘src’, properties[i].image)
card.appendChild(image)
propertiesContainer.appendChild(card)
}

91
Q

What are the benefits of FetchWrapper?

A
  • We only need to set the base URL once (we pass it to the constructor).
  • It always converts the response to JSON (response => response.json()), since our API always returns JSON.

The benefits are even clearer once you work with PUT, POST, or DELETE:

  • the code is a lot shorter.
  • it automatically calls JSON.stringify().
  • it automatically calls response => response.json().
  • it automatically sets the default Content-Type header.
92
Q

What does
document.querySelector(“CSS-selector”) return?

A

It returns an object which is an instance of HTMLElement. HTMLElement is the parent class that every single HTML element in your page inherits from. This means that every element on your page is an instance of a single class which is HTMLElement.

93
Q

How do you log the text of every link to the console?

A

const logLinksTexts = () => {
return document.querySelectorAll(‘a’).forEach(link => {
console.log(link.textContent)
})
}

93
Q

What does querySelectorAll return?

A

A NodeList. A NodeList is a collection of DOM elements.

A NodeList is not an array. However, there are some similarities:

  • they both have a length property (you can access it with .length)
  • you can access items at a specific index with the square brackets. For example, [0] and [1].
  • you can iterate through both of them with .forEach().

These are the only similarities. You cannot call .filter on a NodeList. Calling paragraphs.textContent will never work as there’s no textContent property on the NodeList object. It has to be called on a single element. This is why we need to loop through the list of paragraphs one by one.

94
Q

How do you convert a NodeList into an array?

A

const divs = document.querySelectorAll(“div”); // NodeList
const items = […divs]; // Array

Or, in a single line:

const items = […document.querySelectorAll(“div”)]; // Array

You can then call .filter() or .map() on the array.

95
Q

How do you map over a NodeList to find textContent of each item?

A

const getSelectedCurrencies = () => {
return […document.querySelectorAll(‘.cards .card.active’)].map(item => item.textContent)
}

96
Q

What’s the difference between textContent and innerHTML?

A
  • textContent will return the text, with all the HTML tags stripped out.
  • innerHTML will return the HTML string inside of the element (it will not strip out HTML tags).

So, when you need to keep the HTML tags, you should use innerHTML. Otherwise, textContent is the way to go.

Example:

<div>This is a <strong>sample text</strong></div>

const element = document.querySelector(“#test”);
console.log(element.textContent); // “This is a sample text”

console.log(element.innerHTML); // “This is a <strong>sample text</strong>”

97
Q

How do you change the value of textContent?

A

<div>This is a <strong>sample text</strong></div>

const element = document.querySelector(“#test”);
element.textContent = “This is the new text!”;

98
Q

When is it better to use textContent over innerHTML?

A

If the string that you’re rendering is coming from your users (for example, a string coming from a comment box that the user can fill), then you should avoid using innerHTML as your users will be able to write HTML & JavaScript code inside of your page which may lead to security issues. This is called Cross-Site Scripting (XSS) attack.

99
Q

How do you read the written content of an input element?

Eg:

<form>
<input></input>
<input></input>
</form>

A

To read the written content of an input element, you have to use value property.

const email = document.querySelector(“#email”);
console.log(email.textContent); // undefined ❌ (there’s no closing tag)
console.log(email.value); // text written in the email field

The <textarea> is not self-closing but you still have to access the value property.</textarea>