Monday, January 9, 2017

01/09/2017 Javascript Exercises

Very useful reading on array methods:
https://www.bennadel.com/blog/1796-javascript-array-methods-unshift-shift-push-and-pop.htm

Unshift (adds) Shift (removes)| things on the front  vs | Push (adds) Pop (removes) at the end.


  • I was stuck on this exercise-


function nextInLine(arr, item) {
  // Your code here

  return item;  // Change this line
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

This is the correct code:

function nextInLine(arr, item) {
  // Your code here
  arr.push(item);
  return arr.shift();  // Change this line
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 7)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

I was getting stuck because I called arr.shift(); twice. Once, and then again after "return".
console.log(nextInLine(testArr, 7)); means: print onto the screen the results of calling nextInLine on testArr (defined as [1,2,3,4,5]). The function's job was pushing 7 to the end, and then shifting the first number off.



  • I also liked this one:


function testLogicalOr(val) {
  // Only change code below this line

  if (val) {
    return "Outside";
  }

  if (val) {
    return "Outside";
  }

  // Only change code above this line
  return "Inside";
}

// Change this value to test
testLogicalOr(15);

Answer:
function testLogicalOr(val) {
  // Only change code below this line

  if (val>20 || val<10) {
    return "Outside";
 
  }

  // Only change code above this line
  return "Inside";
}

// Change this value to test
testLogicalOr(11);

Aha moment: I am not saying val should be between 10 and 20. In fact, if the value is "outside" of this range, aka more than 20 OR less than 10, then it is returned as outside! Therefore, when running testLogicalOr(11); we know that 11 is INSIDE of the range, and therefore "Inside" is returned. 

No comments:

Post a Comment