Functions in JavaScript

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we have discussed everything you need to know about javascript functions even the nitty gritty thinks that no one explains for example why do we need functions in the first place and the benefit of using functions etc and etc hi or welcome to the complete javascript bigness tutorial by coder fiction first of all let me ask you a favor if you find this video helpful please consider subscribing to this channel if you haven't yet and please like and share this video with your friends and colleagues functions are the one of the fundamental building blocks in javascript if you like javascript functions and the flexibility it offers i can guarantee you that you will end up loving the language javascript let's get started with following code snippet and let's find out why functions are also now suppose we have three variables a b and c now we are going to divide these numbers here first of all we will divide a with b so i will have this log statement here and let's do the operation here a divided by b now i'm gonna divide a with c so 8 divided by 2 which is 4. now let me copy this and pasting here here we are going to divide b with c so here we have the result after dividing 3 by 2. now you just realized from looking at these various outputs here we can really know what are these outputs here so i will just format these outputs here with string concatenation so i will be using the string templates like this a so here we have the string interpolation a divided by b gives this output here now you could really understand what is this output means now i will do the same for rest of these outputs here so i will just copy this and pasting here for rest of the operations so a divided by c which gives this output and then b divided by c gives this output now somehow you find out another problem that you might have when dividing a number with 0 for example let's assign this b with 0 then this output will be infinity if you want to prevent that from happening you have to check the denominator before the division operation so we will check that with this if statement here if b is equal to 0 and we will just print this denominator is 0 so division is not possible else we will do the division operation see so this is what we are doing here now you might have this problem for other division operations also so i will just copy this if else statement from here and pasting for other operations and changing these variables accordingly now if you pass 0 as a denominator for any of these division operations then it will print this message denominator is 0 so division is not possible now here we have done the same division operation with multiple variables separately like this and thereby we are repeating the same steps at different places of this program repetition of code is not at all a good idea because of various reasons for example if you want to change the steps involved in this operation you have to make the change at different places suppose you want to replace this zero number with zero word you have to do that separately in places where you repeated the same step or code it will become more frustrating than you can imagine when you have a big application in order to prevent this from happening we developers follow a principle called drive principle which is an abbreviation for don't repeat yourself i will show you how javascript functions solve this problem and what are the other benefits of using javascript functions now i will just copy these code snippets from here and let's copy that into another file so that we can refer that after replacing these codes with functions so i will just paste the code into this file here now back to the previous javascript file first of all i will start with function definition function is a set of instructions to perform a particular task or an action and this is how the syntax for defining a function looks like first of all we have the keyword function followed by a function name and then a pair of parenthesis within that we can pass values or you could say parameters we will discuss them in a bit and then we have a code block inside that we can have multiple statements for the function now let's try to define a function here for this division operation so here we have the function keyword and then name of the function which is divide and for this function we can define variables like this number one and number two and these are called as parameters of a function through these variables we can pass values into this function and then here we have the curly brace within that we can provide the statements of this function so everything in between these curly brace is called as body of this function now let me complete this function for dividing two numbers num1 and num2 first therefore i will check whether the denominator is zero or not so num2 which is what we are expecting as a denominator for this division operation so if num2 is equal to 0 then we will print this message here else we will do the division operation for that i will copy paste this statement from here num1 divided by num2 and let's do the division here num1 divided by num2 there are other ways to define functions in javascript this way of defining a function is called function declaration or function statement from now onwards if you want to divide two numbers you can use this function divide here let me show you that here we will just call the function divide like this divide a comma b and then finally we will put a semicolon here see here we are dividing the number here with b same is accomplished with this function divide here so we don't need these codes here let me remove that so this is what we call calling a function or invoking a function sometimes it may also refer as running a function or executing a function so this is how we invoke a function first of all we have the function name and then a pair of parentheses like this within that we can pass the values for these variables so these are called as parameters of a function and the values that we pass into this function these a and b are called as arguments so these are arguments of the divide function and these are parameters of this function and these arguments are assigned to these parameters here in the same order meaning the first argument is assigned to the first parameter and the second argument is assigned to this second parameter here so that's how a function invocation works if you only define a function like this function declaration here it won't make any call the function will be only executed by javascript engine if you call the function or invoke the function like this now let me replace these codes here with the same function divide divide a with c let's call the same function for this division operation also d y b with c now we have defined the function up above now you can reuse this function as much as you want if you want to divide eight with four you could do this and here we have the output so here the function is defined once and reused multiple times now let's discuss why functions are super helpful for that first of all i will open these codes and the previous code side by side now here i have already opened this common practice file now let's open this copied code side by side for that just hold alt on your keyboard then click on this file here so here we have the code snippet with function and without function so the first reason why functions are super helpful is that they are defined once and they can be reused multiple times and thereby we could achieve more with less code as you can see here and also that proves my next point since we are not repeating codes with functions it is easy to modify a function suppose you want to end this message with a period or dot you just need to make the change here and then the same change will be reflected wherever you invoke the function if we were not using function we have to make the modifications at each repetitions here so if there is a change of procedure for doing this operation we only need to make the modification within this function definition here and the same modifications or updation will be reflected wherever we invoke the function so that is more convenient and it helps us to save times in future development now there is one more benefit of using functions suppose we have a variable full name and let's assign that here if you want to convert characters inside this string to uppercase you just need to call the function to uppercase if you want to change all of the characters inside the string to lower case we can just call this function to lowercase so here we have the output through those two functions to uppercase and lowercase here these two functions gives abstractions to what is happening behind the c so function gives abstraction which means we don't have to know what is happening behind the c what are the steps involved in these functions here we can just ignore the complexity of steps in both this function instead we can just think of what actually this function does in brief so once a function is defined we can invoke the function whenever it is necessary without thinking what is happening behind the c so hope you are convinced that functions are super helpful now let's talk about parameters here we already learned that values that we pass into a function is called as arguments and the variables that access those arguments are called as parameters here we have two parameters num1 and num2 these parameters can only be accessed within this function here and also if you look at the function syntax you can't see a semicolon at the end of this function if you look at the output dev console here we are not getting any error by putting a sme colon here but it's not recommended to put a semicolon at the end of a function declaration as a general rule of thumb it is recommended to end all statements in javascript with semicolon except block statements a block statement is something that group multiple statements with a pair of curly brackets like this see here we have a block statement it is not recommended to end the block statement with a semicolon same in case of this function also if you end a statement with a closing brace it's not recommended to follow that with a semicolon we have seen the same with if statements also it's not recommended to put a semicolon after this if statement same in case of switch statements also so as per the syntax it's not recommended to put a semicolon after a block statement or curly brace like this but there is an exception we will see that in a bit now let me get rid of these codes here i want to talk about default parameters for that i'll be defining a function function to calculate total price price per item and quantity to save the total price i will declare a variable total price for this calculation we just need to multiply price per item with quantity finally we will just print this total price like this total price is equal to just concavity variable total price here so here we have the function declaration a function declaration itself won't do anything or execute anything inside the program we have to invoke the function when necessary suppose we bought three notebooks which cost around 39 and 55 cents so we will call this function like this calculate total price now let's pass this total price per item three which is the quantity here so this function receives the first argument with this force parameter and this 3 will be accepted through this parameter quantity inside the function both of them are multiplied and the result is printed with this log statement here we can call this function whenever it is necessary suppose you bought a pen also which cost around five dollar then we call this function calculate total price like this price per item is five bucks and then the quantity will be one so here we have the output see here i just forgot to add a space before this total price here so i will just do the modification inside the function and the same changes will be reflected wherever we call the function now let's talk about default value of a parameter here these parameters values are passed from these function invocations here instead of that we can also provide the default value like this directly assigning the default value within the function declaration itself along with the parameter with this assignment operator so from now onwards if quantity of the item is 1 we don't have to pass the value here it will use this default value here if there is no default value assigned and we are not passing the value for the second parameter we will get the output as nan meaning we are not assigning a value to this parameter it's like an unassigned variable so all unassigned variables has the value undefined so when we multiply that with price per item we will get this output nan not a number if there is a default value we can avoid these situations also so that's how a default value of a parameter works now let's talk about function expression and anonymous function as per the function syntax itself you could see that we need to provide a function name after the keyword function so it is not allowed to define a function without a function name like this you could already see the red squiggly line here and inside this dev console you could see the error message here function statements requires a function name but it is possible to define functions without names when you assign that function to a variable like this let sum is equal to function so here we have the function without a function name so functions without a function name is called as anonymous functions in javascript you already know when we assign a value to a variable like this the right side of the assignment operator is always an expression so here in this case after this assignment operator we have a function so this function is in place of an expression here so this function is also called as function expression when a function is passed in place with javascript is expecting an expression then that function is called as function expression that's what we have here it is recommended to put a semicolon after function expressions when they end a statement like this statement here we are passing this function javascript expect an expression so this is a function expression so let me complete this function here this function is expected to have two parameters and inside this function we will just add these two parameters a and b so this function expression works exactly similar to this function declaration here with few differences we will get into that in a bit now to call this function we can make use of this variable here sum and let's call this function with a pair of parentheses like this here we have the first value 3 4 so 3 plus 4 which is 7. since we are assigning a function to a variable there is a chance of changing this variable to a different value like this we can assign this variable with some value 6 here now if you call this function again somewhere expecting sum is a function and you will get this error sum is not a function so normally when we assign a function expression to a variable like this instead of using lead variables we use constant variables and thereby it's not allowed to change the value of this sum variable and that's how most of the time we assign function expression to a variable using constant keywords when necessary you can also assign functions to let variables also when you want to change the function to a different function but most of the time function expressions are assigned to a constant variable to prevent the variable from changing its value so this is a function expression and this is a function declaration now let's check the differences so first of all function declarations are hosted we have already seen what is meant by hosting in this session where we discussed va led and cons keywords what i really meant by that we can access this function before defining the function if i cut these two function calls here and let's paste that about this function declaration it will still works you see here we have the same output as before so it is possible to invoke a function even before defining the function because function declarations are hosted like variables but it's not possible with function declaration let me move this function declaration up above even before defining the function i will get this error cannot access some before initialization so that's the main difference between function declaration and function expression function declarations are hoisted but not function expression we can only invoke this function after defining the function here in future sessions we will see some situations where function expressions are more appropriate than function declarations for now that's enough with the comparison between function declaration and function expression generally i prefer calling a function after defining the function so i will just move these function invocations after defining the function up above here now let me get rid of these here let's convert this function declaration to a function expression so i will do this we will convert this function name as a variable like this function so here we have the function expression and which is assigned to this variable here so industry of the code we can treat this variable as a function now let's talk about return statement in a function to show you how return statement works i'm gonna define one more function here you could see this output from the function calculate total price generally in amount we only expect two digits after the decimal point so i'm gonna define a function to do the format operation so i'll be using this function expression here format amount function for this function we only have one variable which is amount and here we have the function body we have already discussed this function to fixed under number functions i'll be using the same function for formatting this amount here so we could do this i'll just print the output here amount and let's call the function to fixed we only need two digits after decimal point so i will pass to here now let's call the function inside this function here format amount and let's pass total price here see here we have the output from this function called here instead of printing the formatted amount inside this function we need that amount for rest of the statements inside this function here so instead of logging that amount here we just need to return that like this we will use this keyword return so this function returns the amount back to this function here now instead of passing total price inside this concatenation operation we could pass the formatted amount for that we just need to call the function inside this log statement here see so return statement in a function allows us for further operations on the function output otherwise it will be lost after the function invocation so that's how a return statement works now if there is no return statement inside a function then that function invocation like this here will return the value undefined if you want to check that let's call that within a log statement and thereby we could see the value return the funding function calculate total price and let's pass some amount here see we have called this function within the function we have printed the amount 6 into 1 which is the default quantity here we have the output from this log statement here which is undefined so function without a return statement always returns undefined now there is one more thing i want to talk about suppose we have a function i will give a random name like abc and here we have the function inside the function we have this log statement so that i will just print this one and let me duplicate this few times here now let's call the function here a b c so this function called here we are printing one on each line now if i put a return keyword like this this function only executed this log statement here because early return statement in a function will ignore execution of following statements like this here we only have the keyword written and let's check what actually this function returns so i will just move this function call to this log statement so when we put a return statement without a value it actually returns undefined even if we return a value here the rest of the statements execution will be ignored we will get the return value from the function through this function call as you can see here so that's how return statement works now finally i want to show you the type of a function let's try type of operator on these functions here calculate total price so here we have the output function as an output for this type of operator all functions comes under the data type object all functions are object of a class function in javascript don't freak out if you don't know what is a class we will discuss that under object oriented programming in javascript so in terms of data type function comes under object data type so that's all about this session in next video we'll be discussing arrow functions in javascript so once again if you found this video helpful please consider subscribing to this channel code affection if you haven't yet please like and share this video with your friends and colleagues see you in next video
Info
Channel: CodAffection
Views: 1,263
Rating: undefined out of 5
Keywords: Functions in JavaScript, how to create a function, why do we need function in js, Function Declaration in JavaScript, How to invoke a js Function, Define a js Function, benefits of functions in js, Function Syntax, Parameters and Arguments in a js Function, Default Function Parameters, Function Expression, Function Expression Vs Function Declaration, Return Statement in JavaScript Function, Type Of JavaScript Function, CodAffection, JavaScript Beginners Tutorial
Id: WOmlERydNBk
Channel Id: undefined
Length: 25min 0sec (1500 seconds)
Published: Tue Sep 21 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.