Javascript Flashcards

1
Q

What are the different 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 is the modulo and what does it do?

A

It is the % symbol and it represents the remainder operation
X % Y

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

What happens in this case 3 * 11 +4

A

It calculates it using precedence

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

What are the three special values in Javascript?

A

Infinity, -Infinity, and NaN (not a number)

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

What value is “throw that away!”

A

A string

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

In Javascript, how does a program keep an internal state? How does it remember things?

A

To catch and hold values, JavaScript provides a thing called a variable.

var caught = 5 * 5;

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

What’s an expression?

A

A fragment of code that produces a value is called an expression. Every value that is written literally (such as 22 or “psychoanalysis”) is an expression.

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

What’s the difference between an expression and statement?

A

If an expression corresponds to a sentence fragment, a JavaScript statement corresponds to a full sentence in a human language. A program is simply a list of statements.

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

Give an example of an expression.

A

1;

!false;

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

What is a statement able to do that an expression can’t?

A

A statement stands on its own and amounts to something only if it affects the world. It could display something on the screen—that counts as changing the world—or it could change the internal state of the machine in a way that will affect the statements that come after it. These changes are called side effects.

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

What’s happening?

var mood = "light";
console.log(mood);
// → light
mood = "dark";
console.log(mood);
// → dark
A

When a variable points at a value, that does not mean it is tied to that value forever. The = operator can be used at any time on existing variables to disconnect them from their current value and have them point to a new one.

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

Variables are akin to?

A

You should imagine variables as tentacles, rather than boxes. They do not contain values; they grasp them—two variables can refer to the same value. A program can access only the values that it still has a hold on. When you need to remember something, you grow a tentacle to hold on to it or you reattach one of your existing tentacles to it.

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

Can a single var statement define multiple statements?

A

Yes, A single var statement may define multiple variables. The definitions must be separated by commas

var one = 1, two = 2;
console.log(one + two);
// → 3
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What’s a keyword?

A

Words with a special meaning, such as var, are keywords, and they may not be used as variable names. There are also a number of words that are “reserved for use” in future versions of JavaScript. These are also officially not allowed to be used as variable names, though some JavaScript environments do allow them.

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

What’s an environment?

A

The collection of variables and their values that exist at a given time is called the environment. When a program starts up, this environment is not empty. It always contains variables that are part of the language standard, and most of the time, it has variables that provide ways to interact with the surrounding system. For example, in a browser, there are variables and functions to inspect and influence the currently loaded website and to read mouse and keyboard input.

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

What’s a function?

A

A lot of the values provided in the default environment have the type function. A function is a piece of program wrapped in a value. Such values can be applied in order to run the wrapped program. For example, in a browser environment, the variable alert holds a function that shows a little dialog box with a message. It is used like this:

alert(“Good morning!”);

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

How do you execute a function and what’s it called?

A

Executing a function is called invoking, calling, or applying it. You can call a function by putting parentheses after an expression that produces a function value.

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

What are the values that go in the parentheses?

A

The values between the parentheses are given to the program inside the function. In the example, the alert function uses the string that we give it as the text to show in the dialog box. Values given to functions are called arguments. The alert function needs only one of them, but other functions might need a different number or different types of arguments.

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

Give an example of an argument

A

alert(“Good morning!”);

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

What’s the purpose of the console.log function?

A

The alert function can be useful as an output device when experimenting, but clicking away all those little windows will get on your nerves. In past examples, we’ve used console.log to output values.

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

What’s a side effect?

A

Showing a dialog box or writing text to the screen is a side effect. A lot of functions are useful because of the side effects they produce. Functions may also produce values, and in that case, they don’t need to have a side effect to be useful.

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

What’s a return value?

A

When a function produces a value, it is said to return that value. Anything that produces a value is an expression in JavaScript, which means function calls can be used within larger expressions.

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

What’s happening here:

console.log(Math.min(2, 4) + 100);
// → 102
A

