JS Flashcards

1
Q

Escaping characters

A
Code	Output
\'	single quote
\"	double quote
\\	backslash
\n	newline
\r	carriage return
\t	tab
\b	word boundary
\f	form feed
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Length of a string

A

“some text”.length

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

String values are…

A

Immutable. Which means that they cannot be altered once created. (this does not mean that myStr cannot be changed, just that the individual characters of a string literal cannot be changed)

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

multi-dimensional array

A

[[some content],[other content]]

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

Array values are…

A

Mutable. myArray[0] = 45;

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

.push() does…

A

appends data to an array

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

.pop() does…

A

pops and assigns the last element from an array to anything

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

.shift() does…

A

removes the first element of an array and returns it

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

.unshift() is…

A

like push but to the beginning of an array

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

structure of the function

A
function functionName() {
console.log(something);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Variables which are used without the var keyword…

A

…are automatically created in the global scope.

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

Variables which are declared within a function, as well as the function parameters…

A

… have local scope

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

It is ___ to have both local and global variables with the same name.

A

possible!

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

When you have both local and global variables with the same name…

A

… the local variable takes precedence over the global variable.

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

what is hoisting and what gets hoisted

A

adding vars and functions to memory when executing. they get added to the top of the file, so your function can be at the bottom but you can call it at the top

vars get partially hoisted (only var but not its value)

functions get fully hoisted

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

Variables which are defined outside of a function block have

A

Global scope. This means, they can be seen everywhere in your JavaScript code.

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

In JavaScript, scope refers to…

A

the visibility of variables

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

Variables which are used without the var keyword are…

A

automatically created in the global scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var.

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

It is possible to have both local and global variables with the same name. When you do this,

A

the local variable takes precedence over the global variable.

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

You can use a _ statement to send a value back out of a function.

A

return

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

A function can include the return statement but it does not have to. In the case that the function doesn’t have a return statement, when you call it,

A

the function processes the inner code but the returned value is undefined.

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

=== vs ==

A

unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion.

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

determine the type of a variable or a value

A

typeof 3 // number

typeof ‘3’ // string

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

using logical AND

A

&&

the same effect: nest if statements

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
logical OR
|| | returns true if either of the operands is true
26
case statements for multiple if statements
``` switch (value){ case a: do something; break; case b: do something; break; } ```
27
switch statements equivalent to final "else"
default: do something; break; (should be the last case, just like else)
28
If the break statement is omitted from a switch statement's case,
the following case statement(s) are executed until a break is encountered.
29
If you have multiple inputs with the same output, you can represent them in a switch statement like this:
``` switch(val) { case 1: case 2: case 3: result = "1, 2, or 3"; break; case 4: result = "4 alone"; } ```
30
When a return statement is reached,
the execution of the current function stops and control returns to the calling location.
31
Objects are similar to arrays, except that instead of using indexes to access and modify their data,
you access the data in objects through what are called properties.
32
In an object, you can also use numbers as properties. You can even omit the quotes for single-word string properties, as follows:
``` var anotherObject = { make: "Ford", 5: "five", "model": "focus" }; ```
33
if your object has any non-string properties
JavaScript will automatically typecast them as strings.
34
There are two ways to access the properties of an object
dot notation (.) and bracket notation ([]), similar to an array.
35
Dot notation is what you use
when you know the name of the property you're trying to access ahead of time.
36
Access object property through a variable
var playerNumber = 1; myPlayer[playerNumber] // returns value for 1:
37
add properties to an object
myDog.newProperty = someValue
38
delete properties from an object
delete myDog.newProperty
39
If you have tabular data, you can use an object to "lookup" values rather than a switch statement or an if/else chain.
This is most useful when you know that your input data is limited to a certain range.
40
Testing Objects for Properties
We can use the .hasOwnProperty(propname) method of objects to determine if that object has the given property name. .hasOwnProperty() returns true or false if the property is found or not.
41
The sub-properties of objects can be accessed by chaining together the dot or bracket notation.
ourStorage.cabinet["top drawer"].folder2; // "secrets" | ourStorage.desk.drawer; // "stapler"
42
Array bracket notation can be chained to access nested arrays.
ourPets[0].names[1]; // "Fluffy" | ourPets[1].names[0];
43
while loop
while (condition) { code }
44
for loop
``` for ([initialization]; [condition]; [final-expression]) e.g. for (var i = 0; i < 5; i++) { ourArray.push(i); } ```
45
nested for loops
``` for (var i = 0; i < arr.length; i++){ for (var j = 0; j < arr[i].length; j++){ do something } } ```
46
do...while
It is called a do...while loop because it will first do one pass of the code inside the loop no matter what, and then continue to run the loop while the specified condition evaluates to true. ``` var ourArray = []; var i = 0; do { ourArray.push(i); i++; } while (i < 5); ``` Essentially, a do...while loop ensures that the code inside the loop will run at least once.
47
Recursion is
the concept that a function can be expressed in terms of itself. Use the function within itself.
48
parseInt()
parses a string and returns an integer
49
Use the parseInt Function with a Radix
The parseInt() function parses a string and returns an integer. It takes a second argument for the radix, which specifies the base of the number in the string. The radix can be an integer between 2 and 36. The function call looks like: parseInt(string, radix);
50
conditional operator, also called the ternary operator
can be used as a one line if-else expression. The syntax is: condition ? statement-if-true : statement-if-false;
51
String multiple conditionals/ternary together
condition1 ? statement-if-true : condition2 ? statement-if-true : statement-if-false
52
when using let
variable with the same name can only be declared once
53
"use strict"
This enables Strict Mode, which catches common coding mistakes and "unsafe" actions.
54
When you declare a variable with the let keyword inside a block, statement, or expression,
its scope is limited to that block, statement, or expression.
55
const
has all the awesome features that let has, with the added bonus that variables declared using const are read-only. They are a constant value, which means that once a variable is assigned with const, it cannot be reassigned.
56
A common practice when naming constants
use all uppercase letters, with words separated by an underscore
57
objects (including arrays and functions) assigned to a variable using const
are still mutable: ``` const s = [5, 6, 7]; s = [1, 2, 3]; // throws error, trying to assign a const s[2] = 45; // works just as it would with an array declared with var or let console.log(s); // returns [5, 6, 45] ```
58
To ensure your data doesn't change
JavaScript provides a function Object.freeze to prevent data mutation.
59
Arrow function syntax
const myFunc = () => "value";
60
How to display Default parameters in arrow functions
const myFunc = (arr1, arr2 = 1) => "value";
61
What does rest parameter do?
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. ``` const myFunc = (...args) => { return args.map } ```
62
What does the spread operator allow?
allows us to expand arrays and other expressions in places where multiple parameters or elements are expected ``` const arr = [6, 89, 3, 45]; const maximus = Math.max(...arr) ...arr returns an unpacked array. ```
63
Why use the Destructuring assignment?
for neatly assigning values taken directly from an object. ``` var user = {name: "John", age: '34'}; const { name, age } = user; // name = 'John Doe', age = 34 -- this picks up the keys and matches them and returns their values, so even if there were more keys in the obj, there would be no need to specify them ```
64
One key difference between the spread operator and array restructuring is that...
the spread operator unpacks all contents of an array into a comma-separated list. Consequently, you cannot pick or choose which elements you want to assign to variables. Destructuring an array lets us do exactly that: const [a, b] = [1, 2, 3, 4, 5, 6]; console.log(a, b); // 1, 2 The variable a is assigned the first value of the array, and b is assigned the second value of the array
65
We can also access the value at any index in an array with destructuring
by using commas to reach the desired index: const [a, b,,, c] = [1, 2, 3, 4, 5, 6]; console.log(a, b, c); // 1, 2, 5
66
involving array destructuring, we might want to collect the rest of the elements into a separate array.
const [a, b, ...arr] = [1, 2, 3, 4, 5, 7]; console. log(a, b); // 1, 2 console. log(arr); // [3, 4, 5, 7]
67
Send stuff into a function from an object
``` 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;
68
template literal (what it allows, how to use it)
Template literals allow you to create multi-line strings and to use string interpolation features to create strings. const person = { name: "Zodiac Hasbro", age: 56 }; ``` // Template literal with multi-line and string interpolation const greeting = `Hello, my name is ${person.name}! I am ${person.age} years old.`; ``` ``` console.log(greeting); // prints // Hello, my name is Zodiac Hasbro! // I am 56 years old. ```
69
template literal allows you to...
create multi-line strings and to use string interpolation features to create strings.
70
Write Concise Object Literal Declarations Using Object Property Shorthand
ES6 provides the syntactic sugar to eliminate the redundancy of having to write x: x. You can simply write x once, and it will be converted tox: x (or something equivalent) under the hood. ``` Instead of this const getMousePosition = (x, y) => ({ x: x, y: y }); ``` ``` you do this const getMousePosition = (x, y) => ({ x, y }); ```
71
Write Concise Object Literal Declarations Using Object Property Shorthand
ES6 provides the syntactic sugar to eliminate the redundancy of having to write x: x. You can simply write x once, and it will be converted tox: x (or something equivalent) under the hood. ``` Instead of this const getMousePosition = (x, y) => ({ x: x, y: y }); ``` ``` you do this const getMousePosition = (x, y) => ({ x, y }); ```
72
When defining functions within objects in ES5, we have to use the keyword function as follows
``` const person = { name: "Taylor", sayHello: function() { return `Hello! My name is ${this.name}.`; } }; ```
73
With ES6, You can remove the function keyword and colon altogether when defining functions in objects.
``` const person = { name: "Taylor", sayHello() { return `Hello! My name is ${this.name}.`; } }; ```
74
The class syntax in ES6 simply replaces the constructor function creation:
``` class SpaceShuttle { constructor(targetPlanet) { this.targetPlanet = targetPlanet; } } const zeus = new SpaceShuttle('Jupiter'); ```
75
The class syntax in ES6 simply replaces the constructor function creation:
``` class SpaceShuttle { constructor(targetPlanet) { this.targetPlanet = targetPlanet; } } const zeus = new SpaceShuttle('Jupiter'); ```
76
You can obtain values from an object and set the value of a property within an object. What are they called?
These are classically called getters and setters.
77
Getter functions are meant to
simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable.
78
Setter functions are meant to
modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.
79
How to use getter and setter in a class
``` class Book { constructor(author) { this._author = author; } // getter get writer() { return this._author; } // setter set writer(updatedAuthor) { this._author = updatedAuthor; } } const lol = new Book('anonymous'); console.log(lol.writer); // anonymous lol.writer = 'wut'; console.log(lol.writer); // wut ```
80
How to use getter and setter in a class
``` class Book { constructor(author) { this._author = author; } // getter get writer() { return this._author; } // setter set writer(updatedAuthor) { this._author = updatedAuthor; } } const lol = new Book('anonymous'); console.log(lol.writer); // anonymous lol.writer = 'wut'; console.log(lol.writer); // wut ```
81
Two components of tag
type, src
82
Export a function from a module
``` //defined function const add = (x, y) => { return x + y; } ``` ``` //export export { add }; ```
83
importing a function from a module
import { add } from './math_functions.js';
84
import everything from a module
import * as myMathModule from "./math_functions.js";
85
why use export default
Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module.
86
examples using export default
``` // named function export default function add(x, y) { return x + y; } ``` ``` // anonymous function export default function(x, y) { return x + y; } ```
87
you can only have ___ value be a default export in each module or file
one value
88
you ____ use export default with var, let, or const
cannot
89
importing a default
import add from "./math_functions.js"; The syntax differs in one key place. The imported value, add, is not surrounded by curly braces ({}).
90
You _____ use any name here when importing a default.
can
91
Promise is a ___ function, so you need to use the ___ keyword to create one.
constructor | new
92
Promise takes a function, as its argument, with two parameters - ___ & _____. These are methods used to determine the outcome of the promise.
resolve, reject
93
Promise syntax looks like this:
const myPromise = new Promise((resolve, reject) => { });
94
A promise has three states:
pending, fulfilled and rejected
95
resolve (promise) is used
when you want your promise to succeed
96
reject (promise) is used
when you want the promise to fail
97
using promise and reject in the promise body
``` const makeServerRequest = new Promise((resolve, reject) => { // responseFromServer represents a response from a server let responseFromServer; ``` ``` if(responseFromServer) { resolve("We got the data"); } else { reject("Data not received"); } }); ```
98
Promises are most useful when
you have a process that takes an unknown amount of time in your code (i.e. something asynchronous), often a server request.
99
The then method is executed ____after your promise is fulfilled with resolve.
immediately
100
example code of a then in promise
``` myPromise.then(result => { // do something with the result. }); ``` //result comes from the argument given to the resolve method
101
catch is the method used when
your promise has been rejected. executed, just like then, immediately after reject is called
102
syntax for catch in promise
``` myPromise.catch(error => { // do something with the error. }); ``` //error is the argument passed in to the reject method
103
Arrow functions allow us to...
write shorter function syntax instead of hello = function() { return "Hello World!"; } you write hello = () => { return "Hello World!"; }
104
If the arrow function has only one statement, and the statement returns a value...
you can remove the brackets and the return keyword: hello = () => "Hello World!";
105
Which method will return a new array without changing the original array? Out of slice(), push(), pop(), shift()
slice()
106
What will be the result of using the shift() method on an empty array?
undefined
107
What will be the output for the following code? const arr = ["o", "l", "l", "e", "h"]; console.log(arr.join(""));
"olleh"
108
What is array destructuring?
It is used to extract values from arrays and assign them to variables in a more concise and readable way.
109
What does the rest syntax do?
It is used to add elements to the end of the array and will return the new length.