Techdegree Journal 6: An Easy Way To Remember How Functions, Arguments and Parameters Work Together

love-vs-hate-clinton-vs-trump-4aec5d0779eb57b5a491565e0b25fdf0

Unlike these two, this is the only time an ‘argument’ is good…

Functions

Last week, I spoke about how I was learning how local and function scopes effected functions and how they could be accessed by different parts of the program. But after reflecting and looking through my notes, I realised that I put the “horse before the cart” and should have spoke more about what a function actually does so here goes…

A JavaScript function is a group of statements (lines of code) that when activated, will perform a particular action. In my last blog post, I gave the example of telling my nephew that when I text him from work, that he would need to go to the store and bring me eggs, bacon and milk so that we could have a good breakfast the next morning.

To declare a function, all you need is:
* The keyword ‘function’
* A name goToStore
* A pair of parenthesis ()
* A pair of curly braces which will contain the task that needs to be completed {}

So if I were to write my nephew’s task in pseudo-code, it would look something like this:

function goToStore() {
drive to store;
buy eggs, bacon & milk;
return home;
}

goToStore();

The beautiful thing about functions is that if we can set up a task and when we call it, it will execute the whole thing without me having to write the whole task again. That what keeps the code “DRY”.

The DRY Principle

So I’ve mentioned the term “DRY” in previous posts but what does it actually mean? “DRY” means “Don’t Repeat Yourself” and this basically means that programmers should write the most efficient code possible with the least amount of lines. “DRY” code is:

  • Easier to read by other humans
  • Less bug (error) prone

Along with clear and concise documentation, DRY code makes our life easier!

Arguments and Parameters 

Take a look at this code:

function goToCoffeeShop() {
alert(“Coffee is on the way!”)
}

Now this is similar to the errand that I made my nephew do earlier but this time I asked him to go to the Coffee Shop and grab me a coffee and let me know that it’s coming. That function works perfectly fine but what if instead of a coffee, I wanted some flexibility and wanted to change my drink? Now we would have to do the code to do something slightly different…

function goToCoffeeShop(drink) {
alert(drink + ” is on the way!”)
}
goToCoffeeShop(“Espresso”)

Notice that when I declared (created) the function, the word “drink” is in the first set of parentheses? And when we ‘call’ the function, the word “Espresso” is in the second set? These are examples of parameters and arguments respectively.

In the simplest possible terms, an “argument” is a real value that can be passed to a function that, when the function is called, change the way that the function works.

A “parameter” behaves like a ‘container’ which holds the argument just like a variable will hold a value.

To a novice programmer like me, terms like ‘passing the argument to a function’ were baffling at first and I just couldn’t get my head around it. But being the super creative genius that I am (lol!), I created a mental image that helped me get my head around around it…

Going back to the coffee shop example, I told my nephew that when I contact him, he needs to go the Coffee Shop and grab me a coffee (declaring the function). But while I was at work I had a change of heart and wanted an “Expresso” (the argument). But I need to find a way to pass that information to my nephew.

real-prince-coffee

Sorry I just had to add this in… Too funny!

So after much heavy thinking, I send him a text message with the word “Expresso” – that text message acts as the parameter that ‘holds’ the instruction of what I want. The text message via the phone allows me to pass the instruction to my nephew to change my drinks order, the same way that I can pass a value to a function to change how it works.

Here is another example from my Techdegree:

170-parameter-assistant-2

If only getting your nephew to get things for you on time were this easy…

In this stage of my learning, I find functions fascinating and their applications so useful!
I know that you can only stretch an analogy so far but that mental picture really helped me get a grasp of the concept!

What do you guys think? Is there anything you wish to add? Leave your comments below or tweet at me @karlwebdev.

As always, I really appreciate your time & I will see you next Thursday!

Karlwebdev

Techdegree Journal 5: How JavaScript Functions Are Like the Marvel Cinematic Universe

Reading Time: 5 mins

mcu2

Functions… Assemble!

 

What has the snark of Tony Stark, rage of Bruce banner and the mystery of Black Widow got to do with an object orientated language like JavaScript? A lot more than you think…

As part of studying my FrontEnd Techdegree with Teamtreehouse, I’ve been looking at JavaScript (JS) functions over the last couple of weeks…

Now a ‘function’ is a set of statements (instructions which the browser will follow), which is designed to perform a particular task.

simple-function

The beauty of a function is that once we have written it once, then all we have to do is ‘call’ the function, (activate it by using the function name) and it will do everything that you have to ask it to do without writing it all again which saves tons of time and avoids you repeating yourself loads and loads of time.

simple-call-function

