DEV Community

James Shipman
James Shipman

Posted on

JavaScript ... love it or hate it, here's how to use it

JavaScript

Ahhh JavaScript, the little DOM language that grew into a monster/beast/foundational web technical ... take your pick of terms.

It's light-weight, it can be fast and nowadays it can do almost anything on any operating system and/or browser.

"Quick" Reference Guide

Yeah, this is not going to be a short a list of functions or syntax. Below are my notes for mod 3 of my coding bootcamp that I refer back to often because I'm not going to memorize all of this anytime soon -- I will at some point because that's how I do.


DOM & Just Enough JavaScript

Document-Object Model

  • ask DOM to find or select HTML elements or elements in the rendered page
  • remove and/or insert element(s)
  • adjust a property of selected element(s)

JavaScript / DOM relationship

  • DOM only knows js, js and DOM are linked at hip from start
  • learning about DOM will require js
  • "sight words" to do this

"Sight Words"

  • basic vocab that forms foundation for more learning latter
  • js Sight Words = brief code snippets that are foundational

Just Enough JavaScript

  • learning sight words first is an interactive way of learning js
  • MDN's JavaScript Reference
  • code, code, code, code, code

Coding in Chrome DevTools

  • writing 1 + 1 is an expression
    • a valid unit of code that returns a value
  • math expressions are "raw" in console
  • literal text is wrapped in quotes

"Things" in JavaScript

  • number (integer or float) are things
  • string is a thing
  • reserved words var, let, const
    • var came first, now we have let and const
  • Template Literals
    • with template literals use back ticks, not single quotes

JavaScript is Object-Oriented

  • code i can talk to that know state and behavior
  • all Things in js
    • objects
    • arrays
    • strings
    • numbers
  • dot notation()

JavaScript has loops

  • for each character in slytherin collection, I would like the harry_potter object to invoke expelliarmus method on each wizard passed in as an argument
for (let i = 0; i <slytherins.length; i += 1)
  {
    harry_potter.expelliarmus(slytherins[i]);
  }
Enter fullscreen mode Exit fullscreen mode

Variables

Multi-line Variable Assignment

var a = 5;
var b = 2;
var c = 3;
var d = {};
var e = [];
Enter fullscreen mode Exit fullscreen mode

Equivalent To:

var a = b;
    b = 2;
    c = 3;
    d = {};
    e = [];
Enter fullscreen mode Exit fullscreen mode

Can be Converted To:

var a = 5, b = 2, c = 3, d = {}, e = [];
Enter fullscreen mode Exit fullscreen mode

Use typeof operator to check data type of value currently stored in a variable.

Using const and let instead of var

  • scope issues with 'var'
  • let will throw an error if declare same var more than once
  • const cannot be reassigned
    • assign a primitive value (any data type except object)
    • a const will always point to same object
    • const is self commenting
  • NEVER USE VAR
  • USE LET WHEN I KNOW A VALUE NEEDS TO CHANGE (COUNTERS, LOOPS, ETC...)
  • USER CONST FOR EVERY OTHER VARIABLE

The DOM Tree

document.querySelector(selector)

  • selector is like a query string lets me find things within HTML page

The DOM Tree:
(e) = element
(t) = text
(a) = attribute
Document

|-- <html> (e)
|---- <head> (e)
    |-- <title> (e)
      |-- <My title> (t)
  |-- <body>
      |-- <h1> (e)
          |-- <A heading> (t)
      |-- <a> (e) - <href> (a)
          |-- <Link text> (t)
Enter fullscreen mode Exit fullscreen mode

Finding a Node

document.getElementById()
document.getElementsByClassName()
document.getElementsByTagName()
Enter fullscreen mode Exit fullscreen mode

DOM Tree:

<main>
  <div>
    <div>
      <p>Hello!</p>
    </div>
  </div>
  <div>
    <div>
      <p>Hello!</p>
    </div>
  </div>
  <div>
    <div>
      <p>Hello!</p>
    </div>
  </div>
</main>
Enter fullscreen mode Exit fullscreen mode

Find the <main> element:

const main = document.getElementsByTagName('main')[0]

Get the children of <main>

const div = main.children[1]

Get and update the <p>

const p = div.getElementsByTagName('p')[0]

Change <p>

p.textContent = "Goodbye!"


JS Fundamentals: Arrays

document.getElementsByClassName() => [...many elements...]

  • HTMLCollection, not actually an Array
  • HTMLCollection know its length, can be iterated over with for...in... loop
  • HTMLCollection not technically an Array

document.getElementsByTagName() =>[...multiple elements...]

document.getElementById() => single element


Looping and Iteration

