JavaScripT:

From Zero To Dangerous

🚧  🏗  🧨  💥  🚧

@zachfedor

Further Reading:

Look for the                                 links

🏁 GoalS:

 

  • To get absolute beginners up and running with modern JavaScript development by breaking down common barriers and giving a roadmap for further exploration.
  • To give more experienced developers some analogies for deeper understanding of the language and new features for more investigation.

What is

"Modern"

JavaScript?

☝️ First, What's Javascript?

One of the Big 3 in Web Development:

  1. ​HTML  =  Content
  2. CSS  =  Layout & Style
  3. JavaScript  =  Interactivity

🤔 But wait, can't CSS make things interactive?

🧙 Make Something from Nothing

CSS requires everything to be there on page load. JS has more freedom and more power:

  • Create, destroy, and modify HTML elements or CSS rules
  • Send or receive information without reloading the page
  • Store and manipulate all kinds of information
  • Interact with APIs

📻 Application Programming Interface

Think of a radio

 

        🔈  🔊

 

You don't know how it works,

but you know how to make it work.

🎛️ Some Handy ApIs

Browser/HTML APIs:

  • DOM *
  • Local Storage
  • Notifications
  • Canvas
  • Audio / Video

Third Party APIs:

  • Maps
  • Social Media
  • Many other websites

 Back to Javascript...

  • Built in 1995 for Netscape to - you guessed it - make it more interactive.
  • Brendan Eich made it in 10 days (which is why some people dislike it).
  • Has nothing to do with Java, the name was a marketing decision (another reason for dislike).
  • Influenced by C and Scheme, which are nothing alike and why JS is so different from other languages (more dislike).

But it's on every browser which is why everyone uses it!

ES5,

ES6,

ES.Next?

📜 ECMAScript is the Spec

  • Just like HTML and CSS, an organization comes up with the specification, or rules, for how browsers should handle the code.
  • ECMAScript is the rules, JavaScript is the follower of the rules.
  • Not all browsers interpret the rules the same way, just like HTML and CSS.
  • There have been many versions of ECMAScript
    • ES5 in 2009
    • ES6 in 2015
    • One per year, latest being ES 2018
    • Proposals for features and changes are in the works

 Modern Browsers Support Modern Javascript

My Opinion:

Learn new JavaScript because they're making it better for a reason. ES5 & ES6 are compatible, so write what you know and sprinkle in new stuff as you learn it or need it.

 

My Warning:

If you know you need to support old browsers, then learn ES6 and how to transpile it into an older version. (Next talk, maybe?)

Use New FeatureS

If it breaks, learn the old version.

 

... or look it up before you write it.

What about

JSON/jQuery/

React/Vue?

🍦 Vanilla Javascript

  • Vanilla JS is JS without a framework or library.
  • Frameworks and Libraries can be made with JS and you use them in your project
  • Libraries (like jQuery) are enhancements, APIs that you can use to make things happen quicker or more simply than writing it yourself.
  • Frameworks (like React and Vue) are more wholistic. You follow their convention and use their API to piece together your program.

Using a Library or Framework doesn't mean you can avoid using JavaScript.

Alright,

Where Do

We Start?

🚦 At the Beginning End

<!DOCTYPE html>
<html>
  <head>
    <title>My First JavaScript</title>

    <link href="styles.css" rel="stylesheet">
  </head>
  <body>
    <h1>My HTML Goes Here</h1>

    <script src="main.js"></script>
  </body>
</html>

Because now you have to deal with time.

🔀 The Question of "When?"

  • HTML and CSS happen when they happen and you don't have to think much about it. They are declarative.
  • JS happens line by line for the most part. But it can skip lines, jump back, re-run, or stop altogether. It is procedural.

This can be the most frustrating thing about learning a programming language.

