DEV Community

Shatakshi Gupta
Shatakshi Gupta

Posted on • Edited on

Functions in JavaScript

If you have been into programming for a while then you must have come across functions. So there might be a little possibility that you would be very well aware about functions. But i would like to share the knowledge that I have of Functions. So here it goes hear me out-

Well if you ask me about functions then I would say that functions is one of my favorite topics in programming because they not only help us in writing clean, and efficient
code but also because Functions are a piece of code that enable us to call that block of code anywhere in the program thus refraining to not write that block of code again in the same program.
If you did not understand what functions are then you just need to have some patience and keep reading.

Have Faith

Declaration of functions in JavaScript

Functions without any argument
The functions that do not accept any argument are functions without arguments.

function learnJS() {
    console.log("Attention reader! You need to learn JavaScript now!");
}

//calling learnJS function
learnJS();
Enter fullscreen mode Exit fullscreen mode

The above code gives output

Attention reader! You need to learn JavaScript now!
Enter fullscreen mode Exit fullscreen mode

Functions with argument
The functions in which we pass on some value that would be accepted by some parameter that is present in function declaration. See below for better context

function square(x) {
    let sq = x * x;
    console.log(sq);
}

//calling function
square(4); 
Enter fullscreen mode Exit fullscreen mode

Difference between Arguments and Parameters
Argument - These are the values that we pass while calling the function and these act as the actual value that the variable would contain that we have declared while declaring or defining the functions.

Parameter - These are the variables that are use to store values that we have passed as argument while calling the function. These variables are declared while declaring the function.
Args vs params

  1. What if a function accepts an argument but we do not pass an argument? To understand that go through below example
function sayHi(person) {
    console.log(`hi ${person}`);
}
//calling the function
sayHi();
Enter fullscreen mode Exit fullscreen mode

Output of above code would be

hi undefined
Enter fullscreen mode Exit fullscreen mode

In case of string argument.

Methods in JavaScript
Methods are same as functions in Javascript except that these are the type of function that are already defined and we can access those functions simply by calling them and passing the relevant argument if it is required to pass.
For instance refer the following example
array.push() is a predefined method/function which accepts an integer argument.

Multiple arguments in JavaScript Functions

function greet(firstname, lastname) {
    console.log(`Hello there! ${firstname} ${lastname}`);
}

//calling function
greet('Shatakshi', 'Gupta');
Enter fullscreen mode Exit fullscreen mode

Above code will produce the following output

Hello there! Shatakshi Gupta
Enter fullscreen mode Exit fullscreen mode
  • Order matters! Now if you call the above function in the following manner
greet('Gupta', 'Shatakshi');
Enter fullscreen mode Exit fullscreen mode

Then it would lead to following result

Hello there! Gupta Shatakshi
Enter fullscreen mode Exit fullscreen mode

And that simply implies that while dealing with multiple arguments order matters.

The Return Keyword

  • It is use to store/save value so that we can use it in future.

  • When return keyword is encountered, function execution stops and the value is returned and no next line is ever executed.
    Refer the following code

function add(a,b) {
    return a+b;
}
let total = add(5,6);
console.log(total);
Enter fullscreen mode Exit fullscreen mode

And that will print as 11!

Functions Scope

  • variables declared inside a function cannot be used outside a function.
function printValue(a) {
    a = a+1;
    console.log(a);
}

printValue(4);
console.log(a);
Enter fullscreen mode Exit fullscreen mode

This will give following output

5
VM1082:7 Uncaught ReferenceError: a is not defined
Enter fullscreen mode Exit fullscreen mode

Another example of variables that can not be used outside functions.

function printScore(value) {
    let totalScore = 0;
    totalScore += value; //short form of totalScore = totalScore + value
}

printScore();
console.log(totalScore);
Enter fullscreen mode Exit fullscreen mode

Now that would produce the exact same error like before because variables like 'let' and 'const' are block scoped hence can not be used outside except its own function.

Block Scoped Functions

  • variables inside loops like it if, for, or while loop cannot be accessed outside that block
let value = 8;
if (value > 5) {
    let  score = value;
    console.log(`my score is ${score}`);
    const yay = "im greater than 5";
}

console.log(yay);
Enter fullscreen mode Exit fullscreen mode

And the result of that is

my score is 8
VM1106:8 Uncaught ReferenceError: yay is not defined
    at <anonymous>:8:13
Enter fullscreen mode Exit fullscreen mode

if we declare our variables with var keyword, we can access that variable outside of that block because var is a globally scoped keyword while let and const are block scoped keywords.

Lexical Scoped Functions

  • function inside another function or nested functions
function lexicalScope() {
    const randomNums = [34, 78, 88, 25]
    function anotherFunc() {
        for (let nums of randomNums) {
            console.log(`Numbers in the array are: ${nums}`);
        }
    }
    anotherFunc();
}

lexicalScope();
Enter fullscreen mode Exit fullscreen mode

Which would give output as

