Skip to content

Latest commit

 

History

History
1217 lines (806 loc) · 15.1 KB

book1-chap2-quiz.answers.md

File metadata and controls

1217 lines (806 loc) · 15.1 KB

Quiz - YDKJS: Up & Going 2/3

Chapter 2: Into JavaScript

Answer Sheet

Section: Values & Types


1. Name the 7 built-in types available in JavaScript.

undefined

object

boolean

number

string

symbol

function

2. Name the two ways to access object properties.

dot notation .

brackets notation []

3. Typeof. Look at the following snippets and write what would be the ouput.
Snippet #1
console.log(typeof a);
var a;

"undefined"

Snippet #2
console.log(typeof "hello world");

"string"

Snippet #3
console.log(typeof false);

"boolean"

Snippet #4
console.log(typeof 21);

"number"

Snippet #5
console.log(typeof null);

"object"

Snippet #6
console.log(typeof undefined);

"undefined"

Snippet #7
console.log(typeof { name: "John" });

"object"

Snippet #8
console.log(typeof typeof 42);

"string"

Snippet #9
console.log(typeof 3.1416);

"number"

Snippet #10
console.log(typeof "10");

"string"

Snippet #11
var person = {
  name: "Peter",
  age: 40
};

console.log(typeof person.name);
console.log(typeof person.age);
console.log(typeof person.lastName);

"string"

"number"

"undefined"

Snippet #12
console.log(typeof []);

"object"

Snippet #13
console.log(typeof ["Hello", 20, true][2]);

"boolean"

Snippet #14
console.log(typeof ["Hello", 20, true][3]);

"undefined"

Snippet #15
console.log(typeof { a: 2 }["a"]);

"number"

Snippet #16
var index = "c";
console.log({ a: 1, b: 2, c: 3 }[index]);

3

Snippet #17
console.log({ x: 100, y: 200 }.x);

100

Snippet #18
function getX (point) {
  return point.x;
}

getX.PI = '3.1416';

console.log(typeof getX);
console.log(typeof getX({ x: 34, y: 54 }));
console.log(typeof getX.PI);

"function"

"number"

"string"

Snippet #19
var n = "47";
console.log(typeof n);
console.log(typeof Number(n));

"string"

"number"

Snippet #20
var n = "47";
console.log(typeof (n * 2));

"number"

4. Coercion. Label the following code snippets with explicit or implicit accordingly.
Snippet #21
var a = "13";
var b = a * 2;
console.log(a); // "13"
console.log(b); // 26

implicit

Snippet #22
var a = "13";
var b = Number(a);
console.log(a); // "13"
console.log(b); // 13

explicit

5. List the falsy values in JS.

"" or '' empty string

0, -0, NaN zero, -zero, not a number

null object

undefined undefined

false boolean

6. Boolean Coercion. Write the result true or false for the following snippets.
Snippet #23
Boolean('');

false

Snippet #24
Boolean('.');

true

Snippet #25
Boolean("");

false

Snippet #26
Boolean(0);

false

Snippet #26-2
Boolean("0");

true

Snippet #27
Boolean(1);

true

Snippet #28
Boolean(1/0);

true

Snippet #29
Boolean(0/1);

false

Snippet #30
Boolean(NaN);

false

Snippet #31
Boolean(Infinity);

true

Snippet #32
Boolean(0 + "0");

true

Snippet #33
Boolean("0" + 0);

true

Snippet #34
Boolean("0" * 1);

false

Snippet #35
Boolean(1 * "0");

false

Snippet #36
Boolean(-1 * 0);

false

Snippet #37
Boolean(null);

false

Snippet #38
Boolean(undefined);

false

Snippet #39
Boolean(false);

false

Snippet #40
Boolean(true);

true

Snippet #41
Boolean([]);

true

Snippet #42
Boolean([1, 2, 3]);

true

Snippet #43
Boolean([0].toString());

true

Snippet #43-2
Boolean([1, '', {}][1]);

false

Snippet #43-3
Boolean([1, '', { n: 0 }][2].n);

false

Snippet #44
Boolean([].toString());

false

Snippet #45
Boolean({});

true

Snippet #45-2
Boolean({}.toString());

true

Snippet #46
Boolean({ name: "Doe" });

true

Snippet #47
Boolean({ toString: function () {
  return '';
}}.toString());

false

Snippet #48
Boolean({ number: 0 }.number);

false