By just typing “sayHello()”, the whole function can executed without typing any additional code…

The best analogy that I can give is sending my nephew to buy groceries: Imagine that my 17 year-old nephew is staying with me over the Summer holidays and before I go to work, I tell him that he will need to buy eggs, bacon and milk from the local supermarket when I text him later in the day. I tell him the directions and how much each item will cost. My nephew memorises the instructions and waits for my text. Later in the day, all I would have to do is send a text saying “buy groceries” and my nephew grudgingly will get up, to the store and get the items that I requested. I wouldn’t have to ring him and repeat all the instructions again and we can enjoy a lovely english breakfast tomorrow morning!

Sweet. All was going well until my Techdegree threw me for a loop with this challenge…

172-lilah-george-lilah

Now this section of code will hen executed, will make the browser pop up either the name ‘Lilah’ or ‘George’ The 1st part of the code is a function that has a variable (which is a container) for the name ‘Lilah’. The next line creates an alert box which will display whatever is in that container (which is ‘Lilah’).

But outside that function we also have a variable called ‘person’ but this one contains the name ‘George’. So pop quiz hotshot, when the code runs, what names will appear and in what order?

You guessed it?

It would be Lilah, George and Lilah and here’s why:

1) “greeting();” jumps into the ‘function greeting’ and looks for the variable inside that function and creates a pop-up bar with the name ‘Lilah’.

2) On the next line, “alert(person)” can’t access that function (I’ll explain later) so it looks elsewhere for “var person” and finds one that contains “George”

3) Repeats Step 1.

It may seem easy now but when I first encountered this problem it was driving me crazy as I couldn’t figure it out. Shouldn’t it be all ‘Lilah’ or all ‘George?’

But Treehouse didn’t leave me hanging as they explained a little thing called ‘JavaScript Scopes’.

JavaScript Scopes

In JavaScript, a scope defines what a variables that you have access to and this has massive effect on how your programs run. They come in 2 basic flavours: The ‘Lilah’ variable is an example of a ‘Local Scope’ and ‘George’ variable is an example of a ‘Global’ scope.

Local Scopes

173-local-function

Variables that created within a JS function, become ‘local’ to that function. What that means is that local scopes can only be accessed within that function – basically a local function lives in it’s own universe as it may. You can only change anything in that function when you jump into that ‘universe’. Because it lives in its own ‘universe’, you can use variables with the same names in different functions.

Global Scopes

174-global-function

A variable declared outside of a function becomes global. That means that all the scripts and functions on a web page can access it. This is a much wider ‘universe’ and many more factors can affect it.

Now there’s a very special condition to this: If within a function, the ‘var’ keyword has not been added to the variable, it automatically becomes ‘global’.

i.e if our function was written like this:

function greeting() {

person = ‘Lilah’;

alert(person);

}

it would no longer be a ‘local’ function and this will completely change the result of our programs.

Anyway back to our example.

It was really tough to get my head around this until I had the genius idea to relate it to movie universes… Now we all know that Spiderman belongs to Marvel Comics which is also the home of The Avengers, Doctor Strange, Ant-Man and Guardians of The Galaxy. But why was it only in 2015, did we see Spiderman join the The Avengers in 2016’s “Captain America: Civil War?”

This was because SONY studios owned the Spidey’s movie rights from 2001 to 2016 when they did a co-licensing deal with Marvel. SONY’s spiderman movies are an example of a ‘local scope’ and the Marvel Cinematic Universe (MCU) is an example of a ‘global scope’.

Local Spiderman

spider-man-trilogy-the-amazing-spider-man-original-imadg7dwcjwhgzgc

Although Spidey operated in New York like The Avengers, he could never rub shoudlers with any of them because they could never step into his ‘world’. Any of Spidey’s city destroying battles did not have an effect on any of the comics nor the MCU films.

Like a local variable, Spiderman could only deal with the characters related directly to him and thus did not have the chance to crossover.

Global Avengers

mcu-time

Whereas like a global variable, the MCU holds most of the film rights to it’s most iconic characters which means they exist in a bigger ‘universe’. The MCU not only ties into the movies, but the TV shows, comics and games meaning that what happens in one medium has a direct effect in what happens in another.

A great example is after The Avengers defeated Loki and his alien army in the first Avengers film in New York, TV shows like ‘Agents of Shield’, ‘Daredevil’ and ‘Luke Cage’ showed the aftermath of the battle and how city was permanently changed.

And to take it even deeper, when Spiderman crossed over into the MCU universe is an example of how when the ‘var’ keyword is not declared in a local function, it can become ‘global’ and be accessed by all. In “Captain America: Civil War”, Spidey was a pivotal player in the battle and was a firm fan favourite!

