Chapter 1 Values, Types, and Operators Flashcards

1
Q

What are the six basic types of values in JavaScript

A

numbers, strings, Booleans, objects, functions, and undefined values.

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

What are the three special values in JavaScript that are considered numbers but don’t behave like normal numbers.

A

The first two are Infinity and -Infinity, which represent the positive and negative infinities. Infinity - 1 is still Infinity, and so on. Don’t put too much trust in infinity-based computation. It isn’t mathematically solid, and it will quickly lead to our next special number: NaN.

NaN stands for “not a number”, even though it is a value of the number type. You’ll get this result when you, for example, try to calculate 0 / 0 (zero divided by zero), Infinity - Infinity, or any number of other numeric operations that don’t yield a precise, meaningful result.

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

What does the typeof operator produce?

A
It produces a string value naming the type of the value you give it.
console.log(typeof 4.5)
// → number
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

There is only one value in JavaScript that is not equal to itself, what is it?

A

NaN
NaN is supposed to denote the result of a nonsensical computation, and as such, it isn’t equal to the result of any other nonsensical computations.

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

What is special about null and undefined?

A

They are used to denote the absence of a meaningful value. They are themselves values, but they carry no information.

Many operations in the language that don’t produce a meaningful value yield undefined simply because they have to yield some value.

The difference in meaning between undefined and null is an accident of JavaScript’s design, and it doesn’t matter most of the time. In the cases where you actually have to concern yourself with these values, I recommend treating them as interchangeable

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

What is type coercion?

A

When an operator is applied to the “wrong” type of value, JavaScript will quietly convert that value to the type it wants, using a set of rules that often aren’t what you want or expect.

console.log(8 * null)
// → 0
console.log("5" - 1)
// → 4
console.log("5" + 1)
// → 51
console.log("five" * 2)
// → NaN
console.log(false == 0)
// → true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the difference between confirm() and prompt()?

A

confirm() has a true or false answer

prompt() is an open ended question

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

An important property of functions is that the variables created inside of them, including their parameters, are local to the function. What does this mean?

A

The variable in a function will be newly created every time the function is called, and these separate incarnations do not interfere with each other.

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

What are variables declared outside of a function called?

A

global variables

It is possible to access such variables from inside a function, as long as you haven’t declared a local variable with the same name.

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

Give an example of function declaration.

A
function square(x) {
  return x * x;
}

The statement defines the variable square and points it at the given function.

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

What is a side effect of defining a function through function declaration?

A

console.log(“The future says:”, future());

function future() {
  return "We STILL have no flying cars.";
}
This code works, even though the function is defined below the code that uses it. This is because function declarations are not part of the regular top-to-bottom flow of control. They are conceptually moved to the top of their scope and can be used by all the code in that scope. This is sometimes useful because it gives us the freedom to order code in a way that seems meaningful, without worrying about having to define all functions above their first use.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the Javascript call stack?

A

The order in which Javascript code is implemented

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

What does it mean when the the computer fails with a message like “out of stack space” or “too much recursion”

A

Storing functions in a call stack requires space in the computer’s memory. When the stack grows too big, the computer will fail with these messages. This can also happen if you write an infinite loop as the computer does not have infinite memory. Also known as “blow the stack”

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

The following code is allowed and executes without any problem:

alert(“Hello”, “Good Evening”, “How do you do?”);
The function alert officially accepts only one argument. Yet when you call it like this, it doesn’t complain.

Explain why

A

JavaScript is extremely broad-minded about the number of arguments you pass to a function. If you pass too many, the extra ones are ignored. If you pass too few, the missing parameters simply get assigned the value undefined.

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

What is closure in Javascript?

A

This feature—being able to reference a specific instance of local variables in an enclosing function—is called closure.

function wrapValue(n) {
  var localVariable = n;
  return function() { return localVariable; };
}
var wrap1 = wrapValue(1);
var wrap2 = wrapValue(2);
console.log(wrap1());
// → 1
console.log(wrap2());
// → 2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is Recursion?

