JavaScript From First Steps To Professional Notes

Table of Contents

This was/is a course on the Front End Masters website. These notes are were taken and compiled by Aleks Ozolins.

Introduction

Course materials: https://anjana.dev/javascript-first-steps/

  • node.js = Lets you run JS on servers (server-side)
  • HTML & CSS & JS are BFFs! HTML for content and structure. How we declare the stuff in the webpage. HTML is the noun, CSS is the adjective, and JS is the verb.

Where can you write JS

  • The browser's JS console
  • Local text file in editor
  • Online playground like Codepen, or CodeSandbox

The Document Object Model

<!DOCTYPE html>
<html lang="en-US">
  <head>...</head>
  <body>
    <header>...</header>
    <div id="board">...</div>
  </body>
</html>

So the head and the body are children of the html. The header is a child of body. The div as well is a child of the body.

JS creates an object/entity that represents the structure of the document.

If you just type document on the js console, you will get the document spit back at you.

Finding Elements in a Web Page

Note: You can type clear() to clear the console.

You can type all these things at the console and the console will output whatever that element/object is.

Working with this page: https://anjana.dev/javascript-first-steps/1-tictactoe.html

  • document: build in object in JS that represents the whole HTML document you're working with
  • document.title: Represents the title of the document.
  • document.body: All of the content
  • document.head: Contains other stuff
  • document.body.children: Gives you the header and divs… In different documents might look different.
  • You can use .children to drill down on any element.
  • document.getElementById("board"): Gets is the div that is the "board". Picks out that element. If you have two elements with the same Id, you'll get the first one. Ideally they should be unique.
  • document.querySelector("#board"): Same thing as above but using a CSS query selector
  • document.getElementsByTagName("h1"): Returns all elements with the "h1" tag. Very cool.
  • document.querySelectorAll("h1"): Same thing using CSS selector.

In HTML we have the concept of "class": An HTML class is an attribute that can be added to an HTML element to give a specific class name.

  • document.getElementsByClassName("player"): Returns all HTML elements with the class name "player".
  • document.querySelectorAll(".player"): Same thing with CSS query selector. Using a dot . returns classes.

.length & .textContent

Still working with: https://anjana.dev/javascript-first-steps/1-tictactoe.html

  • document.getElementsByClassName("player").length
  • document.querySelectorAll(".player").length

Both of the previous statements, when typed into the console, will return the number of "things". There are 2 players. How many "things" are in a collection of "things".

  • document.getElementById("p1-name").textContent // We get Anjana returned because that's the text inside of the element

textContent = What is the text inside this element?

The Three Most Important Letters in Web Development

MDN: Mozilla Developer Network: https://developer.mozilla.org/en-US/

You can look up anything here. Basically, this is the docs for JS. Everything for web developers. The search box here is your friend.

  • JS
  • HTML
  • CSS

Exercise: Get this things

  1. all the p elements: document.getElementsByTagName("p")
  2. the text "X": document.getElementById("p1-symbol").textContent OR document.querySelector("#p1-symbol").textContent Note that the # hash symbol when using querySelector picks out stuff by Id.
  3. the number of squares in the board: document.querySelectorAll(".square").length I think the dot . when using querySelectorAll() selects for class.
  4. the text "A game you know": document.querySelector("h2").textContent The querySelector() method returns the first element of that type whereas the querySelectorAll method returns a node list of all those elements so digging down with textContent gets "undefined"

Editing the Dom with JS

Still working with: https://anjana.dev/javascript-first-steps/1-tictactoe.html

document.title = "My Page": Changes the page title.

document.getElementById("p1-name").textContent = "Aleks": Change the name of player 1.

document.getElementById("p1-name").append(" & friends")

Exercise

  1. [X]

    Change the player names to you & neighbor document.getElementById("p1-name").textContent = "George" or document.querySelector("#p1-name").textContent = "George"

    Note you need the # to select the Id when using querySelector.

  2. [X] Swap the player symbols document.getElementById("p1-symbol").textContent = "O" document.getElementById("p1-symbol").textContent = "X"
  3. [X]

    Change subtitle to "A game you know and love" document.querySelector("h2").append(" and love")

    Note: This doesn't work in Firefox for some reason. (append is not a function)

Values & Data Types

Values & Data Types

What are these things we're working with?

Values - chunks of information we want to work with. That information can be of different types:

