Don't wanna be here? Send us removal request.
Text
More Functions
A return statement gets values out of functions.
Functions can have scope. If you put a function inside of a function, it is applies only within that function, like a variable.
Anonymous functions are unnamed functions. They’re used a lot in jQuery and typically used as callback functions are as arguments in another function. Functions stored in variables do not need function names. They are invoked by the variable name. Callback functions are a result of other things happening.
Functions inside of IIFEs (Immediately Invoked Function Expression) only work within the scope of the IIFE. IIFEs fire off as soon at the program reaches it.
(function() { // The code in here will execute immediately.
})();
Fat Arrow functions have somewhat replaced anonymous functions. They work pretty much the same.
Anonymous function:
function() {};
Fat arrow:
() => {}
IIFE with a fat arrow function instead of an anonymous function.
(() => {
// The code in here will execute immediately.
})();
Fat arrow functions can be used in place of callback functions.
Array methods
forEach is an array method that allows you to be able to get a single element from an array and then do something to them. It’s callback function accepts a single element from the array as its argument.
favoriteMovies.forEach(movie => console.log(movie.title));
In this example, it is pulling the “title” from each array.
The filter method accepts a single element in an array in the callback function’s argument. If the callback function returns true, then it returns what function is filtering.
const scifiMovies = favoriteMovies.filter(movie => movie.genre === 'Sci-Fi');
The map method is like the filter method except it puts the returned values into another array. You can also use map to do something to everything in an array.
const jamesCMovies = new Set();
favoriteMovies.map(movie => { if (movie.director === 'James Cameron') { jamesCMovies.add(movie.title); }
});
console.log(jamesCMovies); // ["The Abyss","Aliens"]
The reduce array method compares two things in the array, and it works it’s way through the entire array.
const newestMovie = favoriteMovies.reduce((previous, current) => {
if (current.release_date > previous.release_date) { return current; } return previous; });
console.log(newestMovie.title); // The Incredibles
0 notes
Text
Functions!
Functions make your life easier. It’s like using a dishwasher instead of washing every single dish by hand. Well except for the water and electricity - wasting aspect of it.
Making a function There are two ways to create a function. The first one is declarative style:
welcome(); // This is how to call a function
function welcome () { console.log('High five!'); // Put what you want to happen here. }
Anything you want to happen from the function goes between these guys {}.
The second is making the function a variable.
let welcome = function() {};
Functions assigned to variables have to be called AFTER they’ve been created.. If you use a declarative style, you can call the function wheneva. This is called hoisting.
Arguments Arguments go in between the parentheses. Here’s an example:
function doubleNum(poop) { console.log(poop * 2);
}
doubleNum(3);
doubleNum is the name of the function. Poop is the argument. Arguments are kind of like a placeholder or variable. They’re local variables, meaning they only work within the function.
You can add multiple arguments to a function.
// using multiple arguments
function add(number1, number2) { let num1 = Number(number1); let num2 = Number(number2);
console.log(num1 + num2); }
add(5,10);
Default Now let’s talk about defaults. Defaulting used to be terribly difficult. Now, ecma script has changed the game, man, and life is better for all of us. Here is how you can set defaults for multiple arguments.
// this is the best way to do defaults function betterDefaultValues (arg1 = 35, arg2 = 100) { console.log (arg1, arg2); }
betterDefaultValues ();
The Rest Parameter
As in the rest of the values....Nice pun, ecma scriptmakers. Every function has an invisible variable called arguments, and it exists inside the function. You use the rest parameter when you have an indeterminate amount of variables. 'all the rest of th arrays get stuck in it'
function multiplyAll(...numbers) { let output = 1;
for (let number of numbers) { output *= number; } console.log (output); }
0 notes
Text
Sets, Objects, Loops & JSON
Sets
Sets have unique values. Sets are used when you don’t want values to be repeated. There is no way to get a value out of an array; there’s no need to. You might want to use a set to take out duplicates then convert it into an array. You can put any kind of data in a set.
Sets look like this:
const family = new Set(['Jack', 'Jill', 'Michael', 'Tony']);
You can add a single value to a set like this:
family.add(’Rosie’);
You can add an array to a set like this:
family.add(['Leah', 'terry']);
Even though you can’t get a value out of a set, you can find out what the value is this way:
family.has (’Jack’); // true
You can delete values from a set like this:
family.delete(’Jill’)
You may find that you want to use the functions of an array on a set. In this case you can convert the set to an array this way:
let familyArray = Array.from(family);
You can use array.from() to convert both sets and maps to arrays.
Objects
Objects are another way of putting together key value pairs, kinda like sets. I’m under the impression that objects are pretty important since everyone says it’s an object-oriented language. In an object, the key is a string and the property is a javascript value.
You can create an object using two ways: object literals or use the constructor syntax. Constructor syntax is usually not necessary and it can add more steps.
Object literals look like this:
const movie = {};
Constructor syntax looks like this:
let movie = new Object ();
Here’s an object with properties:
let movie = { name: 'E.T.', year: '1982', rated: true, numberRerelease: 3, starring: ['Henry Thomas', 'Drew Barrymore', 'Peter Coyote'], };
Objects and arrays are mutable, meaning they can change. In contrast, strings are immutable; they cannot change.
100 === 100 // true
[100] === [100] //false
This last one is false because arrays are all their own and can change. One apple does not equal an apple even if they look and taste the same. They are still not the same apple!
You can assign properties to an object using dot syntax.
movie.director = ‘stephen spielberg’;
You can delete properties this way:
delete movie.director;
You can define an object as a constant and still change its inside because it’s mutable. However you can not change its data type, like changing it from an object to an array.
Side note (i.e. something I should remember) : Any number divided by 0 is infinity
Loops
For is basically a function. Inside the for loops, we put in three expressions:
1. Define a variable to keep track of where we are (initial state)
2. a condition that needs to remain true to keep looping and is where you want the loop to end (the condition)
3. the increment. (final statement)
An example loop that logs Aaliyah’s album One in a Million track list backwards:
let OneMillion = [ 'Beats 4 da Streets(Intro)', 'Hot Like Fire', 'One in a Million', 'A Girl Like You', 'If Your Girl Only Knew', 'Choosey Lover', 'Got To Give It Up', '4 Page Letter', 'Everything\'s Gonna Be Alright', 'Giving You More', 'I Gotcha\' Back', 'Never Givin\' Up', 'Heartbroken', 'Never Comin\' Back', 'Ladies in da House', 'The One I gave My Heart To', 'Came To Give Love (Outro)' ];
for(let i = OneMillion.length-1; i >= 0; i--) { console.log(OneMillion[i]); }
While is kinda like the for loop. It’s just written a different way
And here’s an example:
for(let i =1; i < 11; i++)
For..of loop has very important limitations. It only works with arrays, sets and maps. It logs every element in the array, set or map. You can’t go backwards or skip a few - it logs EVERY element. It logs every element in an array. It’s has limited, specific function.
Here’s the syntax breakdown:
for( let an item of an array, set or map of name of array) { console.log (show); }
And an example:
for (let track of OneMillion) { console.log(track); }
For..in loop works the same way but with objects and is pretty useless.
JSON
JSON is only 10 years old.
You cannot have methods in JSON. JSON is not dynamic. Everything is static. No functions. And NO COMMENTS! JSON doesn’t like opinions.
It’s a universal data format, and it used to send information between servers & browsers.
Basically a browser asks a server for some data. Then the server sends the JSON. Once the browser has it, it is converted into a string to be transferred using the stringify function. Then the browser parses it and changes it back to javascript.
Stringify example:
const jsonString = JSON.stringify({"title": "Alien", "genre": "Sci-Fi", "release_date": 1979, "director": "Ridley Scott"}); console.log(jsonString);
Parse example:
console.log(JSON.parse(jsonString).title);
0 notes
Text
Making a Server, Arrays & Maps
I MADE A SERVER!
I’ve been working in the three.js library trying to figure stuff out. I pretty much have no idea what I’m doing. After five billion hours of trying to figure out why I couldn’t make a texture map with an image, I finally got it: Since I was working with WebGL, it wouldn’t allow me to see the texture map because it was on my computer rather than coming from a computer. Why? I did a less than two minute search on this in which pretty much nothing came up except for a rando blog that said it was for “security reasons”. mmhmmmmmmm...
Anyways, to create a server is simple. You make a new js file and call it something. In my case, I called it server.js, and I saved it in the root directory. In the js file I put this piece of code that I got from here :
//Lets require/import the HTTP module var http = require('http'); //Lets define a port we want to listen to const PORT=8080; //We need a function which handles requests and send response function handleRequest(request, response){ response.end('It Works!! Path Hit: ' + request.url); } //Create a server var server = http.createServer(handleRequest);
//Lets start our server server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray! console.log("Server listening on: http://localhost:%s", PORT); });
Then I went to the terminal and typed
$ node server.js
And boom! Texture maps appeared! W O W !
Big dumb lists [Arrays]
Arrays are used to make a list of items. You can have numbers, booleans, other arrays, objects amongst other things in an array.
There are two ways to make array. The literal way:
let arrayName = [];
Or the constructor array:
let constructorArray = new Thing();
There’s no good reason to use one over the other. It’s really a matter of preference. You coding preference also comes into play in the form of the array. An array can look like this:
let tlc = [’t-boz’, ‘left eye’, ‘chili’]
or you may like it to form like this:
let tlc = [ ‘t-boz’, ‘left eye’, ‘chili’ ]
If you prefer it the former way, you can control this in your linter with the comma dangle property. Look it up.
To find out how many items are in an array, use the length property.
tlc.length; //3
To grab an element out an array, use the square brackets:
console.log(TLC[ 1 ]; // left eye
To add an element to the beginning of an array, use
unshift().
To add an element to the end of an array, use
push(),
To add elements to the beginning of an array use
splice(index of where you want to stick it, how many you want to delete and what you want to add); For example
tlc.splice(1, 0, ‘Justin Bieber’); // [’t-boz’, ‘left eye’, ‘Justin Bieber’, ‘Chili’]
Obviously, you can also use splice to delete elements as well.
Maps
A map is like creating a chart of key & value pairs. I have no idea what an object is but I learned that maps are different from objects because:
Keys in maps can be anything
Maps have a size property.
The only way to add things to a map is to add it at the end.
There is only way to make a map and it looks like this:
const STACI = new Map();
You can either have the values entered before you create the map or after. If you do it before, the map will look like this.
let natoMap = [ ['a','apple'], ['b','butter'], ['c','crepe'] ['d','donut'], ['e', 'eel'], ['f', 'fork'], ['g', 'grain'], ['h', 'hi'], ['i', 'ice cream'], ['j', 'jackalope'], ['k', 'king'], ['l', 'lemon'], ['m', 'money'], ['n', 'noon'], ['o', 'octopus'], ['p', 'pie'], ['q', 'quell'], ['r', 'red potato'], ['s', 'sour'], ['t', 'turnip'], ['u', 'ugly'], ['v','velveeta'], ['w', 'water'], ['x', 'xylophone'], ['y', 'yuck'], ['z', 'zephyr']
];
let alphabetSoup = new Map(natoMap);
To add values after, use set.
alphabetSoup.set('zz', 'ZZ Top');
To access keys, use get and enter in the key, or left hand value.
alphabetSoup.get(’a’);
To delete keys, use delete and the key you would like to delete.
alphabetSoup.delete(’b’);
Annnddd that wraps it up!
0 notes
Quote
Arrays are kind of just big dumb lists.
Rob
0 notes
Text
Operators & Control Flow Statements
Operators
Every variable needs a value otherwise it’s undefined, and operators do just that - give value. All operators are expressions. It’s math, man.
There are four kinds of operators:
Assignment operators give value to the left side oper based on what’s on the right.
Comparison operators do exactly what it sounds like - they compare the operand on the left with the right. That comparison produces a boolean value.
Arithmetic Operators are essentially math equations. They produce numerical values and use numeric operands.
Logical operators are freaking cray. They use two operands and evaluate based on the truthiness of them.
Control Flow Statements
Control Flow statements tell the program what to execute.
**If **statements look like this:
if ( an expression) { what will happen if the expression is true } if (someVariable > 100) { x = 32; }
If…else statements give an alternative if the expression is not true.
if (someVariable === true) { console.log(‘Woo!’); } else { console.log(‘Bummer.’); }
You can also use a Ternary Operator for short hand
let someVariable = (an expression) ? ‘if the expression is true this statement happens’ : ‘if is not true, this happens’
if (day = ‘Saturday) ? ‘Woo!’ : ‘Boo!’; If…elseif give even more alternatives! if (day === 'Saturday' || day === 'Sunday') { activity = 'EVERYTHING!'; } else if (day === 'Monday' || day === 'Wednesday') { activity = 'Going to work & then class'; } else if (day === 'Tuesday' || day === 'Thursday') { activity = 'Going to work'; } else { activity = "SLEEPING"; }
Switch statements are an alternative to else if statements.
var Age = '17'; var milestone = undefined; switch (Age) { case '5': case '6': milestone = 'You are starting school!'; break; case '13': case '14': milestone = 'You are starting high school!'; break; case '16': milestone = 'You can officially drive!'; break; case '18': milestone = 'You're freeeeeeee!'; break; default: milestone = 'Life sucks.';
}
The program runs until it hits break. Switch statements only test for equality
0 notes
Text
Lesson 3
After three classes, I’m finally getting the hang of installing gulp & using the terminal. After the past few classes, I’ve been finding random gulp files in weird places on my computer, but NO MORE! I’ve got it.
The short-and-sweet step-by-step:
1. First set up the root folder. Create an index.html file and gulpfile.js and a folder called “src” and put a js file in there.
2. Add this to to gulpfile.js :
var gulp = require('gulp'); var babel = require('gulp-babel'); var sourcemaps = require('gulp-sourcemaps');
gulp.task('babel', function () return gulp.src("src/**/*.js") .pipe(sourcemaps.init()) .pipe(babel()) .pipe(sourcemaps.write()) .pipe(gulp.dest("dist")) ;
});
gulp.task('default', ['babel'], function() {}); gulp.task('watch', function() { gulp.watch('src/**/*.js', ['babel']);
});
gulp.task('default', ['babel', 'watch'], function() {});
3. Go to terminal and type:
cd {folder path}
4. Then initialize the node package manager in the terminal:
npm init
5. Install the plugins:
npm install --save gulp gulp-sourcemaps gulp-babel gulp-watch
6. Test gulp by typing gulp into the terminal.
In addition to finallllyyy getting into the swing of gulp, we’re getting into some of the basics of any language: syntax!
Statements perform an action ; they do something. Expressions produce values. Sometimes you can express same behavior in both statements & expressions.
Semicolons indicate an expression or statement has ended.
Comments act as reminders and documentation of your work. Reminders can be pertinent because, I mean, do you really think you’re going to remember what that variable is in 6 months?! The web is a constantly changing place and things are always being edited. Documentation is important for other people (and also yourself, again) to know what’s going on in your code if it needs to be edited. There are three types of comments:
Single line comments begin line comments with “//“ Multi-line comments begin with /* and end with */ Doc Block style starts with /** and ends with */. This stye is help for documenting your work. It can be used by some programs to actually create your documentation
To declare a variable you can use var, let and const. Variables cannot start with numbers. Variables must start with an upper- or lower-case letter, a dollar sign ($), or an underscore '_' and can contain any of those plus numbers.
Var is going out of style - it is a blanket way of creating a variable. Let has just been released in ECMAscript, and is replacing many instances of var. A let value is only pertinent within the scope of the brackets it’s attached to. Const is used for constant variables, or variables that cannot be changed. It has also been recently introduced. In the past, constants were represented with all uppercase letters. By convention, const variables are typically uppercase. It is good practice to start with all variables being constants until you need to change them unless you know they will need to change later on. On a side note, variables that start with underscores should only be used within its class by convention.
To get the value of a variable just type in console.log (your variable). The console will tell you the value of that variable. However it will also show it as undefined because the value has not been returned.
....aaaaand that wraps it up!
0 notes
Text
ACA HTML Intermediate: First Week
Javascript, man. It can really set off a website from being cool to freakin’ amazing. As a designer, I’ve been able to get a good handle on HTML & CSS, but javascript has been a beast in and of itself. Up to this point, well documented js plugins with explicit tutorials have been my godsend when I’m making websites on my own. I’m really excited to learn more about it. I’ve got my sights set high — one day I’ll be able to make something like dilladimension.com…..right? Webgl maybe? Amirite?
Alright here it goes…my first week was rushed endeavor so that I wouldn’t have to wait until the next class in February. Here’s what I learned:
To start with, we got on this node.js shtick. Node.js allows you to run a “web server virtual machine” with javascript. I thought servers were real machines that you can touch so I’m not sure how one can be virtual, so I’ll just call this magic until further investigation. In the past, javascript has been mainly used for client-side stuff, but node.js allows it to run on your computer & do stuff that is typically server-side…like the stuff php, ruby and python do. Whoa. It allows you to do stuff on your machine to make things easier while you’re developing, such as make your SASS css files.
At this point, we began creating a space to start writing some javascript using the following tools:
NPS “Node Package Manager” : it’s essentially a project manager and makes sure all the stuff to run your project are in the folder
Gulp : it’s a tool that makes working way easier, such as checking for writing errors
Babel : we haven’t gotten into this very deeply but it sounds like it’s a javascript translator from the future.
In working with with Node.js, you have to know some command line stuff. Command line sounds more like a name for something in a drum & bugle corp band, but it’s the things you do in the terminal.
I struggled with doing the homework because I HAD NO IDEA WHAT I WAS DOING IN THE TERMINAL! In any interaction with the terminal previous to this, I ran away from computer in fear that it would probably blow up if I typed anything in the terminal. My first problem was that I couldn’t tell if I was in the folder I was trying to be in! Now I know you just have to say cd at the beginning. After that point, I was able to begin doing the steps outlined in the lesson.
A few good-to-know short cuts on the command line:
$ is not stuff that is actually typed, just denotes a line in the terminal.
cd = change directory
$ cd ~/path/to/some/folder
—————————————————————
~ = shortcut
—————————————————————
pwd = present working directory
—————————————————————
mkdir = make directory
$ mkdir {name of directory}
—————————————————————
touch - create file
$ touch {file name}
—————————————————————
ls - list directory
$ ls -a1H
a= show all
l= list format
h= simplify sizes of files
—————————————————————
clear = clear your code
—————————————————————
history = shows history that you’ve been doing
—————————————————————
! {line of history} = runs that line of code
—————————————————————
!! = runs the last thing that you did
—————————————————————
up and down arrows go through your history
—————————————————————
control c = quits a task
So. I was able to get all this stuff set up to write Javascript. But WTF is Javascript? A language I don’t know, that’s for sure. As with any language there’s a few basics of Javascript that are helpful to know.
The Name & its History
So according to this dude Dr. Axel Rauschmayer, “The programming language is called JavaScript, the language standard is called ECMAScript. They have different names, because there is a trademark on “Java” (held by Oracle). At the moment, only Mozilla is allowed to officially use the name “JavaScript”, because they received a license long ago. Therefore, an open language standard had to have a different name.” By “language standard”, it sounds like he means the rules of the language.
Javascript was started by some guy at Netscape, and other browsers started joining in on the fun. All the browsers started having their own dialect of Javascript, and as versions started rolling out these browsers starting fighting over the diction of writing javascript and would often come to the conclusion that writing both ways was okay. Today, there are multiple ways of writing some parts of Javascript for that reason.
In the future, Javascript will no longer roll out in versions. It will be constantly evolving, with ever feature rolling out on a case-by-case basis. I mean, who wants to wait around for different versions?? IMO, that’s pretty cool.
Now getting into actually writing Javascript...
Primitive Data Types
A boolean can only have a value or true false. Truthy means boolean values that return as “truth”
Falsy means boolean values that return as “false”
The value null represents a placeholder value.
Numbers can be both integers & decimals.
A string is a sequence of characters and literals are shown in quotes.
To get a character’s place in a string, you can use panagram[] or charAt(). To get its length, you can use the length property.
When variables have been declared but don’t have a value or a function doesn’t include a return that value is undefined.
....and that wraps it up!
0 notes