A

When a function calls itself

function power(base, exponent) {
  if (exponent == 0)
    return 1;
  else
    return base * power(base, exponent - 1);
}
console.log(power(2, 3));
// → 8
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a pure function?

A

A pure function is a specific kind of value-producing function that not only has no side effects but also doesn’t rely on side effects from other code

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

What is the difference between value.x and value[x]

A

The difference is in how x is interpreted. When using a dot, the part after the dot must be a valid variable name, and it directly names the property. When using square brackets, the expression between the brackets is evaluated to get the property name. Whereas value.x fetches the property of value named “x”, value[x] tries to evaluate the expression x and uses the result as the property name.

19
Q

What method capitalizes a string in Javascript?

A

.toUpperCase()

20
Q

What method lower cases a string in Javascript?

A

.toLowerCase()

21
Q

How do you create an object in Javascript?

A
var objectName = {
   property: value

}

22
Q

What is the output of this console.log(“right” in anObject);

A

The binary in operator, when applied to a string and an object, returns a Boolean value that indicates whether that object has that property.

23
Q

How do you delete a property from an object?

A

delete anObject.left;

24
Q

How would you write an array that holds objects?

A

var journal = [
{events: [“work”, “touched tree”, “pizza”,
“running”, “television”],
squirrel: false},
{events: [“work”, “ice cream”, “cauliflower”,
“lasagna”, “touched tree”, “brushed teeth”],
squirrel: false},
{events: [“weekend”, “cycling”, “break”,
“peanuts”, “beer”],
squirrel: true}
];

25
Q

When does JavaScript’s == operator return true on an object?

A

JavaScript’s == operator, when comparing objects, will return true only if both objects are precisely the same value. Comparing different objects will return false, even if they have identical contents.

26
Q

What is the difference between indexOf() vs indexOfLast()

A

lastIndexOf, starts searching for the given element at the end of the array instead of the front.

console.log([1, 2, 3, 2, 1].indexOf(2));
// → 1
console.log([1, 2, 3, 2, 1].lastIndexOf(2));
// → 3

27
Q

Define what the slice method does on an array and what input does it take?

A

It takes a start index and an end index and returns an array that has only the elements between those indices. The start index is inclusive, the end index exclusive.

console.log([0, 1, 2, 3, 4].slice(2, 4));
// → [2, 3]
console.log([0, 1, 2, 3, 4].slice(2));
// → [2, 3, 4]
When the end index is not given, slice will take all of the elements after the start index.

28
Q

What does the concat method do?

A

The concat method can be used to glue arrays together, similar to what the + operator does for strings. The following example shows both concat and slice in action. It takes an array and an index, and it returns a new array that is a copy of the original array with the element at the given index removed.

function remove(array, index) {
  return array.slice(0, index)
    .concat(array.slice(index + 1));
}
console.log(remove(["a", "b", "c", "d", "e"], 2));
// → ["a", "b", "d", "e"]
29
Q

What does the The trim method do?

A

The trim method removes whitespace (spaces, newlines, tabs, and similar characters) from the start and end of a string.

console.log("  okay \n ".trim());
// → okay
30
Q

What 2 values in Javascript do not have properties?

A

null and undefined

31
Q

What are Abstractions?

A

Abstractions hide details and give us the ability to talk about problems at a higher (or more abstract) level.

e.g.
using methods like sum and range in a program instead of writing out methods manually. These methods are a little like black boxes but they take care of the little programming details and allows us to focus on bigger problems

32
Q

What does the forEach function do on an array?

A

The forEach() method executes a provided function once for each array element.

var a = [‘a’, ‘b’, ‘c’];

a.forEach(function(element) {
console.log(element);
});

// a
// b
// c
33
Q

What are higher order functions?

A

Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. If you have already accepted the fact that functions are regular values, there is nothing particularly remarkable about the fact that such functions exist. The term comes from mathematics, where the distinction between functions and other values is taken more seriously.