This is all a bit of fun but it really helped me get my head around scopes and I hope that it helps you too!

What do you think? Can you you think of any better examples? As always, leave your comments below or tweet me @karlwebdev!

See you next Thursday!

 

Techdegree Journal 4 “Building A Responsive Web Page”

Reading Time: 3 minutes

sausage_dog-rwd

If only we could change our pets sizes like that in real life…

Introduction

I’m on Project 2 of Teamtreehouse’s Front End Design Techdegree and that involved me creating a website that will change depending on the size of the device screen. I had to create it to fit three sizes:

  1. Mobile screens @320px
  2. Tablet screens @769px
  3. Desktop screens @1020px

I was supplied the images & the mock-ups & was told it should be done in under 6 hours. Hang on to your butts…

Thoughts & Takeaways

As a coding newbie, this was initially very daunting… Sure I’ve created static HTML websites, but creating a fully responsive site involved a little more thinking and understanding how all the elements interacted with each other. After a couple of hours of hacking some code  – I did it! Here’s 4 things that I learnt while doing this project.

1) Don’t panic!

When I was initially given the mock ups, I felt like Jeff Goldblum when he saw the mothership in Independent Day – I was terrified and in awe at the same time.

jeff-min(1)

They… They have media queries…

What I did was work through the HTML and make sure that I had all the relevant elements included before I thought about presentation. Also I remembered the “mobile first” approach which was to design a single column layout then add more features for the subsequent sizes. Writing the HTML was laying down the foundation of the site and it made me feel more confident.

2) Breakdown your CSS

After I wrote up all my HTML, I started to address the CSS presentation. What proceeded to do was to create ‘comment headers’ of different parts of my site & add additional comments where necessary.

CSS headers

Having headers using comments makes life so much easier.

Not only did this help to keep my code neat, it proved invaluable later as it help me find where different declarations were quickly and easily especially if I’d left it for an hour or two. Also having my CSS headers help my thinking process as it gave me a structure to work with.

3) Floats

This project really helped me get my head around floats and the way that they effect other elements. One particularly tricky part of designing this page was dealing with collapsing containers. As we know, floats take elements out of the normal flow of the page and place it on the left or right of his parent container. Now if you float a parent element that has nothing but floated elements i.e. the navigation bar, the height of the container will collapse.

non cleared elements

My picture and the blurb should sit within the header where the nav bar is but because they are floated, the header’s height collapsed…

 

This is mind-boggling at first and I got frustrated – but that’s just how floats work. There are a number of ways to deal with this, but the method that are used was the “clearfix” method which which forces the parent element to clear is floated children.

clearfix

The “clearfix” forced the height to open back up… Much better!

Here’s a great explanation on how this works & this was really helpful.

4) Use the Developer Tools

The Chrome Developer Tools to Front End Developer is what x-ray vision is to superman – essential to help us solve problems and save the day!

developer tools

Positioning elements with floats may produce wacky renders. The Developer Tools helped me understand what’s going on behind-the-scenes of my webpage and how my positioning changes are effecting other elements. This insight allowed me to see the tweaks I needed to make to help the page look better.

Key takeaway

This was it very tricky yet enjoyable project. The key lesson I learnt when building a responsive website is, take your time and start with a mobile layout first. Mobile layouts are simple to put together and will give you the confidence to create more complex iterations of the same website. Take your time, take breaks and do it step-by-step – you will get there.

Thank you for reading and please let me know what you thought about my post! Leave a comment or tweet at me!

See you next Thursday!

Karlwebdev

Techdegree Journal 3 “Don’t Repeat Yourself. Seriously Don’t.”

Reading Time: 2 minutes

IMG_3521

Summary

I often like to take time out of coding on my computer, to go over old notes that I have written. What I have found is that once I’ve gone ahead and learnt new things, all the concepts that I found difficult, often like magic makes sense and this is where I get my lightbulb moments!

IMG_3518

One of the concepts that I found difficult to get my head around what is the “Don’t Repeat Yourself” (DRY) philosophy that was taught by the excellent Guil Hernandez on “CSS basics ” course at Treehouse

Guil explains that:

“DRY is a CSS philosophy where your aim is to write the most effective code with the least amount of lines possible. Repeated code makes the CSS style sheet harder to maintain and makes the browser work harder.”

Thoughts and Takeaways 

The DRY concept in a way it is like watching “The Sixth Sense” Movie for the first time. You think that you understand what’s happening and then the surprise twist at the end makes you realise that you’re watching a different movie all along (Damn you Bruce Willis!)