Here a call to Math.min, which is the opposite of Math.max, is used as an input to the plus operator:

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

What happens when user selects OK when a confirm pops up and what happens in the following code?

confirm(“Shall we, then?”);

A

This returns a Boolean: true if the user clicks OK and false if the user clicks Cancel.

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

What happens here?

prompt(“Tell me everything you know.”, “…”);

A

The prompt function can be used to ask an “open” question. The first argument is the question, the second one is the text that the user starts with. A line of text can be typed into the dialog window, and the function will return this text as a string.

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

Why aren’t prompt and confirm functions used in web programming?

A

These two functions aren’t used much in modern web programming, mostly because you have no control over the way the resulting windows look, but they are useful for toy programs and experiments.

27
Q

Why is it important to declare with “var”?

A

When you fail to specify var, the variable gets placed in the global context, potentially clobbering existing values. Also, if there’s no declaration, it’s hard to tell in what scope a variable lives (e.g., it could be in the Document or Window just as easily as in the local scope). So always declare with var.

28
Q

Why is it important to end assignments with a semicolons?

A

JavaScript requires statements to end with a semicolon, except when it thinks it can safely infer their existence. In each of these examples, a function declaration or object or array literal is used inside a statement. The closing brackets are not enough to signal the end of the statement. Javascript never ends a statement if the next token is an infix or bracket operator.

This has really surprised people, so make sure your assignments end with semicolons.

29
Q

When can semicolons be omitted?

A

Semicolons should be included at the end of function expressions, but not at the end of function declarations. The distinction is best illustrated with an example:

var foo = function() {
  return true;
};  // semicolon here.
function foo() {
  return true;
}  // no semicolon here.
30
Q

What does it mean when a program is executed in straight control flow?

A

When your program contains more than one statement, the statements are executed, predictably, from top to bottom. As a basic example, this program has two statements. The first one asks the user for a number, and the second, which is executed afterward, shows the square of that number.

var theNumber = Number(prompt(“Pick a number”, “”));
alert(“Your number is the square root of “ +
theNumber * theNumber);

The function Number converts a value to a number. We need that conversion because the result of prompt is a string value, and we want a number. There are similar functions called String and Boolean that convert values to those types.

31
Q

What’s another way to execute a program?

A

Executing statements in straight-line order isn’t the only option we have. An alternative is conditional execution, where we choose between two different routes based on a Boolean value.

32
Q

How is a conditional execution written?

A

Conditional execution is written with the if keyword in JavaScript. In the simple case, we just want some code to be executed if, and only if, a certain condition holds. For example, in the previous program, we might want to show the square of the input only if the input is actually a number.

var theNumber = Number(prompt(“Pick a number”, “”));
if (!isNaN(theNumber))
alert(“Your number is the square root of “ +
theNumber * theNumber);

With this modification, if you enter “cheese”, no output will be shown.

33
Q

How does the following code work?

var theNumber = Number(prompt(“Pick a number”, “”));
if (!isNaN(theNumber))
alert(“Your number is the square root of “ +
theNumber * theNumber);

A

The keyword if executes or skips a statement depending on the value of a Boolean expression. The deciding expression is written after the keywords, between parentheses, followed by the statement to execute.

The isNaN function is a standard JavaScript function that returns true only if the argument it is given is NaN. The Number function happens to return NaN when you give it a string that doesn’t represent a valid number. Thus, the condition translates to “unless theNumber is not-a-number, do this”.

34
Q

What happens when the condition doesn’t hold true?

A

You often won’t just have code that executes when a condition holds true, but also code that handles the other case. This alternate path is represented by the second arrow in the diagram. The else keyword can be used, together with if, to create two separate, alternative execution paths.

var theNumber = Number(prompt(“Pick a number”, “”));
if (!isNaN(theNumber))
alert(“Your number is the square root of “ +
theNumber * theNumber);
else
alert(“Hey. Why didn’t you give me a number?”);

