Javascript 1 Flashcards

1
Q

Which way is the slash to escape characters in a string?

A

\ (backslash)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
How to escape these characters...
newline
tab
quote
backslash
A

\n newline
\t tab
" quote
\ backslash

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

How to popup a prompt to ask for input and save to a variable?

A
Use the window object's prompt method:
let name = window.prompt( "Please enter your name" );
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What’s the difference between a function and a method?

A

A method is a function that belongs to an object (must be preceded by object and dot).

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

What object is writeln() a method of?

What object is prompt() a method of?

A

document. writeln(“hello”);

window. prompt(“Enter a number”);

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

What is parseInt()’s optional second argument?

A

The radix is the 2nd argument. By default it’s 10 for base 10, but you can provide 8 for octal or 16 for hexadecimal.

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

switch ( n )
{
case 1:
document.writeln( “The number is 1” );
case 2:
document.writeln( “The number is 2” );
break;
default:
document.writeln( “The number is not 1 or 2” );
break;

A

Missing break on case 1 will cause fallthrough and case 2 executing.

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

Sum the odd integers between 1 and 99.

A

sum = 0;
for ( count = 1; count <= 99; count += 2 )
sum += count;

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

Print the integers from 1 to 20 by using a while loop and the counter variable x. Assume
that the variable x has been declared, but not initialized. Print only five integers per line.
[Hint: Use the calculation x % 5. When the value of this expression is 0, start a new
paragraph in the HTML5 document.

A
let x = 1;
document.writeln( "<p>" );
while ( x <= 20 ) {
  document.write( x + " " );
  if ( x % 5 == 0 )
   document.write( "</p><p>" );
   \++x;
}</p>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

T or F: The default case is required in the switch selection statement.

A

False. If no default action is needed, then there’s no need for a default case.

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

T or F: The break statement is required in the last case of a switch selection statement.

A

False.

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

Find the maximum of three floating point values

A

Math.max(x, Math.max(y, z));

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

Display each integer with a 10px margin between them (margin-right)
——————–
Consider an inline list.

A

p, ol { margin: 0; }
li { display: inline; margin-right: 10px; }

     var value;
     document.writeln( "<p>Random Numbers</p><ol>" );
         for ( var i = 1; i <= 30; ++i ) 
         {
            value = Math.floor( 1 + Math.random() * 6 );
            document.writeln( "<li>" + value + "</li>" );
         } // end for
         document.writeln( "</ol>" );
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Roll-dice (display random images)

A

Random Dice Images

     li { display: inline; margin-right: 10px; }
     ul { margin: 0; }
         // variables used to interact with the img elements
         var die1Image;
         var die2Image;
         var die3Image;
         var die4Image;
         // register button listener and get the img elements
         function start()
         {
            var button = document.getElementById( "rollButton" );
            button.addEventListener( "click", rollDice, false );
            die1Image = document.getElementById( "die1" );
            die2Image = document.getElementById( "die2" );
            die3Image = document.getElementById( "die3" );
            die4Image = document.getElementById( "die4" );
         } // end function start
         // roll the dice
         function rollDice()
         {
            setImage( die1Image );
            setImage( die2Image );
            setImage( die3Image );
            setImage( die4Image );
         } // end function rollDice
     // set src and alt attributes for a die
     function setImage( dieImg )
     {
        var dieValue = Math.floor( 1 + Math.random() * 6 );
        dieImg.setAttribute( "src", "die" + dieValue + ".png" );
        dieImg.setAttribute( "alt", 
           "die image with " + dieValue + " spot(s)" );
     } // end function setImage

     window.addEventListener( "load", start, false );
      <ol>
         <li><img></li>
         <li><img></li>
         <li><img></li>
         <li><img></li>
      </ol>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Submit
Forget

A

Both buttons submit the form. In order to determine which one was clicked in Javascript or PHP you’d need to give id or other solution.

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

Describe addEventListener and its parameters

A

target. addEventListener(type, listener[, options]);
1) the first is the name of the event for which we’re registering a handler
2) the second is the function that will be called to handle the event