Initially I thought that DRY was concerned with the use of IDs and classes. But might been diesels voice, DRY goes a lot deeper than that. As I started to embrace dry, it helped me make my code cleaner, easier to understand and more readable.

For example, I saw the use of drying using shorthand. If I wanted to change the attributes of my particular font would be like so:

font long

Whereas if I use the font shorthand, it would be:

font long copy

Same thing but uses less lines of code:

Also HTML5 includes new elements that help make your markup more readable. For example if I was styling a simple webpage and I was creating containers, I would have to use with IDs & classes to describe what they are like so:

div

Whereas with the new elements, they are self explanatory. Also notice there are less lines of code.

nav

Key Takeaway

Taking time to learn how to use class is affectively, learning shorthands and using new HTML elements can make your code leaner, cleaner and and help you become a better coder. It did for me!

Catch you again soon!

Karlwebdev

Techdegree journal – entry 2 “Keep Your Comments to Yourself!”

Reading Time: 2 minutes

tdd-test-driven-development-and-coding-quotes-19-638

Summary

As I stated before “How To Make a Website” taught by the wonderful Nick Pettit and here’s a super quick summary of what I went over today…

  • Comments – Comments are reminders or visual cues in computer code that’s meant to be readable by programmers. These comments won’t be picked up by the browser and this helps others understand the code that you have written.

Thoughts and takeaways

Comments are not the most sexy subject are they? Talking about comments compared to talking about Front End design is like choosing to ride in a Ferrari F12 Berlinetta or your Grandma’s old Skoda. Not sexy. at. all.

But I realised how critical comments can be – and it’s not for other programmers but for yourself.

comments

Making headers and placing my lines of code underneath each header helped me to understand what the heck was going on in my CSS. Writing comments forced me to actually think about what I was writing and where necessary move things to more relevant places. It felt like I was ‘spring cleaning’ my code! It also forced me to think about structure – rather than plonking random CSS selectors all over the place, I felt that having the comments made me think more ‘modularly’ (if that’s a word) and write better code.

Key takeaway

Comments may not be sexy like a Ferrari but they are necessary and I feel can help you write better code. Anyway who can afford a Ferrari anyway?!?

Please comment below!

Karlwebdev

Techdegree journal – entry 1 “How Many Div’s does it take till you get to the center honey?

Reading time: 3 mins

fry div

Introduction

As some of you may not know I’m taking the wonderful TeamTreehouse’s techdegree – which is an online course designed to give you the skills and develop the portfolio that will give you a new career in Front End Web development in 6-9 months. I have been with TeamTreehouse since July 2015 and doing it in my spare time. To use a metaphor, I liken my programming experience to a romantic relationship –  I felt like I was ‘dating’ coding – I was fooling around with it, taking each day as it comes but I still had my main squeeze which was my ‘teaching’ career. But taking the Techdegree was like putting the shiny rock on coding’s finger and saying “Front End Web Design – will you marry me?” I was ready to up my commitment and I go on to the new chapter on my life!

Summary

I am currently going over again “How To Make a Website” taught by the wonderful Nick Pettit and here’s a super quick summary of what I went over today…

  • I learnt why ‘Normalize.css’ was important as it makes browsers render all elements more consistently and in line with modern standards. 
  • I learnt the “wrapper div” technique – Many websites use a “wrapper div” to center the page in the middle of the site and contain the layout to a specific width. I learnt how to use auto margins and the max-width property to center our page and contain it.
  • I also learnt how important it was to design sites with the ‘mobile-first’ philosophy. Nowadays more people access the Internet via mobile and portable devices than by desktops. When designing websites it’s best to start with a mobile layout and then scale up rather than the other way around.

Thoughts

Although I did this video course 10 months ago, because as part of the Techdegree there was a graded assignment that I had to hand in based on this course, I swallowed my pride decided to go through it all over again. But honestly I was amazed at 2 things that I had discovered when I returned to the video course:

  1. How much I had learnt in 10 months. When I first started this video course I had never typed a word of code before in my life. It was almost like Nick was talking another language. I was as baffled as the poor shopkeeper that I was desperately trying to speak Portuguese to when I went on holiday last year. But now I had a greater grasp of what he was talking about and it was thrilling!
  2. How much I had forgotten. Although it is a very basic course, there was so much advanced techniques in that video, I was scrambling to get my notebook out. It taught me that if I do not practice what I am learning, the knowledge will be like that Bob Dylan song ‘blowing in the wind’.

The most important lesson that I learnt was not to be afraid to go over material that I had thought I had learnt. Sometimes going back is the very thing that will help you go forward! (Tweet that!)

Let me know your thoughts! Leave comments below or tweet at me!

Karlwebdev