Learn JavaScript Flashcards
How can you access a specific character in a string?
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.
What is the output of
a. language.substring(1, 4);
b. language.substring(4);
if const language = “JavaScript”;?
a. console.log(‘ava’)
b. console.log(‘Script’)
What is interpolation?
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 to convert from a string to a number?
eg: let str = “42”;
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).
What scope are let, const and var?
let and const are ‘block scoped’ but var is ‘function scoped’, meaning it will be accessible anywhere inside the nearest function.
Why can we push new data into arrays even if they’re defined with const?
Because const doesn’t mean that the variable is immutable. It’s content can change. However, it will always be an array.
What’s the basic definition of a callback function?
It’s a function definition passed as an argument to another function.
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?
}
The second.
What is the difference between .filter() and .find()?
The .filter() method always returns an array.
The .find() method returns the first array item that matches the callback function or undefined.
What is an object?
An object is a data type that allows you to group several variables together into one variable that contains keys and values.
What are the benefits of arrow functions?
- 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 do you empty an array?
You can do that by setting its length to 0:
const items = [“Pen”, “Paper”];
items.length = 0;
console.log(items); // []
Also, .splice(0)
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
- 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).
What does reduce do?
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 do you identify array destructuring?
You can identify destructuring when you see the square brackets [] on the left side of the equal sign.
How do you identify array destructuring?
You can identify destructuring when you see the square brackets [] on the left side of the equal sign.
How can you concatenate/merge several arrays’ content into a new array?
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];
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?
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 can you return an array of all the keys on an object?
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.
Dynamically log the keys of the following object:
const settings = {
theme: “Dark”,
version: “2.4.1”,
beta: false
};
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
When can’t you use dot notation?
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].
What does [object Object] mean?
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 do you make an array of the values of an object?
const user = {
id: 1,
name: “Sam Green”,
age: 20
};
const values = Object.values(user);
console.log(values); // [1, “Sam Green”, 20]
How do you get the key/value pairs from an object?
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.
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. 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 do you destructure an object with a default value?
const user = {
id: 1,
name: “Sam”
};
const {name, isAdmin = false} = user;
console.log(isAdmin); // false
How do you merge two objects?
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.
What is optional chaining?
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
What is an edge case of optional chaining?
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.
Refactor this using optional chaining:
const data = {
temperatures: [-3, 14, 4]
}
let firstValue = undefined;
if (data.temperatures) {
firstValue = data.temperatures[0];
}
const firstValue = data.temperatures?.[0];
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();
}
const upperCasedName = person.name?.toUpperCase();
What is nullish coalescing?
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”
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”;
}
const name = user.details?.name?.firstName ?? “N/A”;
What’s the difference between null and undefined?
undefined means that the property has not been defined yet. Whereas, null means that the property has been defined but is empty.
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”;
}
}
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"; }
What are the falsy values?
false (is already a boolean)
null
undefined
0
NaN
“” (empty string)
How do you convert a boolean to its opposite?
Logical NOT operator (!)
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. const element = document.createElement(tagName)
b. element.style = “background-color: blue”
c. element.className = “container”
d. element.className = “container center”
What do most APIs (for example, a weather API, Twitter API, etc.) return?
An array of objects. Arrays of objects are the most common data type that you will encounter when working in web development.
What’s a very important tip when working with arrays of objects, especially when iterating over an array of objects?
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);
});