3) the last argument is optional and typically false—. A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.
true - The event handler is executed in the capturing phase
false- Default. The event handler is executed in the bubbling phase

17
Q

What does the following code do?

window. addEventListener( “load”, start, false );

A

Registers the window’s load event handler. The function start will execute as soon as the page finishes loading.

18
Q

What does a Javascript switch look like?

A
switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}
19
Q

__________

Submit

A

Nothing because both submit form but buttons can contain HTML content

20
Q

Generate a random number between 1 and 6.

A

value = Math.floor( 1 + Math.random() * 6 );

21
Q

Describe what the following code does:

face = Math.floor( a + Math.random() * b );

A

a is the shifting value (which is equal to the first number in the desired range of
consecutive integers) and b is the scaling factor (which is equal to the width of the desired range of consecutive integers).

22
Q

What’s the primary difference between local storage and session storage?

A

Local storage: data persists even when page is refreshed or browser closed.

Session storage: data will get cleared when browser is closed.

23
Q

What can localStorage store?

A
  • You can set key: value pairs.
  • You can only store strings.
  • You can store arrays and objects, but you have to turn them into strings first, using a method called JSON.stringify() and JSON.parse().
24
Q

What four methods can be used with local storage?

A

setItem() - add a key and value
getItem() - retrieve a value by key
removeItem() - remove an item by key
clear() - clear all storage, data becomes null

25
Q

Use local storage to save a name variable as Pedro.
Then retrieve it from local storage.

(HINT: gi & si)

A
localStorage.setItem('name', 'Pedro');
const name = localStorage.getItem('name');
26
Q

Local storage stores what data type? Say you had an array you wrote to localStorage. Read it back from local storage into an array.

Hint: (gi)

(HINT: J.p(…))

(HINT:

A
Local storage stores strings.
const tasks = JSON.parse(localStorage.getItem('tasks'));

tasks.forEach(function(task){
console.log(task)
})

27
Q

Print out each element of an array to console. Don’t use a “for” loop. Spoilers below.

(Hint: the array is called “tasks”)

(Hint: use fe)

A

tasks.forEach(function(task){
console.log(task)
})

28
Q

What does JSON.parse(txt) do?

var thing = JSON.parse(txt);

What two types of return values does JSON.parse have?

A

JSON text string txt JSON.parse returns an object if txt contains object or Array if it’s an array that’s in txt.

txt should have been written with JSON.stringify

29
Q

Make a JSON string with a name, John, an age, 30, and a city of New York.

A
const myObj = {
   name: 'John',
   age: 30,
   city: 'New York'
};
const myObjStr = JSON.stringify(myObj);
30
Q
const myObj = {
  name: 'Skip',
  age: 2,
  favoriteFood: 'Steak'
};

const myObjStr = JSON.stringify(myObj);

console.log(myObjStr);

A

”{“name”:”Skip”,”age”:2,”favoriteFood”:”Steak”}”

31
Q
const myObj = {
  name: 'Skip',
  age: 2,
  favoriteFood: 'Steak'
};

const myObjStr = JSON.stringify(myObj);

console.log(JSON.parse(myObjStr));

A

Object {name:”Skip”,age:2,favoriteFood:”Steak”}

32
Q
const myArr = ['bacon', 'letuce', 'tomatoes'];
Print out myArr as a JSON string.
A

console.log(JSON.stringify(myArr);
Stringify writes object or array to a string.
output:
“[“bacon”,”letuce”,”tomatoes”]”

33
Q

ingrStr = “[“bacon”,”letuce”,”tomatoes”]”;

Display to console what value is read from ingr as a JSON string

Hint: Jp

A

console.log(JSON.parse(ingrStr);
JSON.parse takes a JSON string and returns an array or object.
[“bacon”,”letuce”,”tomatoes”]

An array