JavaScript Functions: Introduction

If you wanna execute a block of code with specific arguments and invoke these functions with the input of the provided argument then functions are the method you should go for in javascript.

It is simply a block of code designed to execute specific tasks within it with ease so that it can be used anywhere with just the correct input passing to the respective arguments. 

Syntax

function function_name(paramter)
{
return parameter * parameter  //Returns the multiples of parameter

} 

Example: Square A Number

So we are going to use a function keyword to create a function as you saw in the syntax, and we are going to make a name of our own and pass in the parameter to a square number.

function square(number)
{
    return number * number
}
console.log(square(2))

Output: 4

So here we can see that I used a parameter number, called the function with name square, and passed in the respective parameter to get the number I wanted.

Scope of javascript function

  • Generally, the scope is the meaning of visibility.
  • In javascript function scope works in some ways.
  • We have a global scope and local scope in function.

If a variable is declared before the function, it is a global variable.

var book = 'Harry Potter';

function bookName(){
    console.log(book)
}
bookName()

Output: Harry Potter

So here it is globally declared and was passed in the variable declared globally, and when being called the function name, it prints it.

So a variable that is declared inside the function block is local scope.

var book = 'Harry Potter';

function bookName(){
var book2 = 'Goosebumps'
    console.log(book)
}
bookName()

Output: Goosebumps

  • When they have the same name as the global variable, the local variable takes some precedence over the global variable and declares it.
  • But when we try to access the variable locally inside the function, it won't get access to print it, and it'll print the globally declared variable.

So these are some of the constraints we will face in javascript functions, and we will continue to see some other operations of functions in a separate article.

Mon, 10/18/2021 - 09:28

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.
Tags