Teatime With JJ(& some Java script)

Javascript Workshop & Information

JJ Bastida

General Info

Before we start the lesson...

Be sure to download either Brackets, Atom, or Visual Studio Code.

Download a code editor and use it when coding.

Have a template HTML, CSS, and JS folder structure so you don’t have to start from scratch each time, I have included one here.

JS like CSS, can be written directly in HTML with <script> tag. Itt is good practice to have all scripts on separate files. <script src='[source].js'>

Follow naming conventions for files, variables, ids, & class names like lowercase or camelCase is suggested (camel Case Is Putting No Spaces But Capitalizing Each Word Like This)

It’s generally good code practice to keep variables in their right place, and near the top.

Try to keep code concise; don’t re-write the same line of code 100 times just make a variable.

Be sure to Beautify, Prettier, or Format your code so that it is easily readable.


This is an example of good clean js code
var pageIsSet = false;
var salad = {
      saladType:'caesar',
      ingredients: [
        'lettuce',
        'croutons',
        'parmesan'
      ],
      dressing: true,
      dressingType: 'caesar'
};

function eatSalad() {
    ...
}

                

What's a JS?

Like Java? Like that thing you update???

Javascript or JS is one of the basic programming language of HTML and the Web

It was written to be an easy entry-level scripting language. AND NOT RELATED TO THE JAVA PROGRAMMING LANGUAGE.

It lets you create more intricate interactions and make calculations to create dynamic web interactions.

Usually, a basic site is built with HTML, CSS, and JS together.

At its core JS as a language is used to create, calculate, target, delete, modify or manipulate something. Create, Read, Update, Delete

A typical line of JS will usually include a declaration of some kind, a function, a function call, or a sequence of the previously mentioned things.

JS works in a very atypical way from classic code languages, it was put together to work well with the web but breaks a few fundamental language rules at times.

The general way JS flows is top to bottom, and will only run one time Most of the time

Let’s Learn Some Common Keywords!

If this document is new will it function? Yes. Yes it will.

var - A variable is a stored set of information, it can be a boolean, null, undefined, a string, a float/integer, an array, an object, or more.

function - A function is made up of two parts, the function itself that runs any code inside of it, and the function call.

document - The document is an object that is essentially a collection of everything on your web page.

if / else if / else - An if statement creates a situation where if the set parameters are met, it will execute some code.

for - A for loop is a section of code that will run multiple times until the set parameters are met.

this - This is a special keyword which essentially references whatever scope you are currently working in.

class - A class is a type of object that can be cloned to create duplicates of itself, the class object in itself being a clone of the original class.

new - New is a constructor that creates a copy of a JS class, which is essentially a pre-made sort of object.

Variable Types

Be a good kid and play with your string.

Boolean : true | false
A boolean is a set of two states, true and false. They are essentially the foundation of all code.

Number : float(1.01, 1.02, 1.03) | integer(1, 2, 3)
Weirdly enough, a number in JS can be both a float or an integer at the same time. There is no restriction on the type of number it can be.

String : 'Hi' '🍑'
A string is a set of characters or text, it can include other languages, with mainly Unicode text.

Array : [true, 5, scrollValue, 'eggplant']
An array is an ordered collection of any other kind of variable, they are accessed by referencing the number "index" of where a value is. example[0] === true
Arrays also contain a .length property, it shows how many spots are being held.

Object : {wig: null, location: ['Outer Space', 'On Mars']}
An object (similar to an array), holds values in it but with a specified key and value relationship. It does not have a length, and to reference something you need to use the key. example.wig === null

Null : null
A null value is simply an empty variable, it doesn’t mean anything and will not do anything.

undefined : undefined
An undefined value is similar to that of a null, however, it more specifically means that the variable you are trying to use has not been defined yet with a value or at all. It’s the default value

NaN : NaN
A NaN value is similar to both undefined and null, but is more like an error, stating that the value you are trying to use as a value is "Not a Number."

If statements

If the earth is flat, live in fear. Else, just live your life I guess...

