Blog

Ironhack Day 22

Node JS

1. Using render instead of get:

> // require the Drone model here

const router = express.Router();

router.get(’/drones’, (req, res, next) => {
// Iteration #2
router.get(’/’, (req, res, next) => {
Drone.find({}, (err, drones) => {
console.log(drones);
if(err) {next(err);} else {
res.render(’drones/index’, {drones:drones});

A shorter way of writing this is: res.render(’drones/index’, {drones});

2. Node JS tutorials on Youtube: The Net Ninja – Node JS Tutorial for Beginners

Ironhack Day 17

MongoDB:

0. How to start mongo in the terminal:

a. start_mongo

b. open new tab and type mongo

c. open third tab and node index.js

1. Show me element’s name but not its id:

db.enemies.find({”name”: ”Blinky”}, {name: 1, _id:0})

{ ”name” : ”Blinky” }

2. Show property of an embedded document, notice the use of quotations marks (phone is an embedded document of the employees database, since it has different properties, among them ”ext”):

db.employees.find({”phone.ext”: ”2143”})

3. Updating a document:

db.employees.updateOne(
{ ”name”: ”Martin”},
{ $set: { ”phone.ext”: 1234 }}
)

4. Replacing an object of an array:

var susan = {
”name” : ”Susan”,
”age” : 25,
”phone” : { ”personal” : ”555-223-223”, ”work” : ”555-421-426”, ”ext” : 4240 },
”privileges” : ”user”,
}

db.employees.replaceOne(
{ ”name”: ”Martin”},
susan
)

5a. Deleting one element:

db.employees.deleteOne( { ”_id”: ObjectId(”583ea82c58613b64d5df8405”) })

5b. Deleting several elements:

db.employees.deleteMany({ age : { $gte: 30 }})

5c. Delete all:

db.employees.deleteMany({})

6. Use mongoimport to import documents into a collection:

$ mongoimport –db restaurants –collection restaurants –drop –file ~/downloads/primer-dataset.json

7. The only reason to use the $and operator is to apply more than one condition (that isn’t equality) over the same field:

db.users.find({
$and: [
{”age”: {$gt: 18}},
{”age”: {$lt: 30}}
]
})

OR

db.restaurants.find({
$and: [
{”borough”: ”Brooklyn”},
{”grades.score”: {$gte: 80}}
]
}).pretty()

8. Sorting (note: 1 here is for ascending and -1 for descending order):

db.restaurants.find().sort( { ”borough”: 1, ”address.zipcode”: -1 } )

9a. Counting all the number of documents:

db.restaurants.find().count()

9b. Counting certain documents:

db.restaurants.find({”grades.score”: {$gte: 10}}).pretty().count()

10. Find documents according to their positions in the array (here they are in position two):

db.restaurants.find({”grades.1.grade” : ”A”}).pretty()

9. Example of deleting one document from your Mongo DB:

db.projects.remove( { ”name” : ”bla”})

Ironhack Day 16

ES6

0. ES6 compatibility table: https://kangax.github.io/compat-table/es6/

1.Using classes:

class Product {
constructor (name, price) {
this.name = name;
this.price = price;
}

nameAndPrice () {
console.log(
”The product’s name is: ” + this.name,
”The product’s price is: ” + this.price
);
}
}

const banana = new Product(”Banana”, 2);
banana.nameAndPrice();

2. Inheritance and overwriting methods (see the second nameAndPrice below):

class Product {
constructor (name, price) {
this.name = name;
this.price = price;
}

nameAndPrice () {
console.log(
”The product’s name is: ” + this.name,
”The product’s price is: ” + this.price
);
}
}

class Electronic extends Product {
constructor (name, price, brand) {
super(name, price);
this.brand = brand;
}

nameAndPrice () {
console.log(
”The product’s name is: ” + this.name,
”The product’s price is: ” + this.price,
”and the brand is ” + this.brand
);
}
}

var banana = new Product(”Banana”, 2);
banana.nameAndPrice();

var mac = new Electronic(”Mac”, 200, ”Apple”);
mac.nameAndPrice();

3. If statements and for loops don’t have own scope:

for (var i = 1; i <= 30; i++){
console.log(”Iteration number: ” + i);
}

console.log(”After the loop”, i);
//After the loop 31

4a. Block scoping with let (incorrectly):

for (let i = 1; i <= 30; i++){
console.log(”Iteration number: ” + i);
}

console.log(”After the loop”, i);
//for After the loop: ReferenceError i is not defined

4b. Block scoping with let (correctly):

let name = ”Ironhacker”;

if (true){
let name = ”Ted”;
console.log(”Name inside of if statement: ” + name);
}

console.log(”Name outside of if statement: ” + name);

// Name inside of if statement: Ted
// Name outside of if statement: Ironhacker

5. Although you can’t reassign ’con’, you can still modify its properties:

const TAXES = {
normal: 0.21
}

console.log(TAXES)

TAXES.normal = 0.23

console.log(TAXES)

// { normal: 0.21 }

// { normal: 0.23 }

6. Arrow functions are syntactic sugar over the typical function declaration, with an added bonus: a new function scope is not created:
class Counter {
constructor(){
this.count = 1;
}

countUp(){
setInterval(() => {
console.log(this.count);
this.count++;
}, 1000);
}
}

var myCounter = new Counter();
myCounter.countUp();

Ironhack Week 3

This week everyone’s worked on his/her own project: building a JavaScript/JQuery game of their choise. Even though a week might seem a short time for such a project for someone who was practically thrown into the deep and murky water of web dev just two weeks earlier it felt like a blessing to have time to go thru (many times with the teacher assistant) everything we’ve learned so far and build the game by the book (more or less), i.e. creating a file for the logic of the game and another one for the DOM manipulation, using a constructor in the ”logic file”, using prototypes as well different array methods (splice, sort, pop and _shuffle from LoDash) and manipulating the DOM with JQuery and/or ”pure” JavaScript. Below is the outcome of my project, a game which solves all the problems of the numerous advanced students of Finnish who are dying for revising their sports vocabulary in Finnish ; -)

P.S. I”ve probably never felt so stupid in my entire life like during the first two weeks of this course. Everything we were taught in the morning we had to practice in the afternoon and evening and it’s not only that there was a huge amount of new information to process, but also the exercises we were given were (as I’ve found out later on), to put it mildly, challenging, even for my course mates who have been doing programming much more seriously than myself and for a much longer time. Then came this third week, when I embraced that my web dev knowledge is close to zero and that the last two weeks’ learning material is in an absolute chaos in my head and decided to work my way up from there. With a lot of help from the TA. I’m still useless when it comes to e.g. JavaScript katas used in technical interviews, but hey, I’ve done this project and I more or less understand everything in my code. Except perhaps the part on generating randomly the Finnish word and the English translations so that there would always be different translations on the different cards + that one of the cards contains the right translation. My head is still spinning every time I read that code. Well, that’s how it is right now, but some day, one day…

 

photo of http://bjim-com.stackstaging.com/Memrise-Fin/

Ironhack Day 8

JavaScript:
1. Passing functions into other functions as arguments (i.e. resultFn, which will be ”replaced” in the add() function call by logDone or square):

function add (first, second, resultFn) {
console.log(”Add function started”);
resultFn(first + second);
}

function logDone (num) {
console.log(”I’m done! The result is: ” + num);
}

function square (num) {
console.log(”The square is: ” + num*num);
}

add(2, 3, logDone);
add(2, 3, square);

2. Using functions as variables (here: logDone):

function add (first, second, callbackFunc) {
console.log(first + second);
callbackFunc();
}

var logDone = function() {
console.log(”I’m done!”);
};

add(2, 3, logDone);

3. ’Return’ breaks the flow of the code and returns a value:

var sayHello = function(){
return ”I’m a string”;
console.log(’hello’);

}
console.log(sayHello())
//”I’m a string” (i.e. console.log won’t work, because of breaking the flow of the code with return)

4. Reassigning a variable (console.log will print out 4, because of reassigning var a to 4 inside function inner):

var a = 1;
var b = 2;

function inner() {
a = 4; // not using `var`
var b = 3; // using ’var’ | Shadowing the global variable
}

inner();
console.log(a);
console.log(b);

5a. Because of hoisting when console.logging inside a function the globally defined variable that has been reassigned inside that function we’ll get an ’undefined’ for it:

var name = ”Fer”;

function changeName () {
console.log(”Original name was ” + name);

var name = ”Harry”;
console.log(”New name is ” + name);
}

changeName();
//’Original name was undefined’
//’New name is Harry’

5b. Fixing the ’undefined’ problem mentioned above:

var name = ”Fer”;
console.log(”Original name was ” + name);

function changeName () {

var name = ”Harry”;
console.log(”New name is ” + name);
}

changeName();
//’Original name was Fer’
//’New name is Harry’

6a. When using ’this’ in a function inside a function, ’this’ will refer to the global variable, in this case the var value = 500:

var value = 500;
var obj = {
value: 0,
increment: function() {
this.value++;

var innerFunction = function() {
console.log(this.value);
}

innerFunction(); // Function invocation pattern
}
}
obj.increment(); // Method invocation pattern
//500

6b. Making sure the ’this’ in a function inside a function is referring to the right variable:

var value = 500;
var obj = {
value: 0,
increment: function() {
var that = this;
that.value++;

var innerFunction = function() {
console.log(that.value);
}

innerFunction(); // Function invocation pattern
}
}
obj.increment();
//1

7a. Modifiying with ’apply’ the context to which ’this’ may refer to (here from the object foo to window):

var obj = {
foo: function(a, b, c) {
console.log( arguments );
console.log( this );
}
};

obj.foo(1,2,3);
// ==> [1,2.3]
// ==> obj {}

obj.foo.apply(window, [1,2,3]);
// ==> [1,2.3]
// ==> window {}

7b. Modifiying with ’bind’ the context to which ’this’ may refer to (here from the object foo to window):

var obj = {
foo: function() {
console.log( this );
}
};

var bindFoo = obj.foo.bind(window);

obj.foo(); // ==> obj
bindFoo(); // ==> window

8a. ’this’ is referring to the object AT THE MOMENT OF THE EXECUTION, that’s why in the jQuery code below ’this’ works only when pressed the first time (after that you get undefined):

var dog = {
sound: ”Whoof!!!”,
makeSound: function(){
console.log(this.sound);
}
}
dog.makeSound()

$(’button’).click(dog.makeSound());

8b. Making ’this’ work every time you click the button with the help of ’bind’:

var dog = {
sound: ”Whoof!!!”,
makeSound: function(){
console.log(this.sound);
}
}
dog.makeSound()

$(’button’).click(dog.makeSound.bind(dog));