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));

Ironhack Day 6

JavaScript

1. Example of using an (anonymous) callback function like setTimeout with an asynchronous method:

function init(){
setTimeout(function(){
console.log(’Hi again!’)
}, 8000)
}

init()
console.log(’Hi!’)

// Hi!
// (after 8 sec) Hi again!

2. Using setInterval with an asynchronous method (it calls a function repeatedly with a fixed delayed time between each call):

var i = 10;
var intervalId = setInterval(function() {
if (i > 0) {
console.log(i);
} else {
console.log(”Pop!”);
clearInterval(intervalId);
}

i–;
}, 1000);

// 10
// 9
// 8 etc.
// Pop!

3. When using prototype it’s the instance of the prototype (here the function Car) that has priority over the prototype itself, that’s why below fiat will be red and not blue:

function Car(){
this.color = ”red”
}

Car.prototype.color = ”blue”

var fiat = new Car()

console.log(fiat.color)

// ’red’

4. To speed up your code it’s better to define properties in the prototype instead of defining them in the constructor (=in the function Car):

function Car(){
//this.color = ”red”

}

Car.prototype.color = ”blue”
Car.prototype.wheelsNum = ”4”

var fiat = new Car()

console.log(fiat.color)

var factory = []

for (var i = 0; i < 100; i++) {
factory.push(new Car(”))
}
console.log(factory)

5. In order to make an object be an instanceof another object you have to use both the .call method and prototype:

function Animal (name, owner, sound) {
this.name = name;
this.owner = owner;
this.sound = sound;
}

function Dog (name, owner){
Animal.call(this, name, owner);
this.sound = ”Guau Guau”;
this.humanRelation = ”love”;
}

Dog.prototype = Object.create(Animal.prototype);

var myAnimal = new Animal(”Arya”, ”Josephine”, ”–”);
var myDog = new Dog(”Max”, ”Owen”);

