Javascript Jumpstart - Functions
a.k.a Methods, we explore core concepts of functions.
What we'll cover
Exploring functions and their syntax
Differences between function declaration and function expression
Reusing parameter names and understanding their properties
In JavaScript, functions are blocks of reusable code that perform specific tasks or a set of related tasks. They promote code reusability, modularity, and maintainability. Functions have a name, parameters (or arguments), and a body containing the instructions or statements that define their behaviour.
When a function is called in JavaScript, control is transferred to that function, its statements are executed, and then control returns to the calling code. Functions can also return a value to the caller using the return
statement.
// let's see an example before we go further
function addNumbers(a, b) {
var sum = a + b;
return sum;
}
var result = addNumbers(5, 3);
console.log(result); // Output: 8
JavaScript functions can be called multiple times with different arguments, enabling code reuse. They can also be organized into modules or libraries, making them accessible to other parts of the program.
Now let's go in-depth...
Functions
In javascript,
functions
are first-class citizens.In JavaScript, the term "functions are first-class citizens" means that functions are treated as values and have the same capabilities as any other data type, such as numbers or strings. This concept enables functions to be assigned to variables, passed as arguments to other functions, returned as values from functions, and stored in data structures.
A function is an
object
. Remember, almost everything in javascript is an object.Functions can be assigned to variables and properties in objects.
We can pass functions as parameters/arguments in other functions.
We can return functions as values from other functions.
This behaviour of functions allows us to do Functional Programming in JavaScript.
*we might explore functional programming in another series.
When we create a function using
function declaration
we create a new variable in memory.// this is called a function declaration // it is one way of creating a function function myFn() {}
This will create a variable
myFn
which holdsfunction
as a value. Let's inspect this function in the developer console in the browser to get a look under the hood.The method
console. dir()
displays an interactive list of the properties of the specified JavaScript object.See below, we expanded the
[[Prototype]]
property of the functionmyFn
and we see, it containsf ()
and then within that, it containsObject
. So we verified that afunction
is an object.
In JavaScript,
[[Prototype]]
and__proto__
are both mechanisms used to establish the prototype chain, which is the mechanism for object inheritance.*there are differences between the two and we will explore the prototypal chain and related topics in depth when we see advanced concepts.name: "myFn"
is the name of the function.[[FunctionLocation]]
points to the location of the function.[[Scopes]]: Scopes[1]
describes the scope chain. This is related to the accessibility and visibility of variables and functions in the execution context. For now, it's enough to be aware of this without understanding it.A function is a set of reusable statements and expressions.
let a = 5; let b = 3; let c; c = a + b; console.log(c); // 8 a = 20; b = 10; c = a + b; console.log(c); // 30
We are repeating some lines of code in our script
// repeated code c = a + b; console.log(c);
This is a good candidate for us to turn into a function, let's create one
let a = 5; let b = 3; // function declaration function sum(a, b) { let c = a + b; console.log(c); } // invoking function with arguments sum(a, b); // 8 a = 10; b = 20; sum(a, b); // 30
Syntax of a function
Function Declaration
// this way of creatiing a function // syntax is called function declaration function myFn(a, b) { let c; a = a + 1; c = a + b; return c; }
Here, the
name
ismyFn
which is variable, (a, b) isparameters
, everything between{}
is calledfunction body
, thereturn
keyword is used to return the result of a function.After the closing curly brace, there is no
;
semi-colon. In JavaScript after a block of statements we don't need to add a semi-colon.If we add this function to the existing code, nothing will happen. To use the function we need to call the function
// myFn(10, 3) is calling the function // we wrap it in console.log() to see the output console.log(myFn(10, 3)); // 13
Calling the function will execute it
"a"
is assigned value 10 &"b"
is assigned value 3 ( parameters are assigned corresponding values of arguments )variable
"c"
is declaredvalue of
"a"
is incremented by 1the sum of the values "a" and "b" is assigned to "c"
value of "c" is returned
This completes the function call, the function stops after the return statement.
The parameters of the function are variables, we do not need to declare them with
var, let or const
, these variables are automatically declared and assigned at the time of each function call.Parameters, a return statement and arguments in a function call are optional.
// This is a valid function declaration function myFn() {} myFn(); // undefined myFn(10, true); // undefined
We can call a function with arguments even if there are no parameters, it will return undefined.
*this kind of behaviour is not good, using typescript we can avoid such issues.A function can be of the following types.
Reusing parameter names in code.
// global scope function myFn1(a, b) { /*function scope*/ } function myFn2(a, b) { /*function scope*/ } let a = 5; let b = 6;
We can reuse parameter names.
Parameters (a, b) are limited to that function only and hence can be reused in different functions.
Variables a, and b are declared in the global scope. These are valid declarations.
Function Declaration vs Function Expression
Function Declaration consists of function keyword, function name, parameters which are optional and function body.
Function Expression does not have a function name which means function expression is anonymous, it is an anonymous function expression.
// anonymous function expression function(a, b) { let c; a = a + 1; c = a + b; return c; }
Tabe to outline the usage of
function declaration vs function expression
The most common use case of Function Expression is being passed as an argument in a call to another function i.e. callback function.
Function expression
assigned to a variable.const myFn = function(a, b) { let c; a = a + 1; c = a + b; return c; } // invoking/calling the function myFn(5, 2); // 7
const
is mostly used to declare variables that hold a function as a value, to prevent reassignment of this variable.*we will revisit this in scopes laterIn case of a function expression passed as an argument in a call to another function we don't need to assign the anonymous function expression to any variable.
// setTimeout global scoped function like we discussed in Javascript Jumpstart - Types & Variables // accepts a callback function which is a anonymous function expression being passed to the setTimeout function. // this anonymous function expression is called a callback setTimeout(function() { console.log('Delayed Message') }, 1000);
This article explores all the core concepts we need to know to get a good handle on functions in javascript. Write and execute all different code snippets.
Next article, we will explore operators in-depth Javascript Jumpstart - Operators