Javascript


John Alexis Guerra Gómez


Slides:http://johnguerra.co/lectures/webDevelopment_fall2023/05_Javascript/

Class page:http://johnguerra.co/classes/webDevelopment_fall_2023/

Wat?

https://www.destroyallsoftware.com/talks/wat

What did we learn last time?

Readings discussion

  • questions?

How to ask a question to the staff

  1. Try yourself
  2. Google it
  3. StackOverflow it
  4. Create a reproducible bug (e.g. jsfiddle)
  5. Ask on slack (#general)

Random Questions

  • What is let and why we need it?
  • What is a linter
  • It's Javascript Object Oriented?

Functions

  • How do you create a function?
  • How do you also create a function?
  • And how do you also also create a function?
function add5(a) {
  return a + 5
}
const add5_anon = function(a) {
  return a + 5
}

const add5_arrow = (a) => {
  return a + 5
}


Variable scope

Scope common error

function showHelp(help) {
  document.getElementById("help").textContent = help;
}

function setupHelp() {
  var helpText = [
    { id: "email", help: "Your email address" },
    { id: "name", help: "Your full name" },
    { id: "age", help: "Your age (you must be over 16)" },
  ];

  for (var i = 0; i < helpText.length; i++) {
    // Culprit is the use of `var` on this line
    var item = helpText[i];
    document.getElementById(item.id).onfocus = function () {
      showHelp(item.help);
    };
  }
}

setupHelp();

Variable hoisting

  • A variable can be referenced before it was defined

Variable hoisting

console.log(x === undefined); // true
var x = 3;

(function () {
  console.log(x); // undefined
  var x = "local value";
})();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_Types#Variable_hoisting

undefined vs null

  • undefined a variable hasn't been created or assigned
  • null a variable was created and assigned to null

About closures

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Classes vs Prototypes

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model

Objects

  • It's an object the same thing than a java HashTable?
  • How do you create a new object?
  • Can you add new attributes after object creation?
  • Use Map when you need a Hash

Arrays

  • Create a function that sorts an array
  • Create a function that filters an array of objects
  • Create a function sums all the items on an array

More arrays

  • filter
  • map
  • forEach

Modify the DOM






Exercise

Build a listings page from the SF Airbnb listings for Sept 2023 JSON file.

  • Share your results

Required Readings Next session