Note - strings and numbers are primitive data types, and objects are different. document is an object for example.

Primitive data types

  • string
  • number
  • boolean
  • undefined
  • null
  • a few others

strings (Text data)

  • "Tic Tac Toe" or "#board"
  • Can be in double quotes, single quotes, and backticks as well.
  • typeof tells you the type of value you're dealing with.

numbers

  • Infinity
  • 9
  • 2394832
  • 1.21e9
  • -3.45

booleans

  • true
  • false

undefined and null

A blank void of nothingness.

  • undefined: accidental nothing
  • null: deliberate nothing

Exercise

Which data type is each of these values? We can use typeof to find out!

  • false: boolean
  • "true": string
  • document.title: string
  • "some string".length: number
  • null: object Why does null return object when it is listed as a primitive value? We don't know… it's stupid and nonsensical.

NOTE: typeof is not a function in JS, it is an operator. So, the correct was to use it is:

typeof 43

and not:

typeof(43)

…although the second way will work.

Working with Strings

What are strings made up of? That's right, characters!

Characters are in a specific order. Each gets a number, starting at 0:

  • aloha
  • 01234
  • a l o h a
  • |0|1|2|3|4|5|

We can think of it this second way too. Where length will return 5 but the first letter starts at position 0.

Index

The number given to each thing inside a more complicated thing is an index.

So, the position of a character in a string or of a value in an array.

console.log("Aloha"[0]);

A

How do I ask JS, what is the index of a specific character?

console.log("ALOHA".indexOf("L"));

1

Note: It will return the first appearance of the thing.

If we ask it to find a thing that is not inside the string, it will return -1.

includes will let us know if a thing contains another thing.

console.log("ALOHA".includes("HA"));

true

startsWith will let us know if a thing starts with another thing. Returns a boolean.

At what index does this substring begin?

console.log("ALOHA".indexOf("HA"));

3

Connecting Strings Together

console.log("ALOHA" + "!")
ALOHA!

Making lowercase

console.log("ALOHA".toLowerCase());

aloha

Exercise

Still working from: https://anjana.dev/javascript-first-steps/1-tictactoe.html

Use our new string superpowers to:

  • Add your last name in the players listing: document.querySelector("#p1-name").append(" Harrison") or document.getElementById("p1-name").textContent = "Aleks" + " " + "Ozolins"
  • Retrieve the first "T" in the page title: document.title[9]
  • Answer whether the page title contains the string "JavaScript": document.title.includes("JavaScript") Results: false
  • Capitalize the heading "Tic Tac Toe": document.querySelector("h1").style.textTransform = "uppercase" (advanced) we're using css style attribute. or document.querySelector("h1").textContent = document.querySelector("h1").textContent.toUpperCase()

Operators

Operators

  • "ALOHA" + "!" Here the operator is the +
  • typeof "value" Here the operator is typeof

+ is an operator with several different uses:

  • Concatenates strings
  • Adds numbers

The plus operator needs 2 values to do its job when it's doing the two things above.

Arithmetic operators

  • + add
  • - subtract
  • * multiply
  • / divide

Order of operations

Same as in math, use () to group. I think it's PEMDAS?

So:

((4 + 1) * 2 * 4) + 2 = 42

Operators Exercise

Use arithmetic operators to compute:

  • The total number of siblings of of your parents 1 + 2 = 3
  • The average number of hours you slept this week (6 + 7 + 8 + 5.5 + 6 + 7 + 6) / 7 = 6.5
  • The number of dogs you'd pet in a week if you pet 1 dog per hour while awake (24 - 6.5) * 7 = 122.5

Comparison Operators

  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to

These will return booleans.

  • /=== equal to (and same type)
  • – equal to
  • !== does not equal (and not same type)
  • != does not equal (and not the same type)

In almost every situation, you'll want to use the strict versions of these operators since the data-type matters.

Expressions

What is an expression?

  • 4 / 2 * 10
  • "Frontend" + "Masters"
  • 5 > 4 !== 3 > 4

These are expressions. An expression evaluates (resolves) to a value.

An expression expresses a certain value.

  • "FrontendMasters".includes("Front" + "end")

Expressions function as values.

Variables

let remember = "Sept. 21";

let here is a keyword that lets us declare a variable.

= is the assignment operator.

The ; is saying, "I'm done talking".

Declaring a variable

let bankruptcy;