<!DOCTYPE html>
<html>
  <head>
    <title>My First JavaScript</title>

    <link href="styles.css" rel="stylesheet">

    <script src="main.js"></script>
  </head>
  <body>
    <h1>My HTML Goes Here</h1>

    <button>Make Something Happen</button>
  </body>
</html>

When the browser reads the JavaScript on line 8 which is all about the button, the browser hasn't made the button yet. That's line 13.

A button that should do something:

<!DOCTYPE html>
<html>
  <head>
    <title>My First JavaScript</title>

    <link href="styles.css" rel="stylesheet">
  </head>
  <body>
    <h1>My HTML Goes Here</h1>

    <button>Make Something Happen</button>

    <script src="main.js"></script>
  </body>
</html>

Now the browser makes the button on line 11 which is just in time for the JavaScript to go looking for it on line 13.

A button that actually does something:

Some people might tell you that's the wrong way to do it:

DON'T WORRY.

JUST GET STARTED!

📁 File vs Repl

  • JavaScript files are good for long pieces of code, known as scripts.
  • You can write the script and the browser will interpret and run it when you load it.
  • Read-Eval-Print-Loops, or REPLs, are good for quick tests of code.
  • Open the browser's console from the Developer Tools and you can run JS line by line.

🔎 Read More - Firefox

🔎 Read More - Chrome

Data,
Types,
Expressions

🌎 Data is how We Describe The World To Computers

  • Computers can only understand things in terms of electricity or no electricity.
  • You can understand things on so many more levels.
  • Building a website starts with the content.
  • Writing a program starts with the data.

This can be the other most frustrating thing about learning a programming language.

What does Your Program Need to Know About?

  • It starts with what you're building.
  • Try to describe it with as little data as possible.
  • Try to think about how that data will change over time. We call this state.
  • What do we need to do to that data?

This is all too vague. Let's try and describe the state of a game of Tic-Tac-Toe.

   vs   

🖨️ Data Types

  • Data is the information
  • Its type determines what we can do with it
  • Think of data types as different building materials:

🌳  +  🔨  =  ✔️

🎨  +  🔨  =  ✖️

🎨  +  🖌️  =  ✔️

You're already used to this with CSS:

color: red;    ✔️

width: red;    ✖️

width: 10px;    ✔️

🖨️ Basic Data Types

  • String
  • Number
  • Boolean
  • Null or Undefined

CSS

10px is a length

red is a color

  • Symbol
  • BigInt

JS

10 is a  Number

"red" is a String 

🧮 Values Combine into An Expression With Operators

// Numbers
2 + 2
13 - 5
24 * 7
1 / 4

// Strings
'Hello World'
"con" + "cat" + "e" + "nate"
`half of 100 is ${100 / 2}`

// Booleans
true
3 > 2
true == 3 > 2

What's the // For?

// This is a single line comment

// JS doesn't read it, but you can!

2 + 2  // They can even come after real lines

/*
Here is a
multi-line
comment
*/

Use comments to describe WHY you're doing something so you remember later.

📦 Store Values in Variables

const myName = "Zach Fedor"

let timesEaten = 2

const imHungry = timesEaten < 3

timesEaten += 1

Two things are happening on line 1:

  • The variable myName is declared

  • The value "Zach Fedor" is assigned to it

Variables declared with let can be assigned new values while those declared with const cannot. 

You can't re-declare the same variable name.

📦 More About Variables

  • Try to use const more than let. The more that variables change, the harder they are to use.
  • If you see var, that's old ES5 code. Replace it with const (or let if it needs to change).
  • Remember the difference between a single = which assigns a value, and double == or triple === which check equality.
  • Variables can exist in some places but not others, this is called scope. Read up on it.

🧵 Strings vs Variables

let 1 = 10

let let = 100

This will break, too

'I'm supposed to be a string'

All of this is broken code.

  • Stick to simple words or phrases for variable names
  • Don't use words JS already cares about
  • Wrap your strings in quotes or JS will think it's a variable it should know about
  • Don't end your strings too early by accident