Snippet #49
Boolean({ char: 'a' }.char);

true

Snippet #50
Boolean(function noop() {});

true

7. Operator that checks for value equality with coercion allowed:

==

8. Operator that checks for value equality without allowing coercion:

===

9. Operator that checks for value non-equality with coercion allowed:

!=

10. Operator that checks for value non-equality without allowing coercion:

!==

11. Equality Coercion. Write the result true or false for the following snippets:
Snippet #51
"12" == 12;

true

Snippet #51-2
12 === "12";

false

Snippet #52
1 == true;

true

Snippet #52-2
true === 1;

false

Snippet #53
false == 0;

true

Snippet #54
false == "false";

false

Snippet #55
"" == false;

true

Snippet #56
null == false;

false

Snippet #57
undefined == null;

true

Snippet #58
false == undefined;

false

Snippet #59
0 == "";

true

Snippet #60
0 == null;

false

Snippet #61
var a;
a == null;

true

Snippet #62
({} == {});

false

Snippet #63
({} === {});

false

Snippet #64
 [] == [];

false

Snippet #65
 [1, 2, 3] === [1, 2, 3];

false

Snippet #66
 [1, 2, 3] == "1,2,3";

true

Snippet #67
 NaN == NaN;

false

Snippet #68
 NaN === NaN;

false

Snippet #68-2
 (function noop (){}) == (function noop (){});

false

Snippet #68-3
 (function noop (){}).toString() == (function noop (){});

true

12. Inequality Coercion. Write true or false for the following snippets
Snippet #69
 2 > "1";

true

Snippet #70
 "a" < "b";

true

Snippet #71
 3 < "a";

false

Snippet #72
 "3" < "a";

true

Snippet #73
 0 > NaN;

false

Variables


13. Are these valid JS indentifiers? Fill the table with true or false
identifier is valid?
Name true
0duck false
last.name false
$account true
_age true
-price false
car[123] false
for false
14. What's hoisting?

when a var declaration is conceptually "moved" to the top of its enclosing scope.

15. Hoisting. What would be the output for this snippet?
Snippet #74
a = 10;

foo ();

function foo () {
  a = 5;

  console.log(a);

  var a;
}

var a;

console.log(a);

5

10

16. What's the main difference between var and let?

var declares variables at function level

let declares variables at block level

17. Nested Scopes, var & let. Write the output for the following code snippets
Snippet #75
var a = 1;

function foo () {
  if (a == 1) {
    var b = 2;
  }

  console.log(b);
}

foo();

2

Snippet #76
var a = 1;

function foo () {
  if (a == 1) {
    let b = 2;
  }

  console.log(b);
}

foo();

Uncaught ReferenceError: b is not defined

Snippet #77
function foo () {
  var a = 10
}

foo();

console.log(a);

Uncaught ReferenceError: a is not defined

Snippet #78
function foo () {
  a = 20
}

foo();

console.log(a);

20

Section: Conditionals


18. Write the code to log if a number is even or odd using the if statement, switch statement and the conditional operator ?: aka ternay operator

Clue: you can determine if a number is even if the remainder of n divided by 2 is equal to 0. Use the remainder operator %.

if Solution:

var n = 10;

if (n % 2 == 0) {
  console.log('even');
} else {
  console.log('odd');
}

switch Solution:

var n = 10;

switch (n % 2) {
  case 0:
    console.log('even');
    break;
  default:
    console.log('odd');
}

ternary Solution:

var n = 10;

console.log(n % 2 == 0 ? "even" : "odd")

Section: Strict Mode


19. In your own words, what's use strict;?

is a way to force code to be better written.

is a way to opt in to a restricted variant of JS.

is a way to avoid bugs.

is the opposite of sloppy mode.

20. Use Strict. Write the output for the following code snippets
Snippet #79
function yummy () {
  a = 50
}

yummy();

console.log(a);

50

Snippet #80
'use strict';

function yummy () {
  a = 50
}

yummy();

console.log(a);

Uncaught ReferenceError: a is not defined

Section: Functions As Values


21. Complete the sentence

Functions are the primary mechanism of _____ in JS.

scope

22. Create a function square that takes one parameter number that returns the result of that number multiplied by itself. You need to perform this in 3 different ways
22.1. by using function declaration syntax.

Solution:

function square (number) {
  return number * number;
}
22.2. by using function expression with an anonymous function syntax.

Solution:

var square = function (number) {
  return number * number;
};
22.3 by using function expression with a named function syntax.