That declares the varilable but does not assign a value to it.

The value will be undefined.

Assigning a variable

let myVariable;
myVariable = "so value, much wow";

You can also do it all at once:

let myVariable = "woo";

const & Accessing Variables

const declares & assigns a "constant" - aka a variable that can't be changed.

const myUnchangeableVariable = "Never gonna give you up";

You have to assign the value when using const. Can't just declare like with let.

Using a Variable

  • answerToLife - 10
  • myVariable.toUpperCase()

Valid variable names

  • validVariable (camelCase is the most common)
  • alsovalidbutlesscommon (this is more common in Python)
  • OddbutTechnicallyfine2
  • 0chanceThisWillWork! (this won't work)

Exercise

Declare & assign carilables to remember:

  • Your name: let myName = "Aleks Ozolins";
  • The combined age of your parents: let combinedParentsAge = 75 + 74;
  • The #board element on the page: const board = getElementById("board")

The var Keyword

This is a third keyword that you can use to assign variables.

var is older than let.

For now, we will just use let. Generally we're going to want to use let.

What Are Variables

Variables contain values.

Evaluating Code

When we run this code, what happens?

let answerToLife = 4 + 4;

  • A variable is declared
  • The expression on the right side is evaluated
  • It assigns the value to the variable
let scrub = "guy that thinks he's fly";
let busta = scrub;
scrub = "guy that can't get no love from me";
console.log(busta);

guy that thinks he's fly

Note: The value of busta didn't change when the value of scrub changed. Because when busta was assgined, the value of scrub was evaluated at that time to make the assignation.

Statements vs. Expressions

An expression "asks" JS for a value:

  • myAssignedVariable
  • 6 + 4
  • document.getElementById("board")

An expression though, "tells" JS to do something (e.g. declare/assign a variable):

  • let ten = 6 + 4;
  • myDeclaredVariable = "horse";
  • let board = document.getElementById("board");

Statements tend to have a semicolon at the end of them

Arrays

Arrays let us keep multiple values together in a single collection

let synonyms = ["plethora", "array", "cornucopia"];

We can access that array in different ways:

synonyms.length

let synonyms = ["plethora", "array", "cornucopia"];
console.log(synonyms[1]);

array

So in the example above, the length will be 3, but the last number in the array will be at index 2

We can also check if an array contains a certain value:

synonyms.includes("plethora")

We can modify arrays:

synonyms[1] = "variety"; // replaces the first value with "variety"
let lastItem = synonyms.pop(); // Assigns the last value of synonyms to the variable lastItem and removes it from the array
synonyms.push("multitude"); // adds multitude to the array at the last position. (append)

You can create an empty array with let emptyArray = [];

Arrays can also hold different data types next to each other: let mixedArray = [1, "horse", document];

In the example above, we have a number, a string, and an object.

Useful Array Methods

["c", "a", "d"].sort() // sorts alphabetically even when dealing with non-string values
["lions", "tigers", "bears"].join(" & ") // joins as a string with a separator
[1, 2, 3].concat([4, 5, 6]) // concatenates the array

Note that push only pushes a single item, so if you push an array into an array, you end up with a nested array.

Mutability (Mutating data)

Mutable data can be edited. Arrays are mutable.

Immutable data always stays the same. Strings and other primitives are immutable.

So, we can use pop, push, etc with mutable data, but not with immutable data.

Mutable and Immutable data Excercises

Do these do the same things?

let numbers1 = [1, 2, 3];
let result1 = numbers1.push(4);
console.log(numbers1);

[ 1, 2, 3, 4 ]

And the second thing…

let numbers2 = [1, 2, 3];
let results2 = numbers2.concat ([4]);
console.log(numbers2);

[ 1, 2, 3 ]

So, concat did not change the original array that I called it on, but push did.

So concat created a new array.

push mutates the array – changes it in place.

let letVariable = "original value";
letVariable = "new value";
console.log(letVariable);

new value
const constVariable = "original value";
const constVariable = "new value";
console.log(constVariable);

ERROR

let creates a mutable variable. const creates an immutable variable

Immutable Variables & Values

What happens when we use const with a nutable value like an array?

const operands = [4, 6];
const sum = operands[0] + operands[1];

operands[0] = 5;
const newSum = operands[0] + operands[1];
console.log(newSum);

11

So, while the array that is created with const is immutable, its contents are mutable.

Note: IF you have the choice, using immutable data & variables is usually best. Why is that?

If an underlying value changes, and you didn't expect it to change, ya gonna have a bad time.

Variables & Arrays

let array1 = [1, 2, 3];
let array2 = array1;
console.log(array2);

array1[1] = 4
console.log(array2);

[ 1, 2, 3 ]
[ 1, 4, 3 ]

What is going on here?

  • We have 2 variables pointing to the same array value
  • Same thing would be true even if we used const

Q: Should we always use const for arrays? A: Not necessarily, but unless you have a good reason to expect that you need to change the assignment, use const.

Objects

Objects & Property Access

We saw an object earlier:

const js = {
    name: "JavaScript",
    abbreviation: "JS",
    isAwesome: true,
    officialSpec: "ECMAScript",
    birthYear: 1995,
    creator: "Brendan Eich"
};

console.log(js.name);

JavaScript
undefined

Objects collect multiple values together to describe more complex data.

Similar to how we can point at different values use variables in our code, objects let us point at related values using properties in the object.

We can use a dot to pick a value/property out of an object as above.

The whitespace doesn't matter.

Using property values

const js = {
     name: "JavaScript",
     abbreviation: "JS",
     isAwesome: true,
     officialSpec: "ECMAScript",
     birthYear: 1995,
     creator: "Brendan Eich"
 };

console.log(js.name.startsWith("Java"));
let age = 2022 - js.birthYear;
console.log(age);

true
27

We can even assign properties on an object.

const indecisive = {
    lunch: "sandwich"
};

indecisive.lunch = "tacos"
indecisive.snack = "cheese"

console.log(indecisive);

{ lunch: 'tacos', snack: 'cheese' }

Visualizing Object Access

Arrays are actually also objects.

Exercise

Create an object representing you!

Add properties for facts important to you.

const aleks = {
    name: "Aleks Ozolins",
    age: 41,
    height: "5'7",
    religion: "atheist",
    orientation: "hetero",
    hobbies: ["horn", "running", "boooks"],
    affair: null
};

console.log(aleks.hobbies);

[ 'horn', 'running', 'boooks' ]
  • Object.freeze() method allows you to freeze an object so you can't alter an object.

Object Methods

Properties can point to functions too:

const dog = {
    name: "Ein",
    breed: "Corgi",
    speak: function () {
        console.log("wooooo");
    }
}

dog.speak();

wooooo

A method is a property that evaluates to a function.

So for "string".indexOf("r"), indexOf() is a method.

The this keyword in JS refers back to whatever object you're working with.

Be careful with this. Its behavior is complicated & can be tricky.

Nested Objects

const menu = {
    lunch: {
        app: "salad",
        main: "pasta",
        dessert: "tiramisu"
    },
    dinner: {
        app: "samosa",
        main: "saag paneer",
        dessert: "gulab jamun"
    }
};

console.log(menu.dinner.dessert);

gulab jamun
undefined

So you can have objects inside of arrays, arrays inside of objects, etc. etc.

Objects Methods Exersise

const spices = [
    {name: "Emma", nickname: "Baby"},
    {name: "Geri", nickname: "Ginger"},
    {name: "Mel B", nickname: "Scary"},
    {name: "Mel C", nickname: "Sporty"},
    {name: "Victoria", nickname: "Posh"}
];
const spiceGirls = {
    albums: ["Spice", "Spiceworld", "Forever"],
    motto: "Girl Power",
    members: spices
};

console.log(spices[4].name);

Victoria

From the spiceGirls object, how can we retrieve:

  • "Girl Power" console.log(spiceGirls.motto);
  • The object representing Ginger Spice console.log(spices[1]);
  • "Spiceworld" console.log(spiceGirls.albums[1]);
  • "Victoria" console.log(spices[4].name);

Built-in Objects

  • document is an object that has a lot of properties.
  • console console is a built in object that has a method, log and a lot of other properties. there is console.warn() and console.error()
  • Math We have Math.PI and Math.random etc.

strings?

Strings are wrapped in an "objecty" thing. So string is a built-in object that is like a wrapped. So you can use "hello".toUpperCase

Note: You're not manipulating strings… You are just calling properties on the wrapped string object.

Tic Tac Toe Demo

Date: 2023-06-29 Thu 09:33

Emacs 29.4 (Org mode 9.6.15)