javascript
var, let and const
A var
is a statement that defaults a function-scoped or a globally-scoped
variable. It is also added as a non-configurable property to the global object.
The let
statement created a variable that is block scoped. They are still
accessible from blocks that are children of the block the variable was declared
in.
If let
is not written, javascript quietly creates a global binding and uses
it.
Strings
Javascript template literals allow you to add variables in a string.
let age = 33; let name = 'Paul'; let out = `My name is ${name} and I am ${age}`;
Object Literals
const person = { name: 'Paul' }; // You can add data willy nilly! person.email = "[email protected]";
Object Destructuring
You can pull data out of an object using a technique called object destructuring.
const person = { firstName: 'Paul', lastName: 'Sammut', age: 33, address: { street: '50 main st', city: 'NY', state: 'NY' } } const { firstName, lastName, address:{ city } } = person;
Arrays
There are a bunch of array operations:
shift()
- removes and returns the 0th' element of an array
unshift()
- adds 1 or more elements to the start of an array
Iterating through arrays is a whole thing of course. There are a bunch of ways
to do it. You can while loop it, or you can make use of the for…of
statement.
Filter
Arrays have a filter function that is very powerful. You pass in a function that defines the filter criteria. Very cool.
let applicants = [ { name: "Joe Shmoe", country: "US", age: 33 }, { name: "Rob Parny", country: "GB", age: 29 }, { name: "Rob Parly", country: "GB", age: 16 }, { name: "Lem Meloo", country: "IT", age: 75 } ] let onlyUsApplicants = applicants.filter(app => app.country === "US");
Map
A map
function allows you to go through the elements of an array and build a
new array with returned values of the function passed into map that can act on
each element.
Reduce
A reduce
function is used to compute a single value from an input array. At
its basic form it requires a combining function that combines to elements of the
array.
It can also be used to get a max or min of an array. For example:
let data = [ { name: "red", count: 32 }, { name: "green", count: 2 }, { name: "black", count: 1 },
Some && Every
some
is a function that acts on arrays by taking in a logical test function.
If any of the elements in the array passes the test, it returns true.
every
is a function that acts on arrays by taking in a logical test function.
If all of the elements in the array pas the test, it returns true.
Composing
Composing
is when you get start chaining high-order functions to get to a
result or subset of data in a few lines of code.
// Filter and map to a new array let dirs = SCRIPTS.filter(script => script.living).map(script => { return { name: script.name, direction: script.direction}; });
Functions
There's 3 ways of writing a function in JavaScript.
Using a function
expression:
const fun1 = function(x) { return x*x; };
Using a function
decleration. The interesting thing with this is that you
can call a declared function before it's declated, as they are moved to the top
of their scope, and all code in that scope can use them. They also don't need a
semicolon at the end.
sayHello(); function sayHello() { console.log("Hi!"); }
Using the arrow
notation. This is a third and compact way of writing
functions. If you don't put curly braces and have a single expression, it will
be returned.
const sayHi = () => { console.log('hi'); }; const returnOne = () => 1;
Functions in javascript ignore extra parameters you pass in and also add undefineds for parameters you don't pass in.
Functions in javascript can be named or anonymous. They have access to local variables that are in the scope of their parent functions.
function fun2(){ var output = "" if(typeof myGlobal != "undefined"){ output += "myGlobal: " + myGlobal; } if(typeof oopsGlobal != "undefined"){ output += " oopsGlobal: " + oopsGlobal; } console.log(output) }
Higher-Order Functions
Higher-order functions are functions that operate on other functions, either by passing them in as a parameter or by returning them.
The shit you can do with functions is nuts.
let repeat = function(n, action){ for(let i = 1; i <= n; i++){ action(i); } }; repeat(3, n => { console.log(n); });
Callbacks
You can pass around functions willnilly in javascript. You can easily pass them in as parameters to functions.
function useFunction(func1, func2){ func1("Pass this to func1"); func2("Pass this to func2"); } var firstFunc = function(in){ console.log(in); } var secondFunc = function(in){ console.log(in); } useFunction(firstFunc, secondFunc);
Objects
Objecta can be defined as variables with member variables and functions inside curly braces.
var myPerson = { firstName : "Jack", lastName : "Smith", age : 19, employed : true fullName : function() { return this.firstName + " " + this.lastName; } }
They can also be defined as functions by making use the of the this
and
new
keyword.
function Person(firstName, lastName){ // construct the object using the arguments this.firstName = firstName; this.lastName = lastName; // a method that returns the fullname this.fullName = function() { return this.firstName + " " + this.lastName; } } var myPerson = Person("Paul", "Sammmut"); console.log(myPerson.fullName());
HTML
Javascript was designed to run in a browser and interact with HTML.
You can embed javascript in html sources and make use of many function that can modify HTML elements.
Equality
In javascript there are two equality statements, ==
and ===
.
Double equal: Loose equality check. Tries to coerse types so theres a match and then compares content.
Triple equal: Type and content have to match. Strict equality.
Control Flow
Switch
Switch statements are wierd in that statements start executing at the start of a matching label, and will keep executing accross other labels until it hits a break.
In the following if you pass sunny
Dress Light and Go out will print.
switch(prompt("PUT IN WEATHER")){ case 'rainy': console.log("Bring umbrella"); break; case 'sunny': console.log("Dress light"); case 'cloudy': console.log("Go out"); break; default: console.log("Unknown weather type!"); break; }
OOP
JavaScript OOP.
Methods
Methods in JS are simply properties that hold function values.
let rabbit = {}; rabbit.speak = function(line) { console.log(`I am saying '${line}'.`); } rabbit.speak("hi!");
Prototypes
JavaScript has inheritance. Almost every object in javascript inherits (directly
or indirectly) from Object.prototype
. This gives every object some basic
properties, including methods, such as toString()
.
Classes
You can have classes in JavaScript but they can only contain methods. They cannot contain non functions, such as variables.
class Rabbit{ constructor(type){ this.type = type; } speak(line) { console.log(`This ${this.type} rabbit says '${line}'.`); } } let killaRabbit = new Rabbit('killa'); let spottedRabbit = new Rabbit('spotted'); killaRabbit.speak('Hello precious..'); spottedRabbit.speak('I\'m spotted all ova');
call function
JavaScript has a call function that can be invoked on an function and allows you
to explicitly pass a this
object as the first parameter.
Object Spread Operator
The Object Spread Operator is …
and it allows you to spread concatenate lists in a one line. Link.
I was really confused about it when I saw it used to spread out properties of an object that was returned by a function here.
computed: { localComputed () { /* ... */ }, // mix this into the outer object with the object spread operator ...mapState({ // ... }) }