35
Q

How do you write a program that has more than two paths?

A

If we have more than two paths to choose from, multiple if/else pairs can be “chained” together.

36
Q

How does this code work?

var num = Number(prompt(“Pick a number”, “0”));

if (num < 10)
  alert("Small");
else if (num < 100)
  alert("Medium");
else
  alert("Large");
A

The program will first check whether num is less than 10. If it is, it chooses that branch, shows “Small”, and is done. If it isn’t, it takes the else branch, which itself contains a second if. If the second condition (< 100) holds, that means the number is between 10 and 100, and “Medium” is shown. If it doesn’t, the second, and last, else branch is chosen.

37
Q

When do you run this code “ counter += 1; “

A

Especially when looping, a program often needs to “update” a variable to hold a value based on that variable’s previous value.

38
Q

How can you rewrite this efficiently?

console. log(0);
console. log(2);
console. log(4);
console. log(6);
console. log(8);
console. log(10);
console. log(12);

A

Looping control flow allows us to go back to some point in the program where we were before and repeat it with our current program state. If we combine this with a variable that counts, we can do something like this:

var number = 0;
while (number <= 12) {
  console.log(number);
  number = number + 2;
}
// → 0
// → 2
//   … etcetera

A statement starting with the keyword while creates a loop. The word while is followed by an expression in parentheses and then a statement, much like if. The loop executes that statement as long as the expression produces a value that is true when converted to Boolean type.

The variable number demonstrates the way a variable can track the progress of a program. Every time the loop repeats, number is incremented by 2. Then, at the beginning of every repetition, it is compared with the number 12 to decide whether the program has done all the work it intended to do.

39
Q

we’ve seen how to control our programs given a single condition: whether one variable is equal to a certain value, for instance. But what if we want to check more than one variable?

A

For this, we’ll need logical operators. JavaScript has three: and (&&), or (||), and not (!).

Using these, we can check several variables at once! Check out the code in the editor.

40
Q

How does the logical operator “and” work, how is it written?

A

The logical operator and is written in JavaScript like this: &&. It evaluates to true when both expressions are true; if they’re not, it evaluates to false.

41
Q

How does the logical operator “or” work, how is it written?

A

The logical operator or is written in JavaScript like this: ||. It evaluates to true when one or the other or both expressions are true; if they’re not, it evaluates to false.

true || true; // => true
true || false; // => true
false || true; // => true
false || false; // => false

The or operator is written with two vertical bars ||. The vertical bar character is located right above the Enter key on your keyboard.

42
Q

How does the logical operator “not” work, how is it written?

A

The logical operator not is written in JavaScript like this: !. It makes true expressions false, and vice-versa.

!true; // => false
!false; // => true

43
Q

Write an if / else statement inside the isEven function. It should return true; if the number it receives is evenly divisible by 2. Otherwise (else), it should return false;.

Make sure to return - don’t use console.log()!

A

Hint
Remember, you can use modulo (%) to see if a number is evenly divisible by another number.

Be sure to return true; or return false; in your code—don’t console.log()!

44
Q

How does the function NaN work?

A

If you call isNaN on something, it checks to see if that thing is not a number. So:

isNaN(‘berry’); // => true
isNaN(NaN); // => true
isNaN(undefined); // => true
isNaN(42); // => false

45
Q

What should you be careful of calling is NaN?

A

Be careful: if you call isNaN on a string that looks like a number, like ‘42’, JavaScript will try to help by automatically converting the string ‘42’ to the number 42 and return false (since 42 is a number).

Note that you can’t just do

isNaN(unicorns);
unless you’ve already defined the variable unicorns. You can, however, do

isNaN(“unicorns”); // => true

46
Q

if you have a lot of choices you want to cover in a program, it might be annoying to type else if () ten times. What do you do in Javascript?

A

That’s why JavaScript has the switch statement!

