Functions in JavaScript

dheeraj korangadheeraj koranga
4 min read

A function in JavaScript is a block of code designed to perform a particular task. It is executed when it is called (or invoked). Functions allow code reuse and can take arguments and return values.

function greet() {
    console.log("Hello, World!");
}
// calling function
greet();  // Output: "Hello, World!"

Functions with Arguments

Arguments are values you pass to a function when invoking it. They allow you to make the function more flexible and dynamic.

Example with Arguments:

function greet(name) {
    console.log("Hello, " + name);
}
greet("Alice");  // Output: "Hello, Alice"
  • name is the argument that the function greet accepts.

  • When calling greet("Alice"), the value "Alice" is passed to the name argument.

return Keyword in Functions

The return statement stops the function execution and returns a value to the calling code. If a function doesn’t explicitly return a value, it returns undefined by default.

Example with return:

function add(a, b) {
    return a + b;
}
let result = add(5, 3);
console.log(result);  // Output: 8

What is Scope?

Scope in JavaScript determines the accessibility (visibility) of variables. There are different types of scope in JavaScript:

  1. Global Scope: Variables declared outside of any function or block are available everywhere in the code.

  2. Function Scope: Variables declared within a function are accessible only within that function.

  3. Block Scope: Variables declared with let and const inside a block {} are only accessible within that block (if, loops, etc.).

  4. Lexical Scope: Functions have access to variables declared in their parent scopes due to closures.|

Example of Global, Function, and Block Scope:


let globalVar = "I'm global";  // Global Scope

function myFunction() {
    let funcVar = "I'm inside the function";  // Function Scope

    if (true) {
        let blockVar = "I'm inside a block";  // Block Scope
        console.log(blockVar);  // Output: "I'm inside a block"
    }
    // console.log(blockVar);  // Error: blockVar is not defined
}
console.log(globalVar);  // Output: "I'm global"
myFunction();

Lexical Scope:

Lexical scope allows inner functions to access variables of outer functions.

function outerFunction() {
    let outerVar = "Outer";

    function innerFunction() {
        console.log(outerVar);  // Output: "Outer"
    }

    innerFunction();
}
outerFunction();

Function Expressions or Nameless (Anonymous) Functions

A function expression defines a function and assigns it to a variable. These functions can be anonymous (without a name).

Example of Function Expression:

let add = function(a,b){
    return a+b;
}
console.log(add(50,20));  // output is 70

Higher-Order Function (HOF)

A higher-order function is a function that can take other functions as arguments, or return functions as its result. HOFs are fundamental in JavaScript and are used for tasks such as iterating over arrays, event handling, and more.

Example of HOF (Function as Argument):

let sayHello = function() {
    console.log("Hello from a function expression!");
};
sayHello();  // Output: "Hello from a function expression!"

function greet(name) {
    return "Hello, " + name;
}

function greetPerson(fn, personName) {
    return fn(personName);  // Using the function passed as argument
}

console.log(greetPerson(greet, "Alice"));  // Output: "Hello, Alice"
  • In this example, greetPerson is a higher-order function because it takes a function (greet) as an argument.

HOF Returning Another Function

Higher-order functions can also return another function as the result.

Example of HOF Returning a Function:

function multiplier(factor) {
    return function(number) {
        return number * factor;  // Inner function
    };
}

let double = multiplier(2);
let triple = multiplier(3);

console.log(double(5));  // Output: 10
console.log(triple(5));  // Output: 15
  • In this example, the multiplier function returns another function that multiplies a given number by the factor provided.

**********************************************************************

PRACTICE QUESTION

Qs1. Write a JavaScript function that returns array elements larger than a

const arr=[45,23,56,12,58,95,6,10];

function greaterThan(arr,n){
    newarr=[];
    let j=0;
    for(let i=0;i<arr.length;i++){
        if(arr[i]>n){
            newarr[j++]=arr[i];
        }
    }
    return newarr;
}

console.log(greaterThan(arr,30));

Qs2. Write a JavaScript function to extract unique characters from a string. Example:
str = “abcdabcdefgggh”
ans = “abcdefgh”

let str = "abcdabcdefgggh"

let unique = function(str){
    newStr="";
    for(let i=0;i<str.length;i++){
        let currChar=str[i];
        if(newStr.indexOf(currChar)==-1){
            newStr+=currChar;
        }
    }
    return newStr;
}

console.log(unique(str));   // output : abcdefgh

Qs3. Write a JavaScript function that accepts a list of country names as input and returns the longest country name as output.
Example :
country = ["Australia", "Germany", "United States of America"]
output : "United States of America"

const country = ["Australia", "Germany", "United States of America"] ;

let longestCountryName = function(arr){
    let max=0;
    let c;
    for(let i=0;i<arr.length;i++){
        let len=arr[i].length;
        if(len>max){
            c=arr[i];
        }
    }
    return c;
}

console.log(longestCountryName(country)); 
// output : "United States of America"

Qs4. Write a JavaScript function to count the number of vowels in a String arguments.

let vowels = ["a", "e", "i", "o", "u"];
let str = "my name is mr narendra damodar das modi";

let vowelsCount = function (str, vowels) {
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (vowels.indexOf(str[i]) != -1) {
      count++;
    }
  }
  return count;
};

console.log(vowelsCount(str, vowels));
// output is 12

Qs5. Write a JavaScript function to generate a random number within a range

let start = 100;
let end = 200;
function generateRandom(start, end) {
    let diff = end - start;
    return Math.floor(Math.random() * diff) + start
}

console.log(generateRandom(start,end));
0
Subscribe to my newsletter

Read articles from dheeraj koranga directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

dheeraj koranga
dheeraj koranga