for ([initialization]; [condition]; [iteration]) {
    [loop body]
}
Enter fullscreen mode Exit fullscreen mode
  • use a for loop when I know exactly how many times I want/need the loop to run

querySelector Methods

Learning Goals

  1. Use document.querySelector() & document.querySelectorAll() to find nested nodes
  2. Change value of targeted DOM nodes

Introduction

  • essential skill, find elements in DOM
  • document.getElementById() & document.getElementsByClassName() are good, using tree structure & tags is better

Use document.querySelector() & document.querySelectorAll() to find Nested Nodes

document.querySelector()

  • 1 arg, CSS-compatible selectors
  • returns first instance of arg

example:

<body>
    <div>
      <ul class="ranked-list">
        <li>1</li>
        <li>
          <div>
            <ul>
              <li>2</li>
            </ul>
          </div>
        </li>
        <li>3</li>
      </ul>
    </div>
             
    <div>
      <ul class="unranked-list">
        <li>6</li>
        <li>2</li>
        <li>
          <div>4</div> **
        </li>
      </ul>
    </div>
</body>
Enter fullscreen mode Exit fullscreen mode

const li2 = document.querySelector('ul.ranked-list li ul li')

const div4 = document.querySelector('ul.unranked-list li div')


document.querySelectorAll()

  • 1 arg
  • returns a NodeList collection
    • an Array, but not technically an Array

example:

<main id="app">
    <ul class="ranked-list">
      <li>1</li>
      <li>2</li>
    </ul>
             
    <ul class="ranked-list">
      <li>10</li>
      <li>11</li>
    </ul>
</main>
Enter fullscreen mode Exit fullscreen mode

document.getElementById('app').querySelectorAll('ul.ranked-list li')

// => list of Nodes: <li>1</li>, <li>2</li>, <li>10</li>, <li>11</li>


Removing, Altering & Inserting HTML

document.querySelect('element-name').remove()

  • this is to remove an element

document.classOrIdThing.remove('thing-name-here')

  • removes a class or id from an element, leaves the element in place

Explicit and Safe .remove() pattern

 let x = document.querySelector('element#id');
 let y = x.parentNode;
 y.removeChild(x);
Enter fullscreen mode Exit fullscreen mode

Explicit and Safe adding

We’ve been inundated by cat owners who are angry that we have missed their favorite species of pet. What JavaScript snippet will add an li with a span inside with the text "Nancy Drew (the cat)" inside to our ul?

 base = document.getElementsByTagName("li")[0].parentNode;
 item = document.createElement("li"); 
 s = document.createElement("span"); 
 s.id = "cat"; 
 s.textContent = "Nancy Drew (the cat)"; 
 item.appendChild(s); 
 base.appendChild(item)
Enter fullscreen mode Exit fullscreen mode

JavaScript Everything

Different Types of User Events

  • mouse click
    • click, double-click, right-click, etc ...
  • key press
    • keypress, keydown, keyup
  • form submission
    • submit ton of browser events

Functions in js

  • most important thing in js
  • a series of multiple tasks can be pulled into a function if the series can be generalized
    • makes the tasks repeatable

Scope

  • global scope
    • accessible everywhere in js code
  • block scope
    • let & const
    • only within their function
  • variables declared w/out const, let, or (NO!!!!!) var are always globally-scoped
    • even within a block

Chain Scope

  • Chain Scope is using global vars in a local context
  • matters where it is declared, not invoked
  • local vars can reference outer scoped vars all the way up the levels

Lexical Scoping

  • scope based on where vars & blocks defined by developer at writing, solidified when code is processed

Hoisting

  • by time js engine reaches execution phase all functions are in memory so order is not important in the code itself
  • best way to avoid confusion, declare all functions at the top of my code
    • refactor as needed/on-going or otherwise
  • use let & const as js engine !allow referenced before initialized

Object Iteration

for ... of

  • use with arrays, actual ordered data
const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
         
 for (const el of myArray) {
    console.log(el);
 }
Enter fullscreen mode Exit fullscreen mode

for ... in

  • use with objects where order is not required just the key/value pair
 const address = {
    street1: '11 Broadway',
    street2: '2ns Floor',
    city: 'New York',
    state: 'NY',
    zipCode: 10004
 };
 for (const key in address) {
    console.log(address[key]);
    console.log(key);
 };
 // console.log(address[key]) will return the value of the key
 // console.log(key) will return the key
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
jessicatriana profile image
Jessica Triana

Super informative!

Collapse
 
jbshipman profile image
James Shipman

Thank you :)

Collapse
 
aaidenplays profile image
Aaidenplays

Wow what a great guide. Thank you!

Collapse
 
jbshipman profile image
James Shipman

Glad you like it :)