switch allows you to preset a number of options (called cases), then check an expression to see if it matches any of them. If there’s a match, the program will perform the action for the matching case; if there’s no match, it can execute a default option.

47
Q

What’s happening here:

var lunch = prompt(“What do you want for lunch?”,”Type your lunch choice here”);

switch(lunch){
  case 'sandwich':
    console.log("Sure thing! One sandwich, coming up.");
    break;
  case 'soup':
    console.log("Got it! Tomato's my favorite.");
    break;
  case 'salad':
    console.log("Sounds good! How about a caesar salad?");
    break;
  case 'pie':
    console.log("Pie's not a meal!");
    break;
  default:
    console.log("Huh! I'm not sure what " + lunch + " is. How does a sandwich sound?");
}
A

The switch statement is put together like this:

switch (/*Some expression*/) {
    case 'option1':
        // Do something
        break;
    case 'option2':
        // Do something else
        break;
    case 'option3':
        // Do a third thing
        break;
    default:
       // Do yet another thing
}
JavaScript will try to match the expression between the switch() parentheses to each case. It will run the code below each case if it finds a match, and will execute the default code if no match is found.
48
Q

What do the following functions do and why do you use them?

.toUpperCase() and .toLowerCase()

A

This converted the user’s answer to ALL CAPS before saving it in the answer variable. This helps eliminate problems that might crop up if your program tests for ‘YES’ but your user typed in ‘yes’ or ‘Yes’. The input becomes all caps before we test, so we only have to test for all caps!

You can also use .toLowerCase(), which converts a string to all lower-case letters.

49
Q

Do you remember how to access an element of an array by offset (with the [] notation)?

A

Remember, you can access an array’s element like this:

var element = array[index];
If you want the first element of languages, you'd type

languages[0];
because arrays start counting their elements at 0.

50
Q

How do you iterate over an array?

A

By combining all these ideas with a for loop, you can iterate over the languages array and print out each element in turn!

var languages = [“HTML”, “CSS”, “JavaScript”, “Python”, “Ruby”]

for (languages = 0; languages < languages.length; languages++){
console.log(languages);

}
51
Q

What are Heterogeneous arrays?

A

it’s not necessary for you to put the same type of data in an array! For instance, you don’t have to have

var pronouns = ["I", "you", "we"];
var numbers = [1, 2, 3];
You can have a heterogeneous array, which means a mixture of data types, like so:

var mix = [42, true, “towel”];

52
Q

What’s Arrays of arrays?

A

not only can you put a mixture of types in an array, you can even put other arrays inside arrays. You can make a two-dimensional array by nesting arrays one layer deep, like so:

var twoDimensional = [[1, 1], [1, 1]];
This array is two-dimensional because it has two rows that each contain two items. If you were to put a new line between the two rows, you could log a 2D object—a square—to the console, like so:

[1, 1]
[1, 1]

53
Q

What’s wrong with this?

var numSheep = 4;
var monthNumber = 1;
var monthsToPrint = 12;

while (monthNumber );
numSheep *= 4, monthNumber++;
}

A
var numSheep = 4;
var monthNumber = 1;
var monthsToPrint = 12;

while(monthNumber );
monthNumber++;
}

54
Q

What’s a function and how do they work?

A

A function is created by an expression that starts with the keyword function. Functions have a set of parameters (in this case, only x) and a body, which contains the statements that are to be executed when the function is called. The function body must always be wrapped in braces, even when it consists of only a single statement (as in the previous example).

55
Q

What’s an anonymous function?

A
var square = function(x) {
  return x * x;
};
console.log(square(12));
// → 144
56
Q

How parameters can a function have?

A

A function can have multiple parameters or no parameters at all. In the following example, makeNoise does not list any parameter names, whereas power lists two:

var makeNoise = function() {
  console.log("Pling!");
};
makeNoise();
// → Pling!
var power = function(base, exponent) {
  var result = 1;
  for (var count = 0; count < exponent; count++)
    result *= base;
  return result;
};
console.log(power(2, 10));
// → 1024
57
Q