🧬 Data Structures

const myObject = {
  key: 'value',
  name: 'Zach Fedor',
}

myObject.name    // 'Zach Fedor'

myObject.newKey = 13

2 + myObject.newKey

Objects are the grandaddy of data types

  • Composed of key-value pairs, also called properties and attributes
  • The key is a label, kinda like a variable within a variable
  • The value can be anything, even another object!

🧬 Data Structures

const myArray = [
  'apples',
  'bananas',
  'cherries',
]

myArray[0]    // 'apples'

myArray.push('dates')

// ['apples', 'bananas', 'cherries', 'dates']

Arrays are special objects where the keys are numbers

  • Good for keeping a list of values that don't need separate names, especially if order is important
  • Keys for arrays are called indexes
  • The first one starts at 0. It's strange, but you'll get used to it.

Functions,

Control Flow

 Functions are Re-Usable

  • Think of it like a script within a script
  • Some are built-in, but you can write your own
  • Some are properties of values of a certain type, also called methods
  • You'll be writing a ton of these!
alert("Hello!")

myArray.push('new item')
myArray.push('another new item')

"some string".indexOf('t')    // 6

console.log("Print to the browser console")

 Declaring Functions

  • This is ES6's arrow function
  • Like variables, you declare a name. The function is a value!
  • Functions can take inputs, called arguments or parameters
  • Functions can give outputs using the return keyword
const average = (x, y) => {
  return (x + y) / 2
}


average(5, 10)   // 7.5
average(1, 10)   // 5.5
average(1, 'hello')   // NaN

// This function takes no arguments and does nothing
const myFunction = () => {}

 Declaring Functions

  • These are two older styles of declaring functions
  • Pick one you like and stick with it to learn how it works
  • When you're following a tutorial, convert them to the one you like
  • If it doesn't work, then you can learn the difference
// Function Expression
const average = function(x, y) {
  return (x + y) / 2
}


// Function Declaration
function average(x, y) {
  return (x + y) / 2
}

🌵 Branching Code

  • JS gives you many ways to control the flow of code
  • The most common is the if...else statement
  • Any valid expression can be the condition, but it'll probably evaluate to true or false
if (condition) {
  doSomething()
} else if (condition2) {
  doOtherThing()
} else {
  doLastThing()
}

🔂 Looping Code

You also have a few ways to run the same code multiple times

  • Use the for loop to run a set number of times
  • Use the while loop to run an unknown number of times
  • Use the for .. of loop to iterate over an array
for (let i = 1; i <= 5; i++) {
  console.log(i)
}

const myArray = [1, 2, 3, 4, 5]
for (let i of myArray) {
  console.log(i)
})

Document

Object
Model

The Dom is The HTML in Code

const bodyElement = document.querySelector('body')

const newParagraph = document.createElement('p')

newParagraph.textContent = "I didn't exist before"

bodyElement.appendChild(newParagraph)

Using the browser's DOM API, you can control the rendered HTML and CSS. This example:

  • Finds the <body> element and stores it in a variable
  • Creates a new <p> element and stores it, too
  • Adds text to the new paragraph
  • Then adds it to the document at the end of the body

Naming
& Style
Conventions

👜 Don't Spend Too much Time on Style

  • There's endless debate about style
  • Try to match exactly what you're reading
  • Fix only what breaks
  • Eventually you'll have your own opinions

Disclaimer: This is only true for your own code!

If you work on a team, just follow their lead. Once you have opinions, feel free to voice them, but remember there might be reasons you don't know about.

What

Not
To Do?

#1

Don't not start.

... There is no #2

So,

What's

Next?

Curriculum

Reference

Books

Thanks For Listening!

 

  • Check out techlancaster.com for more events like this
  • Ask one of us about the Slack workspace to keep in touch
  • Go explore some of the links in the slides
  • Feel free to ask me for help
  • Come back next month

 

But most importantly, go build something!

Made with Slides.com