Bootstrap:
1. Remember to add the jquery cdn at the bottom of your html (see https://code.jquery.com/) before the bootstrap.min.js, like this:

<!– jQuery (necessary for Bootstrap’s JavaScript plugins) –>
    <script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”></script>
    <!– Include all compiled plugins (below), or include individual files as needed –>
    <script src=”js/bootstrap.min.js”></script>
  </body>
</html>

2. Customizing Bootstrap: http://getbootstrap.com/customize/

3. Alternatives to Bootstrap:
http://materializecss.com
http://foundation.zurb.com

4. Free Bootstrap themes: https://bootswatch.com/

Ironhack Day 5

JavaScript:

1. Use ’this’ e.g. when you want to create new objects based on your function (remember to use ’new’ when creating new objects + the convention is to use capital letters for the name of the function in such cases to show they are classes; classes behave like blueprints, prototypes, etc.: they are there in order to enable you with the help of ’new’ to make as many instances of them as you want):

function Car(name){
this.name = name;
this.sayMyName = function() {
console.log(”This car’s name is ” + this.name);
};
}

var kitt = new Car(”Knight Industries Two Thousand”);
var modelS = new Car(”Tesla Model S SuperCar”);

kitt.sayMyName(); // => My name is Knight Industries Two Thousand
modelS.sayMyName(); // => My name is Tesla Model S SuperCar

2. When invoking a method in an object, ’this’ becomes the object itself:

var kitt = {
name: ’Knight Industries Two Thousand’,
sayMyName: function() {
console.log(”My name is ” + this.name);
}
};

var modelS = {
name: ’Tesla Model S SuperCar’,
sayMyName: function() {
console.log(”My name is ” + this.name);
}
};

kitt.sayMyName();
modelS.sayMyName();

3. Simple multiplying function with ’this’:

function Calculator () {
this.total = 0;
this.multiply = function(first, second) {
this.total = first * second;
console.log(this.total);
};
}

var s = new Calculator();
s.multiply(2,3);

4. Calculator with prototype:

function Calculator(){

this.number1 = 0;
this.number2 = 0;
this.result = 0;

Calculator.prototype.askNumber1 = function(){
this.number1 = parseInt(prompt())
}

Calculator.prototype.askNumber2 = function(){
this.number2 = parseInt(prompt())
}

Calculator.prototype.showResult = function(){
console.log(this.result)
}

Calculator.prototype.add = function(){
this.result = this.number1 + this.number2
}

Calculator.prototype.multiply = function(){
this.result = this.number1 * this.number2
}

Calculator.prototype.substract = function(){
this.result = this.number1 – this.number2
}

Calculator.prototype.divide = function(){
this.result = this.number1 / this.number2
}
}
Calculator.prototype.add = function() {
this.result
}
var calc = new Calculator()

calc.askNumber1();
calc.askNumber2();
calc.add();
calc.showResult();

5. Link to DOM (Document Object Model) properties: https://developer.mozilla.org/en-US/docs/Web/API/Document#Properties

6. Link to DOM methods: https://developer.mozilla.org/en-US/docs/Web/API/Document#Methods

Ironhack Day 4

JavaScript:

map is very similar to forEach (both are used to process arrays), except that forEach simply iterates over an array and allow us to do something with each element, while map iterates over an array, BUT returns a new array where each element of the new array is. Examples:

1a. Map:
var array = [1, 2, 3];

var newArray = array.map(function(number){
return number * 2;
})

console.log(newArray);
// [ 2, 4, 6 ]

1b. To achieve the same thing with forEach, you need a longer code:

var array = [1, 2, 3];
var newArray = [];

array.forEach(function(number){
newArray.push(number * 2);
})

console.log(newArray);
// [ 2, 4, 6 ]

2. Another example of using map (turning the first letters of an array’s elements into capital letters):

var cities = [”miami”, ”barcelona”, ”madrid”];

var capsCities = cities.map(function(city){
return city.charAt(0).toUpperCase() + city.slice(1);
})

console.log(capsCities);
// [”Miami”, ”Barcelona”, ”Madrid”]

3a. Using .reduce to get the sum of a number array + print also currentIndex and the array:

var numbers = [2, 4, 6, 8];

var total = numbers.reduce(function(previous, current, currentIndex, originalArray){
console.log(previous, current, currentIndex, originalArray);
return previous + current;
}, 0);

console.log(total);
// 20

3b. Using .reduce to get the sum of a number array:

var numbers = [2, 4, 6, 8];

var total = numbers.reduce(function(previous, current){
/*console.log(previous, current);*/
return previous + current;
}, 0);

console.log(total);
// 20

4a. Calculate the sum of an array’s objects’ properties (like age of persons) using .reduce:

var people = [
{ name: ”Candice”, age: 25 },
{ name: ”Tammy”,   age: 30 },
{ name: ”Allen”,   age: 49 },
{ name: ”Nettie”,  age: 21 },
{ name: ”Stuart”,  age: 17 }
];

var ages = people.reduce(function(sum, person){
return sum + person.age;
}, 0);

console.log(ages);
// 142

4b. Calculate the sum and average of an array’s objects’ properties using .reduce:

var menu = [
{ name: ”Carrots”, calories: 150 },
{ name: ”Steak”, calories: 350 },
{ name: ”Broccoli”, calories: 120 },
{ name: ”Chicken”, calories: 250 },
{ name: ”Pizza”, calories: 520 }
];

var totalCalories = menu.reduce(function(previous, current){
return previous + current.calories;
}, 0);

var averageCalories = totalCalories / menu.length;
console.log(averageCalories);
// 278

5. Using forEach to calculate sum of elements in an array:

var numbers = [1, 2, 3, 4];
var total = 0

numbers.forEach(function(number){
total += number;
})

console.log(total);
// 10

6. Find certain elements in an array with .filter:

var numbers = [1, 2, 3, 4, 5, 6];

var evens = numbers.filter(function(number){
return number % 2 === 0;
});

console.log(evens);
// [ 2, 4, 6 ]

7a. Sorting an array’s elements in numerical order from lowest to highest:

var numbers = [22, 23, 99, 68, 1, 0, 9];

console.log(numbers.sort());
// [ 99, 68, 23, 22, 9, 1, 0 ]

7b. Sorting an array’s elements in numerical order from highest to lowest:

var numbers = [22, 23, 99, 68, 1, 0, 9];

numbers.sort(function(a, b){
// switch the order of the comparison
return b – a;
});

console.log(numbers);
// [ 99, 68, 23, 22, 9, 1, 0 ]

8. The thisIsMyCB function below is called a callback or higher order function, i.e. you pass a function as an argument and use it inside the other function (more about callback functions: http://callbackhell.com):

function main(thisIsMyCB){
var something = ”bla”;
thisIsMyCB(something);
}

main(function(something){ /*FUNCTION HERE REFERS TO thisIsMyCB*/
console.log(”I’m anonymous ” + something)
})

9. Sort string array alphabetically:

var words = [”Hello”, ”Goodbye”, ”First”, ”A”, ”a”, ”Second”, ”Third”];

words.sort()

console.log(words);

10. Sort string array in descending alphabetical order:

var words = [”Hello”, ”Goodbye”, ”First”, ”A”, ”a”, ”Second”, ”Third”];
words.sort(function(a, b){
if (a > b){ return -1; }
if (a < b){ return 1; } return 0; }); console.log(words); 11. Sort string array by length: var words = [”Hello”, ”Goodbye”, ”First”, ”A”, ”a”, ”Second”, ”Third”]; words.sort(function(a, b){ if (a.length > b.length){ return -1; }
if (a.length < b.length){ return 1; }
return 0; });
console.log(words);
//[ ’Goodbye’, ’Second’, ’Hello’, ’First’, ’Third’, ’A’, ’a’ ]

12. Lodash JS library: https://lodash.com/docs/

Ironhack Day 3

Thought of the day: huge amount of new things to process, not much time to digest them.

My notes from the class:

JavaScript:

1. In order to assign the property of an object to a variable you have to use bracket notation, e.g.:

var columns = {
left: true,
center : false,
right : false
}
var side = columns[’left’];
console.log(side);

2. Accessing properties of an object example 1:

var user = {
name: ”snoopy”,
age: 25,
size: ”small”,
toys: [”bone”, ”ball”],
address: {
street: ”bla”,
number: 23
}
}

console.log(user.toys[1]);
console.log(user.address)
console.log(user.address.street)

Accessing properties of an object example 2:

var book1 = { title: ”The Catcher in the Rye”, author: ”J.D Salinger”, isbn: ”0316769487”, category: ”Classic Literature” };
var book2 = { title: ”To Kill a Mockingbird”, author: ”Harper Lee”, isbn: ”0446310786”, category: ”Classic Literature” };

var library =[book1, book2]
console.log(library[1].title)

3. Accessing properties of an object containing an array:

var library= [
{ title: ”The Catcher in the Rye”, author: ”J.D Salinger”, isbn: ”0316769487”, category: ”Classic Literature” },
{ title: ”To Kill a Mockingbird”, author: ”Harper Lee”, isbn: ”0446310786”, category: ”Classic Literature” }
]

console.log(library[0].title)

4. If you use an array inside an object instead of an object inside an object it will be easier to access the respective properties. Example:

var classRoom = {
teacher: { firstName: ’Marcelino’, lastName: ’Padberg’, age: 25 },
students: [
{ firstName: ’Aliyah’, lastName: ’Schulist’, age: 18 },
{ firstName: ’Cleveland’, lastName: ’Towne’, age: 28 },
{ firstName: ’Jan’, lastName: ’Quitzon’, age: 18 },
{ firstName: ’Alaina’, lastName: ’Runolfsdottir’, age: 18 },
{ firstName: ’Gerhard’, lastName: ’Bergstrom’, age: 23 }
]
};

console.log(classRoom.students[2].firstName);
// ’Jan’

console.log(classRoom.teacher.age);
// 25

CSS:

1. Something I didn’t know about advanced selectors:

advanced selectors in css

2. Useful site if planning to use transitions: http://cubic-bezier.com/

3. If planning to do css animations, you might find this site useful: https://daneden.github.io/animate.css/

4. For inspiration on how to use keyframes for css animations check e.g. https://codepen.io/tag/keyframes/

Ironhack Day 2

There are two kinds of students here: those who have spent years programming and/or have a science degree and the rest. I belong to the latter category. For the former group this bootcamp is a stroll in the park, for the latter it’s overwhelming. That’s just how it is, trying to face the music and hope I’ll come out of this experience with a bit more solid knowledge of web dev than what I’ve had before.

That being said here are my notes from day 2:

CSS:

Learned that the absolutely positioned div is relative to its parent if the latter is positioned relatively. If there’s no such parent, then it will be positioned relatively to the body.

JavaScript:

Learned i.a. about anonymous functions, recursion, high-order functions and forEach method, see details below.

1. Anonymous function:

var anon = function(){
console.log(”An0nym0us Funct10n”);
}

anon();

When calling this function the function itself will be printed, i.e. ”Function: anon”, instead of ”An0nym0us Funct10n”.

2. Recursion (function definitions that are implemented in a way they use their own definitions. It’s like function inception. Btw factorial of a non-negative integer n is the product of all positive integers less than or equal to n, e.g. 5 ! = 5 × 4 × 3 × 2 × 1 = 120):

function factorial(number) {
if (number === 0) { return 1; }
return number * factorial(number – 1);
}

3. High-Order Functions: functions can return functions or receive other functions as parameter.

var add = function (a) {
return function (b) {
return a + b;
};
};

var add2 = add(2);
add2(3);
// => 5

add(4)(5);
// => 9

4. forEach:
Example nr 1:
var raceResults = [’Hellen’, ’John’, ’Peter’, ’Mery’];
raceResults.forEach(function(elem, index){
console.log(elem + ’ finished the race in ’ + (index+1) + ’ position!’);
});

Example nr 2:
function averageWordLength(words) {
var sum = 0;
words.forEach(function(word){
sum = sum + word.length;
})
var average = sum/words.length;
return average;
}

var words = [
”seat”,
”correspond”,
”linen”,
”motif”,
”hole”,
”smell”,
”smart”,
”chaos”,
”fuel”,
”palace”
];
var averageLength = averageWordLength(words);
console.log(averageLength);

Syntax:
arr.forEach(function callback(currentValue, index, array) {
//your iterator
}[, thisArg]);

Ironhack Day 1

On the first day of my Ironhack Web Dev Bootcamp our teacher, Thor (great name, btw!) made a super-quick summary of Git, Github, HTML, CSS and JavaScript (mainly things we’ve had to read for the pre work exercises of the bootcamp). Below are the things that grabbed my attention:

Git & Github:

  • touch index.txt (create file)
  • nano index.txt (open the files, used for making small changes)
  • cat index.txt (check what the file contains)
  • going back to previous versions with the help of git log, was introduced to the concept of HEAD

 

JavaScript:
The following notes are related to the pair work we did after the actual teaching. Even though my head was spinning after that, given the fast pace at which my team mate, who’s been working with JS for 6 years, was coming up with different possible solutions to the exercises, it’s been incredibly useful for me. Besides the things listed below my main take-away was seeing in action how one translates to JS’ logic (functions, loops, if statements & all that jazz) the instructions given in more or less plain English.

  • use of functions: noticed there are two cases where we were supposed to print words backwards
  • use of .indexOf for ”translating” characters from a string into numbers (=their position in the string) in order to check which of the strings comes first in an alphabetical order
  • use of .replace in order to be able to ignore spaces between words when checking whether the string entered by the user is a palindrome or not
  • counting number of words in a text by checking how many blank spaces the text contains
  • counting how many times a word has been used in a text by checking: 1. if the first characters of the text match with the word we’re looking for; 2. if there are in the text cases when a blank space is followed by these characters, which are in turn followed by another blank space.