An if statement, as mentioned earlier, is a code segment that will run, top to bottom only if the provided parameter you set is valid (true).

When using && and || it reads left to right, so be sure that for && you have things in the proper order.

You always start with an if, followed by as many else if as you want or simply an else with no parameters.


if (eggs >= 12) {
    bakeCake();

} else if (eggs == 6) {
    makeOmelette();

} else if (eggs == 1 && people !> 2) {
    makeFriedEgg();

} else {
    console.log("Buy Eggs")
}

                    

For Loops

You are from here on our banished, for i < 100*years.

A for loop is a section of code that loops a specified amount of times until it’s set condition is no longer valid.

Be careful when using a for loop, if your conditions can never be met it will loop infinitely.

The for loop has a cousin that serves a relatively similar purpose, the while loop, which will continue until the set condition is false. Be very careful with it, you have to create the iteration condition inside of it and will also loop infinitely if used wrong. while( i > 5 )

The for loop also has a close sibling, the forEach function, that serves to loop through all of the values inside of an array. It will run your code with the variable name you set for the values and apply the code to all of them in order. You can call the values whatever you want, and if it is an array filled with objects can loop through specific keys. array.forEach(function(value){console.log(value)})


for ( var i = 0; i < 365; i++ ){
    console.log(“WATCH ME COUNT” + i);
};

                    

Comparison Operators

if (pineapple === onPizza || pizzaSize != 'large')

> - Greater Than

< - Less Than

>= - Greater Than and Equal to

<= - Less Than and Equal to

== - Equal to

=== - Equal to and Equal to variable type

! - not

!= - Not Equal to

!== - Not Equal to and Equal to variable type

&& - And

|| - Or

+ - Add values (or string)

- - Subtract values

++ - Add 1 to a value

-- - Subtract 1 to a value

* - Multiply Values

/ - Divide Values

+= - Add values directly to initial value

-= - Subtract values directly to initial value

*= - Multiply values directly to initial value

/= - Divide values directly to initial value

Minor Other Stuff

I mean just look at ({['"that"']})

Bracket Types

( ) : functions & conditions
Regular round brackets are only used when it comes to functions and conditions when using for loops, while, loops, if statements and more. You use them to create functions with parameters or to call functions.

{ } : start & end/thing to be executed
Squiggly brackets/Braces are used to show the start and end of a set of code to be executed, usually after the if statement, function declaration, or for loop. They are also used with objects showing the start and end of an object.

[ ] : array
Square brackets show the start & end of arrays, they can be used to reference specific spots in arrays and in objects as well! object[key] === object.key

Additional Syntax

.
As you have probably seen already the . is used quite a bit in JS, its purpose is mainly to access properties inside of something, or to apply a function call on something. Which does contain that function in it.

Advanced JS

var John {You just don't get the real me John. You don't get me at all!}

If you don't have a good understanding of JS SKIP THIS SECTION!

When trying to understand more complex comparators, functions, scope, and calls it's important to properly know basic JS.

I'm going to be going over key concepts and a lot of ES5 ECMAScript 5 / JS 5

Scope

Scope is a concept that is used in most code languages to dictate where the reach of certain variables and functions are allowed to be used.

Compared to most languages JS uses a weird rigged up version of scope, that works in it's own unique way; and has just began opening it's doors to more traditional code syntax with ES5.

Scope is generally dictated by functions, classes, and objects; with the global scope being outside of everything.

I'm sure you've seen that when a variable is in the global scope it can be used anywhere, while when it's declared inside of a function or another scope it cannot be used outside of that scope.

Also, be sure to keep in mind that JS looks for variables from the current scope first and moves outwards until it reaches the global scope.


var example = true; This is an example of global scope

function functionScope() {
var scoped = true;This is an example of lexical scope

console.log(example)works

}

console.log(scoped)doesn't work

Advanced JS +

