Hello folks! I am here with another JavaScript post covering my learning and javascript fundamentals. Continuing my journey with freeCodeCamp, this time I have learned about functions in JavaScript. The previous post in the series can be found here.
Now, let's start with functions.
Functions
We can define functions in JavaScript using the keyword function
, followed by the function name.
Functions are used to divide the code into reusable parts.
Let's see an example now
function myFunction() {
console.log("This is inside a function!");
}
We have named our function as myFunction
. The body of function starts with the opening curly bracket and ends with the closing curly bracket.
Note: There is no semicolon after the closing curly bracket.
We have also used the console.log()
statement within the function's body. We have not encountered this method yet. We'll be knowing about it in future posts, but to give you an idea, this method logs out whatever we pass to it within parentheses.
There is a console in all the browsers which can be accessed using the key combination of Ctrl + Shift + I
. This will open a console session, where you could write JavaScript code and the output of it would be provided to you immediately.
Note:- The key combination may differ in other browsers. It does work in Google Chrome and Mozilla Firefox.
Calling a function is as simple as writing the following statement
myFunction();
This would print the line "This is inside a function!"
onto the console.
Parameters and Arguments
A lot of times, a function takes a number of inputs to it which are known as parameters, and values for those inputs can be passed at the time of function calling which are known as arguments. Let's say we have a function
function functionWithArgs(a, b) {
console.log(a - b);
}
functionWithArgs(10, 5);
Here a
and b
are the parameters which act as placeholders for the values to be passed as arguments. These can be used within the function. The values 10
and 5
, which we have passed at the time of function calling are known as arguments.
In the above function, the value will be passed as defined i.e. sequentially. The value of a
would be 10
and the value of b
would be 5
.
Scopes in function
Scope in JavaScript refers to the visibility of a variable within a JavaScript code. There are two types of scopes in general
Global Scope
The variable defined outside of a function has a global scope i.e. it can be used everywhere in the JavaScript code.
Any variable defined without the
var
keyword, will be treated as global irrespective of where it is defined. This may lead to unwanted results. Therefore we should always use the keyword to define any variable.
Local Scope
A variable defined within the function body and the parameters defined in the function definition both have a local scope which means they are only visible within its body. Trying to access them in the global scope would generate a ReferenceError
.
Let's see an example
function myTest() {
var loc = "foo";
console.log(loc);
}
myTest(); // logs "foo"
console.log(loc); // loc is not defined
As you may notice, using console.log(loc)
would raise the error as it is not visible(accessible) outside of the function.
ReferenceError: loc is not defined
Global Scope vs Local Scope
There can be cases, where a variable is declared in the global scope i.e. outside of any function and another variable with the same name is defined within the function i.e. inside a local scope.
In such cases, the local scope takes precedence over the global scope. Let see an example
var someVar = "Hat";
function myFun() {
var someVar = "Head";
console.log(someVar);
}
myFun(); // prints "Head"
console.log(someVar); // prints "Hat
You can notice, that calling the function prints the variable defined within it i.e. the one in the local scope.
Returning from a function
At times, a function does some processing and returns a value. Returning a value means that a function can send a value whenever called. Later, that value can be stored or used directly.
A function returns the value using the return
keyword.
When a function reaches the
return
statement, the execution of the current function stops and control goes to the calling location.
Let's see an example
function add(num1, num2){
return num1 + num2;
console.log("It will never be executed!")
}
var result = add(2, 3);
console.log(result); // prints 5
The variable result
stores the value returned by the function add()
and later can be used to print. Also, the console.log
statement within the function body won't be executed because it comes after the return statement.
It can also be used without explicitly using a variable as
console.log(add(2, 3)); // prints 5
Here console.log
uses the value returned by add(2, 3)
directly.
When a function doesn't return anything using the return
keyword, the default value returned by it is undefined
. For e.g.
function mul(num1, num2) {
sum = num1 + num2;
}
console.log(mul(2, 3)); // prints undefined
Albeit the sum
has been modified but the function does not return anything. Therefore it prints out undefined
.
Conclusion
With the end of this post, we have acquired some knowledge about functions and how to use them. Functions play an important role in any programming language as they help you to make reusable code and simplify the logic significantly.
References
Let's meet next time with some other JavaScript basics. Till then be curious and keep learning. :)
Top comments (0)