4. JS Functions Público

4. JS Functions

Kostas Diakogiannis
Curso por Kostas Diakogiannis, actualizado hace más de 1 año Colaboradores

Descripción

JavaScript functions introduction

Información de los módulos

Sin etiquetas

Elemento multimedia

Contexto

JavaScript functions Up to now, we write code in our script in such a way that will be executed or run once. Even with the construction of a loop, we define a loop, that runs multiple times but we can't execute this code:  1. Whenever we want 2. More than once It seems that functions give us the opportunity to GROUP our code into  a specific block and give a name to this block. Then any time we want this block of code to be executed and run we can just simply call it by it's own name. If we call this block more than once, it will run more than once. Thus we keep code, organized, grouped by the task it performs, separately from other code, cleaner and reusable. Let's take a look at how.
Mostrar menos
Sin etiquetas

Contexto

Functions' syntax  We can define a function by using the function keyword followed by the unique name of the function and parentheses (we will talk later about them). Then as usual follows the body of the function.  There inside the body we can define variables and do JS things as like we were in the global execution context. Once the function declaration finishes, we can call and execute whatever lies inside the function's body by calling the function by it's name as shown above followed by parentheses.  The function summary anytime it is called, creates two variables named a and b with corresponding values 10 and 20 and prints the sum of them to console.
Mostrar menos
Sin etiquetas

Contexto

The return keyword and function scope Return is a reserved JS keyword that is used only by functions in order to expose a  result to the open world! What does this mean? Take a look at the function above. Normally you may expect that after line 5 you can console.log the a and b variables in order to see the values. If you do this though you will get an error. That is because these variables have been created inside the function, thus they are available ONLY inside the function's body! This is happening due to var keyword, and it's scope (range of usage and access). Var keyword it's what we call function scope, that means lives inside the function that it was born, and it will die there.  Ok. But then what if we want to have access to the result of these variables outside the function? Then the return keyword comes to the rescue! Return is what this function returns (or gives back). In other words the result of the function. We can have access to this result by assigning the function's invocation (we call it the function) into a variable. Attention: That doesn't mean that the other lines of code inside the function will not be executed. Everything will be executed normally from top to bottom as always, anytime the function is invoked (called). Whatever we put in the return we can access it and assign it to a variable outside the function though. On the example above, in line 7 we store the number 30 (a + b) to the resultSummary variable. Then the resultSummary is equal to WHATEVER the summary function returns!!! Last but not least, once the return keyword is reached inside the function, the function exits immediately and returns the value that follows the keyword. In other words if we write some code after a return keyword, this code will never be executed.  Every function can have only one return keyword on the same block.
Mostrar menos
Sin etiquetas

Elemento multimedia

Contexto

JS Functions Arguments Arguments are local variables that are defined inside parentheses after function declaration and are accessed only inside the body of the function. No outer scope has access to arguments unless the value of these arguments is returned from the function. They are extremely powerful and useful feature as they allow us to parameterize the result of the function. The basic functionality remains the same but the result can alter based on the values we have passed to the arguments any time we call (invoke) the function. Thus, functions can be really a re-usable piece of code, that we define only once, but we can call and execute the same functionality, with different results. The example above defines a function that accepts two arguments. The functionality is the same, it adds these arguments and returns the sum of them.  Calling the function by passing 10 and 15 as arguments returns 25, second time same function, different arguments returns 45.
Mostrar menos
Sin etiquetas

Elemento multimedia

Contexto

F-1 Return type function Write a function  that accepts a single argument and returns it's type. Store this result that comes from the function into a variable and print the type to the console.
Mostrar menos
Sin etiquetas

Elemento multimedia

Contexto

F-2 Refactor FizzBuzz Refactor the fizzBuzz solution you created the other day by making this more re-usable.  It's not mandatory to start from 1 and end to 100. These numbers should be defined anytime we call the function. Estimated time: 15 mins.
Mostrar menos
Sin etiquetas

Elemento multimedia

Contexto

F-3 Assign Grade Write a function that accepts a number from 1 to 100 as a result of a test you gave to your students. If the result is lower than 50 then print Not Pass! Try again next time. If it is between 50-60 print the grade D. If it is between 61-80 print the grade C If it is between 81-90 print the grade B If it is between 91-98 print the grade A If it is 99 print 'Almost perfect' If it is 100 'Take a day-off tomorrow' Put different values and call the function multiple times to check your result.
Mostrar menos
Sin etiquetas

Elemento multimedia

Contexto

F-4 Calculate saved money till pension Write a function that accepts several parameters and calculates the number of money that will have been saved as pension until a person retires. Especially the parameters that should be defined are: The current age of the person // ex. 40 The pension's age of the person // ex. 60 The monthly wage the person earns // ex. 1000 The percentage (as integer)  that the person saves each month // ex. 10%   If the person has already retired then the message 'Calculate your past memories mate!' should be printed. If not, then the program should calculate how many years remain until the person retires, the monthly income and take a specific percent of this income every month as saved money. Example: A lady is 40 years old, she retires at 65, she earns 2000$ per month and she saves the 5% of it. How much money will she have saved until she retires? // This case is 30.000
Mostrar menos
Sin etiquetas

Elemento multimedia

Contexto