() => {const things = 'are 'bout to get severe up in here.'}

Alternate Var declarations

let : permanently scoped
Let assignment declarations are strictly scoped, which means that even trying to set one outside of its scope will result in an error. They are very useful in for loops, as they retain their values throughout all iterations and don't overlap.

const : permanent variable & scoped
Const, like a let, is scoped to whatever location it is placed in, the only difference is that that constant's value can not be reassigned (updated). constantVariable = 5; will not work

Callback/Fat Arrow functions

A callback function or fat arrow function is in a way a shorthand on anonymous functions. It works the same as any function, but without a name.

Functions can also start themselves after being declared by adding () around and to the end of an anonymous function.

It looks like the following: (anyVariablesGoHere) => { //... }


const example = true; This is an example of global scope

(() => {
let scoped = true;This is an example of lexical scope

example = falsedoesn't work
scoped = falseworks

})()

scoped = falsedoesn't work

Advanced JS ++

This prototype has got me scoping out some new objects/arrays.

Classes & Prototypes

Classes are essentially like function-y objects, they are templates with keys and properties that are duplicate themselves.

That being said, they're not perfect copies, they still connect to their original with a "prototype" or "__proto" key. Protos can be modified, but it's bad practice

When creating a class, they usually contain a "constructor", a function that builds and stores all of the properties that are passed into a class when called.

this

This is something you may have seen before, it is a very useful keyword that references the current scope.

It references itself in a sense and allows you to reference other parts of the scope in cases where they may be out of scope.

In some cases you may need to "bind" the current this, because when you call a function you're switching also switching the current scope to the scope of that function.


class Soup {
constructor(soupType, makeSoup) { soupType = this.soupType,
makeSoup = this.makeSoup().bind(this),

}

function makeSoup () {
console.log('Your ' + this.soupType + ' has been made!'); }
}

let chickenSoup = new Soup('Chicken Soup');

chickenSoup.makeSoup(); Should return "Your Chicken Soup has been made!"

Help & Troubleshooting

HELP! EVERYTHING IS UNDEFINED!

Check that everything is spelled correctly & that your stylesheets and external files are linked correctly.

Check it again! Trust me check your code again to be sure you didn’t miss anything.

Use the Developer Tools Inspector generally by right-clicking and selecting inspect.

console.log() anything you want to check and look at the console tab in the inspector window.

If some external file or resource is not loading you can check the network tab to see all the requests the site has made and any failed ones.

Try Google-ing the problem.

Ask a prof, peer, mentor, or me!

If none of that solved your problem.. Honestly just cry and give up at that point.

Common JS Errors

My console has 0 errors and nothing is working...

Be sure to check the following:

Spelling of Ids and Classes is consistent and correct.

When using getElementsByClassName, remember it returns an array so use getElementsByClassName[elementYouWant].

Make sure your > and < are facing the right direction.

Make sure your brackets are closing properly; sometimes formatting or beautifying your code helps.

Make sure the stuff you're referencing is within the function or global (see scope).

Check for loops and if statements to make sure they have the right condition.

Look for missing semicolons ; , apostrophes ' ' " " , squiggly brackets { } , or regular brackets ( ) , or commas ,

Tips

For all you cool kids 😎

Using objects saves the number of variables you have if the variables are related

Use querySelector or quereySelectorAll to find stuff easier and faster. It's like getElementById, getElementsByClassName, and getElementsByTagName all in one

Use incredibly descriptive function and variable names so you know what they do and don't have to take notes.

Keep all of your variables near the top, and space out your functions & if statements, it improves the readability of your code.

Use eventListeners, they make interactions with things on screen a dream instead of adding onClicks, onMouseOver, etc... in your HTML.

Use the import and export functionalities of ES6 (JS6), to separate big chunks of code into other files which you can import when needed.

Use Ternary Operators, you can essentially write an if statement in half the time. They work like this [condition] ? [true] : [false]; and they return the value you put in each of the true and false conditions (and yes you can string them together).

Use !! before any variable reference to forcibly make it into boolean instead of whatever value it is. So if var egg = 1; !!egg is true.

That’s all for now!

Be sure to contact me if you have any questions or concerns