Posts

Showing posts with the label JavaScript Function

Function Expressions in JavaScript

What are Function-Expressions? A Function-Expression is a function that is assigned to a variable or a property of an object. It can be named or anonymous. It is a function that is created at runtime and can be passed as an argument to another function. //example of a named Function-Expression let square = function ( num ) { return num * num ; } ; //example of an anonymous Function-Expression let add = function ( a , b ) { return a + b ; } ; How are Function-Expressions used? Function-Expressions are commonly used for following purposes: 1. To create and assign a function to a variable or property of an object. 2. To create a closure, i.e., functions within functions that can access the outer functions' variables. 3. To pass a function as an argument to another function. 4. To return a function from another function. //example of a Function-Expression used to create a closure function outerFunction ( x ) { function innerFunction ( y ) { re...

Functions in JavaScript

What is Function? Functions are an important concept in JavaScript, allowing you to wrap reusable blocks of code. They are a way to group together a set of statements to perform a specific task or return a value. They allow you to call that code whenever you need it, using a single command instead of typing out the same code multiple times. As a result your codebase become more organized, readable and maintainable. Function Declaration To define a named function in JavaScript, you use the 'function' keyword followed by the name of the function, a list of parameters enclosed in parentheses, and the JavaScript statements that define the function enclosed in curly brackets. This type of function can be called before the declaration in the code because JavaScript hoists function declarations to the top of their containing scope. Here is the basic syntax: // Function Declaration function functionName ( parameter1 , parameter2 , ... ) { // Function body // Code to be exe...