TIL/2020–12–16
Today is my fourth day learning with Treehouse’s Full Stack JavaScript Techdegree. I initially learned quite a lot about functions and how it works through my momentum chrome clone coding (https://renzoregio.github.io/momentum-clone/). But its been awhile since I used JavaScript again (since I focused on Python and Django for about a month or two). So going through Treehouse’s Full Stack JavaScript Techdegree is a very good refresher since it also allows me to polish my JavaScript skills and also go into further detail into the syntax of JavaScript code. Apart from that, I picked up more skills and have more understanding about functions and how I can use it in different situations depending on the requirements — and also mixing conditionals, numbers and more in it. I also learned new things such as hoisting, the different ways we can run/execute functions (Function declaration/function expression/arrow functions) and more.
These are my notes for today:
Function — set of instructions you want to run over and over again
- Lets you group a specific set of statements or instructions to do a task
How to declare a function:
Function nameoffunction () {
}
To activate/execute/run the function, you have to call it:
nameoffunction();
It is common for programmers to place functions on top of a file
The code in the function doesn’t run immediately until you call it
You can call it as many times as you want
Returning a value from a function — return statement
- Similarly to what we do use python we use “return” in JavaScript
Without returning anything we will not get any data/information from the function — we will get undefined
Having undefined means that there is no return value specified — a function always returns a value, either what you return or if you don’t return anything then it will be undefined
But when we return randomNumber we are retrieving the information from the randomNumber Variable and we can call the function through various ways which makes the function more flexible and efficient.
A function can also be saved in a variable
— —
When we call a function, JavaScript is instructed to go inside a function and go through each line until it is instructed to end or when there is a return statement
A function can have more than one return statement — using conditional statements (if-else)
Or to simplify we can do
!field.value rather than field.value === “”
Note: When a return statement runs, it causes the JavaScript engine to exit the function. SO this means that the return statement should be the last line.
Return can only return one value — a string, variable, number etc.
— -
JavaScript functions can also accept information called arguments which we add to the function
To have a function accept an argument — we add a parameter
function nameoffunction (parameter) {
}
A function parameter represents a value that we give to the function via argument — and in this case the parameter drink is supplied with the string you put or whatever value you place
Pass information to the function = pass an argument to the function
Parameter = function functionname (paremeter){}
Arguments = genRandomNumber(argument) — information you pass to the parameter
Passing multiple arguments to a function:
Variable Scope
JavaScript provides separate scopes for each function — each function acts as its own universe.
The variables created in the function are only in that function — they dont interact with other functions
In this example, see that we have two variables called “person” one is outside of the function greeting and one is inside the greeting function. Yet even if we assigned values to each “person” variable, it does not get overwritten. Because the variable person inside the function is within the scope of the function.
When we create a variable inside a function, we can only use that variable inside that function.
Functions do not have access to each other’s scopes.
In the example, we cannot change “miguel” from outside of the function but only inside. It is only acting in its own universe.
The scope is a way JavaScript protects variables from overwriting each other
Global Scope: outside of the functions — any variable you create outside of a function is inside a global scope
Function Scope: inside of the function
Note: if you remove let, the variable “person” inside the function will override the “person” variable in the global scope. That is why it is good to use const whenever dealing with variables in the global scope.
— -
Function Declarations vs. Function Expressions
Function Declaration:
- What we’ve been doing ever since
- Function nameoffunction () { }
Function Expressions: Lets you assign a function to a variable
A function without a name after the function keyword is called an anonymous function
Here we are basically storing a function in a variable name called getRandomNumber
Because it is a const — it is now a statement so you have to add a ; as part of the JS syntax
Difference:
HOISTING
With function declarations you can call it even before the function — this is because the javascript engine loads the function declarations first and moves it to the top. This is why we can call a function declaration even before the function is declared on the file.
NO HOISTING
Function expressions are not hoisted. It is read from top to bottom like variables — it is only read when the js engine reaches the line the code is on.
— —
Arrow Functions / Arrow Function Expressions
- Similar to function expressions
- Const variablename = (x) => { }
Function Declaration
Function Expression
Arrow Function
Arrow functions with one parameter:
- No need for ()
- Const area = x => {}
Arrow functions with more than one parameter:
- Needs ()
- When dealing with more than one parameter it is required the have the parameters inside ().
Arrow functions with one line statements:
- Implicit return: no need to add the return keyword anymore as it automatically returns the values inside one line statements
- Const area = x => { x * x };
- Or you don’t even need the curly braces anymore
- Const area = x => x * x;
- Const area = (x, y) => x * y;
Single line functions with no parameters ():
- Required to have ()
- Const name = “renzo”;
- Const greeting = () => alert(`Hello, ${name}!`);
— -
Default function parameters
The default parameter saves your program from breaking or returning undefined if there is no argument when the function is called
To prevent this from happening we can set a default parameter to the function in case there is no argument returned when calling the function
So whenever there is no argument given to the parameter:
The default “Student” is what is returned rather than undefined.
Now when I add an argument, it takes on the argument given.
Let’s add greeting!
But how can we skip the greeting parameter and just change the student parameter? So that we can always use the greeting parameter.
We can give the argument undefined. This instructs the JS engine to make us of the default parameter set.
— —
Descriptive comments for functions — JSDoc
/**
* [A short description of the myFunc function]
*
* @param {[param type]} param1 — [parameter description]
* @param {[param type]} param2 — [parameter description]
* @returns {[return type]} [documents the function’s return value]
*/
function myFunc( param1, param2 ) {
// function returns a value…
}
Example by Treehouse:
/**
* Calculates and returns the area of a rectangle.(Short description of the function)
*
* @param {number} width — The width of the rectangle.
* @param {number} length — The length of the rectangle.
* @param {string} unit — The unit of measurement.
* @returns {string} The area of the rectangle and unit of measure.
*/
function getArea(width, length, unit) {
const area = width * length;
return `${area} ${unit}`;
}