Numbers in the array are: 34
Numbers in the array are: 78
Numbers in the array are: 88
Numbers in the array are: 25
Enter fullscreen mode Exit fullscreen mode

FUNCTION EXPRESSION

  • In this variables store functions
  • Functions act as value that are assigned to variables

  • Function expression without any argument

let JsIsAwesome = function() {
    console.log("JavaScript is awesome. Indeed!");
}

//calling the function 
JsIsAwesome();
Enter fullscreen mode Exit fullscreen mode

The output of above expression would be

JavaScript is awesome. Indeed!
Enter fullscreen mode Exit fullscreen mode
  • Function Expression with Argument
let add = function (x,y) {
 console.log(x+y);
}

//calling the function
add(5,6)
Enter fullscreen mode Exit fullscreen mode

The output of above expression would be

11
Enter fullscreen mode Exit fullscreen mode

FUNCTION STATEMENT / FUNCTION DECLARATION

function sayHi() {
 console.log("hello there!");
}
Enter fullscreen mode Exit fullscreen mode

ANONYMOUS FUNCTIONS

  • These are the functions used in function expressions.
  • These basically have no name. Anonymous funcs

FIRST CLASS FUNCTIONS
The ability to use functions as values, pass functions as arguments & return function as a value are known as first class
functions.

HIGHER ORDER FUNCTIONS

  • The functions in which we can pass function as argument
function basicJavascript(func) {
 func();
 console.log("But first I should clear my basics of JavaScript");
}

function learnJavascript() {
 console.log("I need to learn JavaScript");
}

basicJavascript(learnJavascript);
Enter fullscreen mode Exit fullscreen mode

OUTPUT

I need to learn JavaScript
But first I should clear my basics of JavaScript
Enter fullscreen mode Exit fullscreen mode
  • The ones in which we can return function as value
function func() {
    let random = Math.random();
        if (random < 0.5) {
        return function() {
        console.log("thats too low!");
        }
    } else {
        return function() {
        console.log("thats too high!");
        }
    }
}
func();
Enter fullscreen mode Exit fullscreen mode

ARROW FUNCTIONS

  • These are type of functions that are syntactically alternative to a regular function expression
  • In this we remove function keyword and use an arrow to show that there is an function ahead
const add = (x, y) => {
 return x + y;
} 
Enter fullscreen mode Exit fullscreen mode

now how would you call this function in the following way

add(1,7)
Enter fullscreen mode Exit fullscreen mode

that would print out to be 8!

Arrow functions with no arguments

const print = () => {
 console.log("This function says me to only print");
}

// calling above function
print();
Enter fullscreen mode Exit fullscreen mode

OUTPUT:
This function says me to only print

Arrow functions implicit return
if you have a single statement inside arrow functions that needs to be evaluated like printing or a simple calculation then u can do that in the following way:

let add = (x, y) => x+y
Enter fullscreen mode Exit fullscreen mode

now above statement is the same as you just wrote the one with curly braces!

CALLBACK FUNCTIONS

  • Function that is passed into another function or the function that is passed as an argument to another is called a callback function.

  • These are the type of functions that execute only when a certain function or statement has finished executing.
    Refer below code

console.log("Hellooo..");

setTimeout(() => {
    console.log("well this got printed after 5sec and that is an example of CallBack concept!");
}, 5000);

console.log("Do you know CallBacks help us play with the async nature of js?");
Enter fullscreen mode Exit fullscreen mode

And that gives us the output

Hellooo..
Do you know CallBack helps us play with the async nature of js?
undefined
well this got printed after 5sec and that follows CallBack concept!
Enter fullscreen mode Exit fullscreen mode

CONCLUSION
Okay so that was a lot to grasp. But no worries you can go through this article whenever you feel like referring. If you have come this far then Congrats 🎉 you just learned some really important topics in JavaScript.
I'm so proud of you and wish you nothing but the best in your life as you keep learning and growing.
congrats

Thanks for reading and hope you have great day! :)
You can connect with me on Twitter

Top comments (3)

Collapse
 
pierrewahlberg profile image
Pierre Vahlberg

This was a good read overall, my only feedback would be that the part about methods being a little off. First out is that Array.push() is a prototype method that does not only accept integers, but any value (almost).

My understanding is that methods belong to an object - which all things in JS are but i refer to the commonly known object x = {}

That brings the prototype into play but also the methods/functions execution scope - the "this" keyword, which is only ever present in methods.

Also the term Closure is widely used in articles and could be mentioned here

Everything else you wrote was very good! I hope you appreciate me writing this in hope you wish to improve 🙏

Collapse
 
shatakshig8 profile image
Shatakshi Gupta

Hi Pierre! This article is more beginner intended to explain complex topics through example so that beginners can understand it well. Also, Thanks for providing your feedback. :)

Collapse
 
shatakshig8 profile image
Shatakshi Gupta

yes, absolutely. I'd definitely like to connect with you. And thanks a ton for your feedback! :)