Function in JavaScript

Function in JavaScript

A function is the main building block of the JavaScript program. We can call the function many times without any repetition of code. Functions are designed to perform a particular task.

Advantage

  • Code reusability
  • Less code
  • Easy to readable

Syntax

code.png

Explanation

Function Declaration

Screenshot 2021-08-26 112743.png

  • Function declaration starts with a function keyword
  • Then, goes the name of the function
  • Then, the parameter of the function between two paranthese, separated by a comma.
  • Then, we can write code between two curly braces called the function body
  • And now call the function with their function name.

Hoisting in function

When we declare a variable inside a function, that variable is only visible inside the local scope.

code.png

If we try to access outside of the function, it throws an error message into the console.

code.png

If a variable declares in global scope then, we can access that variable inside any function body.

code.png

We can update the global variables from the function body with var and let keywords.

code.png

Thank you