an introduction
> npm install -g eslint nodemon node-inspector
Install tools using npm
console.log("Hello world")
// Example
var ourName;
// Define myName below this line
ourName = "Nick";
// Example
var ourVar = 19;
JavaScript provides seven data types:
undefined, null, Boolean, string, symbol, number, and object.
declared variables have an initial value of undefined
var product = 8 * 0;
var quotient = 66 / 0;
JavaScript uses the * symbol for multiplication and / symbol for division.
// Example
var array = ["John", 23];
// Initialize an empty array
var myArray = [];
// Empty existing array
array = []
// Example
var ourArray = [1,2,3];
var ourData = ourArray[0]; // equals 1
ourArray[1] = 3; // ourArray now equals [1,3,3].
// Example
var ourArray = ["Stimpson", "J", "cat"];
ourArray.push(["happy", "joy"]);
// ourArray now equals ["Stimpson", "J", "cat", ["happy", "joy"]]
var removedArray = ourArray.pop();
// removedArray now equals ["happy", "joy"], and ourArray now equals ["Stimpson", "J", "cat"]
removedArray = ourArray.shift();
// removedArray now equals "Stimpson" and ourArray now equals ["J", "cat"].
ourArray.unshift("Happy");
// ourArray now equals ["Happy", "Stimpson", "J", "cat"]
In JavaScript, we can divide up our code into reusable parts called functions.
function functionName() {
console.log("Hello World");
}
var array = [1,2,3]
array.map(function(num) {
return {value: num}
});
// [{value: 1}, {value: 2}, {value: 3}]
In JavaScript, scope refers to the visibility of variables. Variables which are defined outside of a function block have Global scope. This means, they can be seen everywhere in your JavaScript code.
var foo = 'Canadian Developer Connection';
console.log(foo); // Prints 'Canadian Developer Connection'
if(true){
var foo = 'BAR';
console.log(foo); // Prints 'BAR'
}
console.log(foo); // Prints 'BAR'
Variables which are declared within a function, as well as the function parameters have local scope. That means, they are only visible within that function.
function myTest() {
var loc = "foo";
console.log(loc); // "foo"
}
myTest(); // "foo"
console.log(loc); // "undefined"
It is possible to have both local and global variables with the same name. When you do this, the local variable takes precedence over the global variable.
var someVar = "Hat";
function myFun() {
var someVar = "Head";
return someVar;
}
console.log(myFun()); // Head
console.log(someVar); // Hat
function func(x){
console.log(typeof x, arguments.length);
}
func(); //==> "undefined", 0
func(1); //==> "number", 1
func("1", "2", "3"); //==> "string", 3
Using arguments.length property, we can get the total number of arguments passed to a function.
Write a mul function which will produce the following outputs when invoked:
console.log(mul3(2)(3)(4)); // output : 24
console.log(mul3(4)(3)(4)); // output : 48
var ourDog = {
name: "Camper",
legs: 4,
tails: 1,
friends: ["everything!"]
};
var myObj = {
prop1: "val1",
prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
// setting object property
myObj.prop1 = "Happy Camper";
var myDog = "Hunter";
var dogs = {
Fido: "Mutt",
Hunter: "Doberman",
Snoopie: "Beagle"
}
var breed = dogs[myDog]; // "Hunter"
console.log(breed)// "Doberman"
// Example
var ourDog = {
"name": "Camper",
"legs": 4,
"tails": 1,
"friends": ["everything!"]
};
// adding property
ourDog.bark = "bow-wow";
// deleting property
delete ourDog.tails;
var alpha = {
1:"Z",
2:"Y",
3:"X",
4:"W",
...
24:"C",
25:"B",
26:"A"
};
alpha[2]; // "Y"
alpha[24]; // "C"
var value = 2;
alpha[value]; // "Y"
Objects can be thought of as a a dictionary. If you have tabular data, you can use an object to "lookup" values rather than a switch statement or an if/else chain.
You are given a JSON object representing (a small part of) your record collection. Each album is identified by a unique id number and has several properties. Not all albums have complete information.
Write a function which takes an id, a property (prop), and a value.
For the given id in collection:
Always return the entire collection object.
// Setup
var collection = {
2548: {
album: "Slippery When Wet",
artist: "Bon Jovi",
tracks: ["Let It Rock", "You Give Love a Bad Name"]
},
2468: {
album: "1999",
artist: "Prince",
tracks: ["1999", "Little Red Corvette"]
},
1245: {
artist: "Robert Palmer",
tracks: [ ]
},
5439: {
album: "ABBA Gold"
}
};
function update(id, prop, value) {
return collection;
}
console.log(update(5439, "artist", "ABBA")[5439].artist) // ABBA
console.log(update(1245, "tracks", "Addicted to Love")[1245].tracks[0]) // Addicted to Love
We are also able to create objects using constructor functions.
A constructor function is given a capitalized name to make it clear that it is a constructor.
var Car = function() {
this.wheels = 4;
this.engines = 1;
this.seats = 1;
};
var myCar = new Car();
console.log(myCar.wheels); // 4
The constructor we have is great, but what if we don't always want to create the same object?
To solve this we can add parameters to our constructor. We do this like the following example:
var Car = function(wheels, seats, engines) {
this.wheels = wheels;
this.seats = seats;
this.engines = engines;
};
var myCar = new Car(6, 3, 1);
console.log(myCar.wheels); // 6
We can also create private properties and private methods, which aren't accessible from outside the object.
var Car = function() {
// this is a private variable
var speed = 10;
// these are public methods
this.accelerate = function(change) {
speed += change;
};
this.decelerate = function() {
speed -= 5;
};
this.getSpeed = function() {
return speed;
};
};
// create an object
var myObject = {};
// create a method on our object
myObject.someMethod = function () {
console.log(this);
};
// call our method
myObject.someMethod();
Object invoked the function, so this will refer to the Object that called it:
// let's assume .elem is <div class="elem"></div>
var element = document.querySelector('.elem');
// our function
var someMethod = function () {
console.log(this);
};
// when clicked, `this` will become the element
element.addEventListener('click', someMethod, false); // <div>
// if we just invoke the function, `this` becomes the window object
someMethod(); // [object Window]
This is dynamic, which means the value could change. Here’s a real simple example to show that:
someMethod.call(anotherScope, arg1, arg1); // commas
someMethod.apply(anotherScope, [arg1, arg1]); // array
We can change context of a function with a few methods, .call(), .apply() and .bind().
var obj = {};
var element = document.querySelector('.elem');
var someMethod = function () {
console.log(this);
};
element.addEventListener('click', someMethod.bind(obj), false); // bind
Using bind
var monica = {
name: 'Monica Geller',
total: 400,
deductMontlyFee: function(fee){
this.total = this.total - fee;
return this.name + ' remaining balance is '+ this.total;
}
}
console.log(rachelDeductor(400)); //"Rachel Green remaining balance is 1300"
Given the code below. Add the necessary code to output the following to the console:
Rachel Green remaining balance is 1300
var oldArray = [1,2,4]
var timesFour = oldArray.map(function(val){
return val * 4;
}); // [4,8,16]
array = timesFour.filter(function(val) {
return val !== 8;
}); // [4,16]
The array method reduce is used to iterate through an array and condense it into one value.
var array = [8,6,4,2]
var singleVal = array.reduce(function(prevVal, curVal) {
return prevVal + curVal;
}, 0);
console.log(singleVal); // 20
sort can be passed a compare function as a callback. The compare function should return a negative number if a should be before b, a positive number if a should be after b, or 0 if they are equal.
var array = [1, 12, 21, 2];
array.sort(function(a, b) {
return a - b;
});
console.dir(array); // [1,2,12,21]
use for each to iterate over an array with a callback function
var array = [1, 12, 21, 2];
array.forEach(function(x) {
console.log(x);
});
concat can be used to merge the contents of two arrays into one.
newArray = oldArray.concat(otherArray);
Given the following array of todo items, use functional programming to:
var data = [
{
username: "batman",
subject: "Read about functional programming",
dueDate: "01/15/2016",
complete: false
},
{
username: "batman",
subject: "Try out the Node Stream Adventure",
dueDate: "01/01/2016",
complete: false
},
{
username: "robin",
subject: "Build Todo app based on Highland js",
dueDate: "02/01/2016",
complete: true
},
{
username: "robin",
subject: "Build GraphQL server for Star Wars API",
dueDate: "03/01/2016",
complete: false
}
]
Results should look like
{ robin:
[ { subject: 'Build GraphQL server for Star Wars API',
dueDate: '03/01/2016' } ],
batman:
[ { subject: 'Read about functional programming',
dueDate: '01/15/2016' },
{ subject: 'Try out the Node Stream Adventure',
dueDate: '01/01/2016' } ] }
ES2015
Lodash
Classes
Arrow functions
const, let, var
enhanced object literals
template strings
modules
promises
JavaScript utility library
http://lodash.com