How does the return statement work within a function?

A

A return statement determines the value the function returns. When control comes across such a statement, it immediately jumps out of the current function and gives the returned value to the code that called the function. The return keyword without an expression after it will cause the function to return undefined.

58
Q

What are important properties of a function?

A

The parameters to a function behave like regular variables, but their initial values are given by the caller of the function, not the code in the function itself.

An important property of functions is that the variables created inside of them, including their parameters, are local to the function. This means, for example, that the result variable in the power example will be newly created every time the function is called, and these separate incarnations do not interfere with each other.

var makeNoise = function() {
  console.log("Pling!");
};
makeNoise();
// → Pling!
var power = function(base, exponent) {
  var result = 1;
  for (var count = 0; count < exponent; count++)
    result *= base;
  return result;
};
console.log(power(2, 10));
// → 1024
59
Q

How does a local and global variable work?

A

This “localness” of variables applies only to the parameters and to variables declared with the var keyword inside the function body. Variables declared outside of any function are called global, because they are visible throughout the program. 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.

The following code demonstrates this. It defines and calls two functions that both assign a value to the variable x. The first one declares the variable as local and thus changes only the local variable. The second does not declare x locally, so references to x inside of it refer to the global variable x defined at the top of the example.

var x = “outside”;

var f1 = function() {
  var x = "inside f1";
};
f1();
console.log(x);
// → outside
var f2 = function() {
  x = "inside f2";
};
f2();
console.log(x);
// → inside f2
60
Q

How does a local variable help?

A

This behavior helps prevent accidental interference between functions. If all variables were shared by the whole program, it’d take a lot of effort to make sure no name is ever used for two different purposes. And if you did reuse a variable name, you might see strange effects from unrelated code messing with the value of your variable. By treating function-local variables as existing only within the function, the language makes it possible to read and understand functions as small universes, without having to worry about all the code at once.

61
Q

What’s a Nested Scope?

A

JavaScript distinguishes not just between global and local variables. Functions can be created inside other functions, producing several degrees of locality.

For example, this rather nonsensical function has two functions inside of it:

var landscape = function() {
  var result = "";
  var flat = function(size) {
    for (var count = 0; count < size; count++)
      result += "_";
  };
  var mountain = function(size) {
    result += "/";
    for (var count = 0; count < size; count++)
      result += "'";
    result += "\\";
  };
  flat(3);
  mountain(4);
  flat(6);
  mountain(1);
  flat(1);
  return result;
};
console.log(landscape());
// → \_\_\_/''''\\_\_\_\_\_\_/'\_
The flat and mountain functions can “see” the variable called result, since they are inside the function that defines it. But they cannot see each other’s count variables since they are outside each other’s scope. The environment outside of the landscape function doesn’t see any of the variables defined inside landscape.
62
Q

What is the difference between the following lines of code:

//Function declaration
function foo() { return 5; }
//Anonymous function expression
var foo = function() { return 5; }
//Named function expression
var foo = function foo() { return 5; }
A

They’re actually really similar. How you call them is exactly the same, but the difference lies in how the browser loads them into the execution context.

function declarations loads before any code is executed.

While function expressions loads only when the interpreter reaches that line of code.

So if you try to call a function expression before it’s loaded, you’ll get an error

But if you call a function declaration, it’ll always work. Because no code can be called until all declarations are loaded.

ex. Function Expression

alert(foo()); // ERROR! foo wasn’t loaded yet
var foo = function() { return 5; }
ex. Function Declaration

alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }
As for the second part of your questions.

var foo = function foo() { return 5; } is really the same as the other two. It’s just that this line of code used to cause an error in safari, though it no longer does.

63
Q

What parts does an HTTP request consist of?

A
An HTTP request consists of four parts:
• the HTTP request method or “verb”
• the URL being requested
• an optional set of request headers, which may include authentication information
• an optional request body