📝 Josh's Notes

JavaScript Notes

Ways to define a variable

1// Using var
2var var1 = true;
3
4// Using const
5const var1 = true;
6
7// Using let
8let var1 = true;

The ‘Not’ Operator

1var sense = true;
2
3var nonsense = !sense;
4
5var notNonsense = !nonsense;
6console.log('Not Nonsense:', notNonsense);

Output:

"Not Nonsense:" true

Numbers

One number type in JS - Number (can be pos, neg, floating point etc) three symbolic values - +Infinity, -Infinity, and NaN (Not a Number)

DOM (Document Object Model)

A DOM is a representation of the HTML file. It’s an object that can be manipulated using JavaScript code.

Events

An event listener runs when a particular event (like a click of a button) happens.

There is a parameter that you can pass into your event handler functions: the event object. The event object gives you lots of information about the event. For example, you can use it to log some text to the console whenever a user clicks on an HTML element.

this refers to the DOM element that the listener was attached to. Put another way, whenever you write foo.addEventListener('click', someFunction) the context of this inside of someFunction will refer to foo. On the other hand, event.target will refer to the element that caused the event to fire.

1// Will log only will only log what caused the event to fire (what was clicked on)
2var div = document.querySelector("div");
3
4var logText = function(event) {
5  console.log(event.target.textContent);
6}
7
8div.addEventListener("click", logText);
1// Will log everything inside the DOM
2var div = document.querySelector("div");
3
4var logText = function() {
5  console.log(this.textContent);
6}
7
8div.addEventListener("click", logText);

When the element that fires the event is the same as the element that has the listener on it, you should see that this and event.target are the same. But there are times when you’ll want to add the event listener to an element that won’t necessarily be the same as the element (or elements) that will be firing the event.

When manipulating the DOM, it’s important that your JavaScript code not load until the DOM is ready. There are a couple of ways to do this. The most common way is to use the DOMContentLoaded event:

1var imgLog = function() {
2  console.log("You moused over Mega Man!");
3}
4
5document.addEventListener("DOMContentLoaded", function() {
6  var img = document.querySelector('img');
7  img.addEventListener('mouseover', imgLog);
8});

This event fires when the document has been loaded and parsed. This happens before all assets (e.g. images, videos, stylesheets, etc.) have completely loaded. In other words, DOMContentLoaded gets fired before the window finishes loading.

When an event happens. It captures down the DOM tree from <html> to the element where the event happened. Then, it bubbles back up the DOM tree until it gets back to <html>. Along each element it passes, it fires the event.

#programming #webdevelopment #javascript