Solution:

var square = function square (number) {
  return number * number;
};
23. What's an IIFE? Give an example.

an Immediately Invoked Function Expression

example:

(function hello () {
  console.log("hello!");
})();
24. What's a closure in JS?

a closure is the combination of a function and the lexical environment within which that function was declared.

25. Closure. What would be the output for the following code?
Snippet #81
function createHello (greeting) {
  return function greet (name) {
    return greeting + " " + name + "!";
  }
}

var greetInSpanish = createHello('Hola');

console.log(greetInSpanish("Pedro"));
console.log(createHello('Hi')("Mike"));

"Hola Pedro!"

"Hi Mike!"

Section: this Keyword


26. this. Write the output for the following code
Snippet #82
// Kitties
function sayHello() {
  console.log("Hello " + this.name);
}

var name = "Fluffy";

sayHello();

var kitty = {
  name: "Buttercup",
  sayHello: sayHello
};

kitty.sayHello();

sayHello.call({ name: "Cocoa" });

new sayHello();

"Hello Fluffy"

"Hello Buttercup"

"Hello Cocoa"

"Hello undefined"

Section: Prototypes


27. Prototypes. Write the output for the following code
Snippet #83
var animal = {
  walk: "I'm walking!"
};

var bird = Object.create(animal);

bird.fly = "I'm flying!";

var penguin = Object.create(bird);

penguin.fly = "I can't fly :(";
penguin.swim = "I'm swimming!";

var canary = Object.create(bird);

var tiger = Object.create(animal);

console.log(tiger.walk);
console.log(tiger.fly);
console.log(canary.fly);
console.log(canary.walk);
console.log(canary.swim);
console.log(penguin.fly);
console.log(penguin.walk);
console.log(penguin.swim);

"I'm walking!"

"undefined"

"I'm flying!"

"I'm walking!"

"undefined"

"I can't fly: :("

"I'm walking!"

"I'm swimming!"

Section: Old & New


28. What are the two main techniques to make older browsers work with newer features available in JS? Describe each

polyfilling. A piece of code that provides the techonology that you expect the browser to provide natively.

transpiling. The process that converts your newer code into older code equivalents.

Section: Non-JavaScript


29. Is the alert method provided by the JS engine?

nope, alert is provided by the browser.

Section: Challenges


2.1 Create a module in an IIFE stored in a variable calculator that exposes 4 methods: plus, minus, times and dividedBy. Each method should receive one parameter firstNumber and return a function that receives another parameter secondNumber. Every method should perform the operation it describes, for example, it's expected that plus adds the firstNumber to the secondNumber, dividedBy should divide the secondNumber by the firstNumber and so on. The idea is to have "stored" the firstNumber to perform the next operations with it.

TIP: You can create a script.jsfile and test your code in the browser or node.js.

Solution:

// create your calculator module here
var calculator = (function calc () {
  function plus (firstNumber) {
    return function addTo (secondNumber) {
      return secondNumber + firstNumber;
    }
  }

  function minus (firstNumber) {
    return function subtractTo (secondNumber) {
      return secondNumber - firstNumber;
    }
  }

  function times (firstNumber) {
    return function multiplyTo (secondNumber) {
      return secondNumber * firstNumber;
    }
  }

  function dividedBy (firstNumber) {
    return function divideTo (secondNumber) {
      return secondNumber / firstNumber;
    }
  }

  return {
    plus: plus,
    minus: minus,
    times: times,
    dividedBy: dividedBy
  };
})();

// Do NOT touch this code
const testCases = [
  { type: "plus", n1: 3, n2: [1, 2, 3], expected: [4, 5, 6] },
  { type: "minus", n1: 1, n2: [1, 0, -1], expected: [0, -1, -2] },
  { type: "times", n1: 5, n2: [2, 5, 10], expected: [10, 25, 50] },
  { type: "dividedBy", n1: 10, n2: [10, 100, 1000], expected: [1, 10, 100] }
];

const result = testCases.every(test => {
  const operation = calculator[test.type](test.n1);
  return test.n2.every((number, i) => {
    const testPassed = operation(number) === test.expected[i];
    if (!testPassed) {
      console.log(`Expected: ${operation(number)} to be: ${test.expected[i]}. Operation: secondNumber(${number}) ${test.type} firstNumber(${test.n1})`);
    }
    return testPassed;
  });
});

console.log("All tests passed: ", result);