34
Q

Explain what the output of this program will be?

function unless(test, then) {
  if (!test) then();
}
function repeat(times, body) {
  for (var i = 0; i < times; i++) body(i);
}
repeat(3, function(n) {
  unless((n % 2), function() {
    console.log(n, "is even");
  });
});
A
// → 0 is even
// → 2 is even
35
Q

What does JSON stand for?

A

JavaScript Object Notation. It is widely used as a data storage and communication format on the Web.

36
Q

What does JSON.stringify do?

A

It takes a JavaScript value and returns a JSON-encoded string

var string = JSON.stringify({name: "X", born: 1980});
console.log(string);
// → {"name":"X","born":1980}
37
Q

What does JSON.parse do?

A

It takes such a string and converts it to the value it encodes.

var string = JSON.stringify({name: "X", born: 1980});
console.log(JSON.parse(string).born);
// → 1980
38
Q

What does the filter method do?

A

It filters out elements that don’t pass the test

//real use case
console.log(ancestry.filter(function(person) {
  return person.father == "Carel Haverbeke";
}));
// → [{name: "Carolus Haverbeke", …}]
//definition
function filter(array, test) {
  var passed = [];
  for (var i = 0; i < array.length; i++) {
    if (test(array[i]))
      passed.push(array[i]);
  }
  return passed;
}
console.log(filter(ancestry, function(person) {
  return person.born > 1900 &amp;&amp; person.born < 1925;
}));
// → [{name: "Philibert Haverbeke", …}, …]
39
Q

What does the map method do to an array?

A

The map method transforms an array by applying a function to all of its elements and building a new array from the returned values. The new array will have the same length as the input array, but its content will have been “mapped” to a new form by the function.

//definition
function map(array, transform) {
  var mapped = [];
  for (var i = 0; i < array.length; i++)
    mapped.push(transform(array[i]));
  return mapped;
}
var overNinety = ancestry.filter(function(person) {
  return person.died - person.born > 90;
});
console.log(map(overNinety, function(person) {
  return person.name;
}));
// → ["Clara Aernoudts", "Emile Haverbeke",
//    "Maria Haverbeke"]
40
Q

What does the reduce method do on arrarys?

A

Returns a single value from the array.

The parameters to the reduce function are, apart from the array, a combining function and a start value.

If your array contains at least one element, you are allowed to leave off the start argument. The method will take the first element of the array as its start value and start reducing at the second element.

//definition
function reduce(array, combine, start) {
  var current = start;
  for (var i = 0; i < array.length; i++)
    current = combine(current, array[i]);
  return current;
}
console.log(reduce([1, 2, 3, 4], function(a, b) {
  return a + b;
}, 0));
// → 10
41
Q

What is a drawback to using abstractions?

A

They are expensive to use.

Function calls in JavaScript are costly compared to simple loop bodies.

Abstractions add layers between the raw things the computer is doing and the concepts we are working with and thus cause the machine to perform more work.

Fortunately, most computers are insanely fast. If you are processing a modest set of data or doing something that has to happen only on a human time scale (say, every time the user clicks a button), then it does not matter whether you wrote a pretty solution that takes half a millisecond or a super-optimized solution that takes a tenth of a millisecond.

42
Q

Why is it helpful to roughly keep track of how often a piece of your program is going to run?

A

If you have a loop inside a loop (either directly or through the outer loop calling a function that ends up performing the inner loop), the code inside the inner loop will end up running N×M times, where N is the number of times the outer loop repeats and M is the number of times the inner loop repeats within each iteration of the outer loop. If that inner loop contains another loop that makes P rounds, its body will run M×N×P times, and so on. This can add up to large numbers, and when a program is slow, the problem can often be traced to only a small part of the code, which sits inside an inner loop.

43
Q

What does the bind method do?

A

The bind method, which all functions have, creates a new function that will call the original function but with some of the arguments already fixed.