Function scope, var, let and const We have spoken a bit regarding scope when we were explaining the var keyword alongside with a return function statement. In JavaScript, not all values and variable are accessible from everywhere. Some of them they are only accessible inside the function that were defined. Other variables are accessible only inside the block scope they were defined (inside a loop's body etc). That means, that each variable's scope can vary, depending on how and where it was initially declared.  In JS there are 4 ways to create and define a new variable.  1. Without a keyword! For example: a = 20; That means that a new variable will be created with the value of 20. If you create a variable like that ( you shouldn't but that's another story), the a variable is accessible from EVERYWHERE in your script regardless of where has been declared. That is because the a variable's scope is the GLOBAL SCOPE! 2. By using the var keyword: For example: var a  = 20; That means that the a variable is accessible inside the whole function it was created. Var keyword's scope is the function scope. Take notice: If a was created on the global execution context then a variable is global (since the whole script is the function that wraps it!) 3. By using the let keyword: For example let a = 20; That means that a  is accessible only inside the block of code (the curly braces) that was created. For example if you have declared the let a = 20; inside an if statement, then you have access to a variable's value only inside this if block! This is called block scope. 4.  By using the const keyword: const a  = 20; Exactly like let, block scope, but re-assignment of a new value is NOT allowed. A is a const, that means it's value is subject to no changes.   If you want to learn more about scope, var, let, const and a procedure that is called hoisting, you can do so here
Mostrar menos
Sin etiquetas

Elemento multimedia

Contexto

F-5 Return the square of every number. Write a function that accepts any number and returns it's square value.  Don't forget to validate always before that the accepted input of the function is always number. If not print an appropriate message to the console to inform the user that this action is not possible and prevent further code from running.
Mostrar menos
Sin etiquetas

Elemento multimedia

Contexto

F-6 The factorial function Write a function that accepts a single number as parameter and returns it's factorial number. Factorial number is the product of all multiplications from number to 1 to the number itself. For example. Factorial of 5 = 1 * 2 * 3 * 4 * 5 = 120 factorial of 4 = 1 * 2 * 3 * 4 = 24 etc.
Mostrar menos
Sin etiquetas

Contexto

Recursion Recursion is a programming method we use in functional programming for imitating the functionality of a loop without having to define a loop. Instead we call the same function with different arguments from inside the function nearly before last line. Thus we execute the function again any time we are about to finish it.  In order to exit this recursive 'loop' we normally specify a condition that prevents code from further execution and from the function to call itself again.  Take a look at the code above and how the factorial function has been implemented again, this time recursively.  The function still accepts a number as before, but instead of looping from 1 to this number, we calculate the result (line 9) and then call the same function, this time with the number decreased by one. We do the same thing again and again until the number is 1. Then the if statement is executed and we return the result itself  (remember return, also exits the function).
Mostrar menos
Sin etiquetas

Contexto

F-7 Recursive functions practice Rewrite the container problem without using a loop. Only by using recursion.
Mostrar menos
Sin etiquetas

Elemento multimedia

Contexto

F-8 Money until rest of the week calculator Write a function that calculates how much money someone is going to earn until the end of the week by just accepting a number from 1 to 7 that represents the days of the week. (1 is for Monday, 2 for Tuesday, etc 7 is for Sunday). Given someone earns 10$ per hour and his working schedule is this: Monday: works 4 hours Tuesday:  works 6 hours Wednesday:  works 8 hours Thursday: works 10 hours  Saturday: works 2 hours Fridays and Sundays  can have his days-off.   For example: if we execute calculateRestOfWeekMoney(3) The number 3 is passed as argument indicates that today is Wednesday so we calculate from Wednesday (included) until sunday. With calculateRestOfWeekMoney(4) we start counting from thursday until sunday etc.   Rules: Write this in a re-usable way and without using a loop (recursive style maybe!). Estimated time: 30 mins.
Mostrar menos
Sin etiquetas

Elemento multimedia

Contexto

IIFE's and Function expressions The way have seen for declaring functions is not the only one JS provides. The method we have used so far was global function declarations, but functions can also be declared as expressions. That means we can store a function into a variable as any other JS data type.  Be careful! We don't store the result or what the function returns! We have already done this multiple times. We store the body of the function, the whole functionality in other words. As you can see in line 1 we have defined a function expression. A function stored in a variable that is called greetingsJs. Now this variable holds this function as value. Thus we can call this function by the name of it's variable. The main difference is that a function that has been instantiated as function expression can be called ONLY  after it has been defined (same as other languages like python). If you define a function with the way we have been doing so far you can use it also before. This is possible due to a JS procedure that is called hoisting. Hoisting is beyond the scope of this tutorial but if you want to learn more, read here. Another way of defining JS functions you can see it on line 5. What is this weird syntax? This is an immediately invoked function expression. That means, this function will be executed exactly after it is defined! Not only that but it will run only once! So it can't be called further afterwards.
Mostrar menos
Sin etiquetas

Elemento multimedia

Contexto

F-9 Return the x number to the power of y Write a function that accepts two numbers and validate that their type is number for sure.  After that the function should print to the console the all the exponential values between 1 and y.  For example if we have function(3, 5) The function should print 3, 9, 27, 81, 243. Another example (2, 8) The function prints 2, 4, 8, 16, 32, 64, 128, 256. Create another function that accepts again two numbers but in this case it prints all the exponential values (y) for every x number from 1 to x.   Example: example(5, 4) Will for numbers from 1 to 5 all the exponential to the power of 4. ex. 1**1 1**2 1**3 1**4 2**1 2**2 2**3 2**4 3**1 3**2 3**3 3**4 4**1 4**2 4**3 4**4 5**1 5**2 5**3 5**4
Mostrar menos
Mostrar resumen completo Ocultar resumen completo