Skip to main content

Function Basics

We define a function using the function keyword followed by function name and parentheses.

The basic syntax is:

function functionName(parameter-list)

Parameter-Passing Basics

Function parameters are the variables present in the function definition. Function arguments are the real values passed at the function call.

function printName(firstName, lastName) {
console.log("My name is " + firstName + " " + lastName);
printName("John", "Samuel");

return Statements

If the function want to exit and return a value as well, return statement is used.

function sum(a, b) {
return a + b;
console.log(sum(2, 3));

Function will return undefine by default unless an explicit value is returned.

function sum(a, b) {
a + b;
console.log(sum(2, 3));

Mask Out

Use of same variable for local and global variables creates a confusing situation, termed as mask out.

var x = "Global"; // Global variable
function testFn() {
var x = "Local"; // Local variable
console.log("Inside the function: " + x);
console.log("Before the function call: " + x);
console.log("After the function call: " + x);

When both global and local variables have same identifier, the local variables have more importance than the global variable. So, it's better to avoid such confusions.