0% found this document useful (0 votes)
10 views64 pages

More Examples O-WPS Office

The document provides various examples of if-else statements and loops in JavaScript, illustrating their usage for conditions and repetitive tasks. It covers different types of loops such as for, while, do...while, for...of, and for...in, along with control statements like break and continue. Additionally, it explains the syntax and functionality of these control structures, emphasizing their role in efficient coding.

Uploaded by

samuel asefa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views64 pages

More Examples O-WPS Office

The document provides various examples of if-else statements and loops in JavaScript, illustrating their usage for conditions and repetitive tasks. It covers different types of loops such as for, while, do...while, for...of, and for...in, along with control statements like break and continue. Additionally, it explains the syntax and functionality of these control structures, emphasizing their role in efficient coding.

Uploaded by

samuel asefa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 64

More Examples of JavaScript if-else Statements

Here are additional examples of if-else statements in JavaScript:

Example 1: Checking Even or Odd Number

let num = 7;

if (num % 2 === 0) {

console.log("The number is even.");

} else {

console.log("The number is odd.");

// Output: The number is odd.

Example 2: Checking Age for Voting Eligibility

let age = 17;

if (age >= 18) {

console.log("You are eligible to vote.");

} else {

console.log("You are not eligible to vote.");

// Output: You are not eligible to vote.

Example 3: Checking Temperature for Weather Advice

let temperature = 30;

if (temperature > 25) {

console.log("It's hot outside! Stay hydrated.");

} else {

console.log("The weather is pleasant.");

}
// Output: It's hot outside! Stay hydrated.

Example 4: Validating User Login

let username = "admin";

let password = "1234";

if (username === "admin"&& password === "1234") {

console.log("Login successful!");

} else {

console.log("Invalid credentials. Please try again.");

// Output: Login successful!

Nested if-else Statement Examples

Example 1: Grading System

let marks = 85;

if (marks >= 80) {

console.log("Grade: A");

if (marks >= 90) {

console.log("Excellent Performance!");

} else {

console.log("Great Job!");

} else {

if (marks >= 60) {

console.log("Grade: B");

} else {

console.log("Grade: C");
}

// Output: Grade: A Great Job!

Example 2: Checking Weather Conditions

javascript

Copy

let temperature = 15;

if (temperature > 30) {

console.log("It's too hot outside!");

} else {

if (temperature > 20) {

console.log("The weather is nice.");

} else {

if (temperature > 10) {

console.log("It's a bit chilly.");

} else {

console.log("It's very cold!");

// Output: It's a bit chilly.

Example 3: Nested Login Authentication

let username = "admin";

let password = "secure123";


if (username === "admin") {

if (password === "secure123") {

console.log("Login successful!");

} else {

console.log("Incorrect password.");

} else {

console.log("Invalid username.");

// Output: Login successful!

Loop control in JavaScript allows you to execute a block of code multiple times. Here are the
main types of loops and their control mechanisms:

1. for Loop

The for loop is used when the number of iterations is known.

for (let i = 0; i < 5; i++) {

console.log(i);

2. while Loop

The while loop continues as long as a specified condition is true.

let i = 0;

while (i < 5) {

console.log(i);

i++;

3. do...while Loop
The do...while loop executes the block at least once, then continues as long as the condition is
true.

let i = 0;

do {

console.log(i);

i++;

} while (i < 5);

4. for...of Loop

Used for iterating over iterable objects (like arrays).

const array = [1, 2, 3, 4];

for (const value of array) {

console.log(value);

5. for...in Loop

Used for iterating over the properties of an object.

const obj = { a: 1, b: 2, c: 3 };

for (const key in obj) {

console.log(`${key}: ${obj[key]}`);

Loop Control Statements

break: Exits the loop immediately.

continue: Skips the current iteration and continues with the next one.

Example of break and continue

for (let i = 0; i < 10; i++) {

if (i === 5) {
break; // Exit loop when i is 5

if (i % 2 === 0) {

continue; // Skip even numbers

console.log(i); // Logs only odd numbers less than 5

JavaScript for loop is a control flow statement that allows code to be executed repeatedly based
on a condition. It consists of three parts: initialization, condition, and increment/decrement.

// for loop begins when x=2

// and runs till x <= 4

for (let x = 2; x <= 4; x++) {

console.log("Value of x:" + x);

Output

Value of x:2

Value of x:3

Value of x:4

For loop to print table of a number.

let x = 5

for (let i = 1; i <= 10; i++) {


console.log(x * i);

Output

10

15

20

25

30

35

40

45

50

For loop to print elements of an array.

let arr = [10, 20, 30, 40];

for (let i = 0; i < arr.length; i++) {

console.log(arr[i]);

Output

10

20

30

40

Syntax of For Loop in JavaScript


A for loop in JavaScript repeatedly executes a block of code as long as a specified condition is
true. It includes initialization, condition checking, and iteration steps, making it efficient for
controlled, repetitive tasks.

Syntax:

for (statement 1 ; statement 2 ; statement 3){ code here...}

Statement 1: It is the initialization of the counter. It is executed once before the execution of the
code block.

Statement 2: It defines the testing condition for executing the code block

Statement 3: It is the increment or decrement of the counter & executed (every time) after the
code block has been executed.

Flow chart

This flowchart shows the working of the for loop in JavaScript. You can see the control flow in
the For loop.

for loop flow chart

Statement 1: Initializing Counter Variable

Statement 1 is used to initialize the counter variable. A counter variable is used to keep track of
the number of iterations in the loop. You can initialize multiple counter variables in statement 1.

We can initialize the counter variable externally rather than in statement 1. This shows us clearly
that statement 1 is optional. We can leave the portion empty with a semicolon.

Example:

let x = 2;

for (; x <= 4; x++) {

console.log("Value of x:" + x);

Output

Value of x:2

Value of x:3
Value of x:4

Output

Value of x:2

Value of x:3

Value of x:4

Statement 2: Testing Condition

This statement checks the boolean value of the testing condition. If the testing condition is true,
the for loop will execute further, otherwise loop will end and the code outside the loop will be
executed. It is executed every time the for loop runs before the loop enters its body.

This is also an optional statement and Javascript treats it as true if left blank. If this statement is
omitted, the loop runs indefinitely if the loop control isn't broken using the break statement. It is
explained below in the example.

Example:

let x = 2;

for (; ; x++) {

console.log("Value of x:" + x);

break;

Output
Value of x:2

Output:

Value of x:2

Statement 3: Updating Counter Variable

It is a controlled statement that controls the increment/decrement of the counter variable.

It is also optional by nature and can be done inside the loop body.

Example:

const subjects = ["Maths", "Science", "Polity", "History"];

let i = 0;

let len = subjects.length;

let gfg = "";

for (; i < len;) {

gfg += subjects[i];

//can be increased inside loop

i++;

console.log(gfg)
Output

MathsSciencePolityHistory

Output

MathsSciencePolityHistory

More Loops in JavaScript

JavaScript has different kinds of loops in Java. Some of the loops are:

Loop Description

for loop A loop that repeats a block of code a specific number of times based on a
conditional expression.

while loop A loop that repeats a block of code as long as a specified condition is true.

do-while loop A loop that executes a block of code at least once, then repeats the block as long
as a specified condition is true.

for...of loop Iterates over the values of an iterable object (like arrays, strings, maps, sets, etc.)

for...in loop Iterates over the enumerable properties of an object (including inherited
properties).

Learn and master JavaScript with Practice Questions. JavaScript Exercises provides many
JavaScript Exercise questions to practice and test your JavaScript skills.

Advertise with us

Next Article

ashishsaini3
Follow

22

Similar Reads

JavaScript Tutorial

JavaScript is a programming language used to create dynamic content for websites. It is a


lightweight, cross-platform, and single-threaded programming language. JavaScript is an
interpreted language that executes code line by line, providing more flexibility.JavaScript on
Client Side : On client sid

11 min read

JavaScript Basics

JS Variables & Datatypes

JS Operators

JS Statements

JS Loops

JavaScript Loops

Loops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of code as
long as a specified condition is true. This makes code more concise and efficient.Suppose we
want to print 'Hello World' five times. Instead of manually writing the print statement repeatedly,
we can u

3 min read

JavaScript For Loop

JavaScript for loop is a control flow statement that allows code to be executed repeatedly based
on a condition. It consists of three parts: initialization, condition, and increment/decrement.
javascript// for loop begins when x=2 // and runs till x <= 4 for (let x = 2; x <= 4; x++) { console.

5 min read

JavaScript While Loop

The while loop executes a block of code as long as a specified condition is true. In JavaScript,
this loop evaluates the condition before each iteration and continues running as long as the
condition remains trueHere's an example that prints from 1 to 5. JavaScriptlet count = 1; while
(count <= 5

3 min read

JavaScript For In Loop

The JavaScript for...in loop iterates over the properties of an object. It allows you to access each
key or property name of an object.JavaScriptconst car = { make: "Toyota", model: "Corolla",
year: 2020 }; for (let key in car) { console.log(`${key}: ${car[key]}`); }Outputmake: Toyota
model: Corolla

3 min read

JavaScript for...of Loop

The JavaScript for...of loop is a modern, iteration statement introduced in ECMAScript 2015
(ES6). Works for iterable objects such as arrays, strings, maps, sets, and more. It is better choice
for traversing items of iterables compared to traditional for and for in loops, especially when we
have bre

3 min read

JavaScript do...while Loop

A do...while loop in JavaScript is a control structure where the code executes repeatedly based
on a given boolean condition. It's similar to a repeating if statement. One key difference is that a
do...while loop guarantees that the code block will execute at least once, regardless of whether
the co

4 min read

JS Perfomance & Debugging

JS Object

JS Function

JS Array

Article Tags :

JavaScript

Web Technologies

javascript-basics
geeksforgeeks-footer-logo

Corporate & Communications Address:

A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)

Registered Address:

K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar
Pradesh, 201305

GFG App on Play Store

GFG App on App Store

Advertise with us

Company

About Us

Legal

Privacy Policy

In Media

Contact Us

Advertise with us

GFG Corporate Solution

Placement Training Program

Languages

Python

Java

C++

PHP

GoLang

SQL
R Language

Android Tutorial

Tutorials Archive

DSA

Data Structures

Algorithms

DSA for Beginners

Basic DSA Problems

DSA Roadmap

Top 100 DSA Interview Problems

DSA Roadmap by Sandeep Jain

All Cheat Sheets

Data Science & ML

Data Science With Python

Data Science For Beginner

Machine Learning

ML Maths

Data Visualisation

Pandas

NumPy

NLP

Deep Learning

Web Technologies

HTML

CSS
JavaScript

TypeScript

ReactJS

NextJS

Bootstrap

Web Design

Python Tutorial

Python Programming Examples

Python Projects

Python Tkinter

Python Web Scraping

OpenCV Tutorial

Python Interview Question

Django

Computer Science

Operating Systems

Computer Network

Database Management System

Software Engineering

Digital Logic Design

Engineering Maths

Software Development

Software Testing

DevOps

Git
Linux

AWS

Docker

Kubernetes

Azure

GCP

DevOps Roadmap

System Design

High Level Design

Low Level Design

UML Diagrams

Interview Guide

Design Patterns

OOAD

System Design Bootcamp

Interview Questions

Inteview Preparation

Competitive Programming

Top DS or Algo for CP

Company-Wise Recruitment Process

Company-Wise Preparation

Aptitude Preparation

Puzzles

School Subjects

Mathematics
Physics

Chemistry

Biology

Social Science

English Grammar

Commerce

World GK

GeeksforGeeks Videos

DSA

Python

Java

C++

Web Development

Data Science

CS Subjects

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

Lightbox

geeksforgeeks
S

My Profile

Edit Profile

My Courses

Join Community

Transactions

Logout

Home

Saved Videos

Courses

Data Structures and Algorithms

ML & Data Science

Web Development

Languages

Interview Corner

CS Subjects

Jobs

Practice

Contests

GBlog

Puzzles

What's New ?

Change Language

JS Tutorial
JS Exercise

JS Interview Questions

JS Array

JS String

JS Object

JS Operator

JS Date

JS Error

JS Projects

JS Set

JS Map

JS RegExp

JS Math

JS Number

JS Boolean

JS Examples

JS Free JS Course

JS A to Z Guide

JS Formatter

Open In App

JavaScript While Loop

Last Updated : 19 Nov, 2024

The while loop executes a block of code as long as a specified condition is true. In JavaScript,
this loop evaluates the condition before each iteration and continues running as long as the
condition remains true
Here's an example that prints from 1 to 5.

let count = 1;

while (count <= 5) {

console.log(count);

count++;

Output

Syntax

while (condition) { Code block to be executed}

Using While Loop to find Traverse an Array


let arr = [10, 20, 30, 40];

let i = 0;

while (i < arr.length) {

console.log(arr[i]);

i++;

Output

10

20

30

40

Do-While loop

A Do-While loop is another type of loop in JavaScript that is similar to the while loop, but with
one key difference: the do-while loop guarantees that the block of code inside the loop will be
executed at least once, regardless of whether the condition is initially true or false .

Syntax

do {

// code block to be executed

} while (condition);

Example : Here's an example of a do-while loop that counts from 1 to 5.


let count = 1;

do {

console.log(count);

count++;

} while (count <= 5);

Output

Comparison between the while and do-while loop:

The do-while loop executes the content of the loop once before checking the condition of the
while loop. While the while loop will check the condition first before executing the content.

While Loop

Do-While Loop

It is an entry condition looping structure.

It is an exit condition looping structure.


The number of iterations depends on the condition mentioned in the while block.

Irrespective of the condition mentioned in the do-while block, there will a minimum of 1
iteration.

The block control condition is available at the starting point of the loop.

The block control condition is available at the endpoint of the loop.

Advertise with us

Next Article

SHUBHAMSINGH10

Follow

20

Similar Reads

JavaScript Tutorial

JavaScript is a programming language used to create dynamic content for websites. It is a


lightweight, cross-platform, and single-threaded programming language. JavaScript is an
interpreted language that executes code line by line, providing more flexibility.JavaScript on
Client Side : On client sid

11 min read
JavaScript Basics

JS Variables & Datatypes

JS Operators

JS Statements

JS Loops

JavaScript Loops

Loops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of code as
long as a specified condition is true. This makes code more concise and efficient.Suppose we
want to print 'Hello World' five times. Instead of manually writing the print statement repeatedly,
we can u

3 min read

JavaScript For Loop

JavaScript for loop is a control flow statement that allows code to be executed repeatedly based
on a condition. It consists of three parts: initialization, condition, and increment/decrement.
javascript// for loop begins when x=2 // and runs till x <= 4 for (let x = 2; x <= 4; x++) { console.

5 min read

JavaScript While Loop

The while loop executes a block of code as long as a specified condition is true. In JavaScript,
this loop evaluates the condition before each iteration and continues running as long as the
condition remains trueHere's an example that prints from 1 to 5. JavaScriptlet count = 1; while
(count <= 5

3 min read

JavaScript For In Loop

The JavaScript for...in loop iterates over the properties of an object. It allows you to access each
key or property name of an object.JavaScriptconst car = { make: "Toyota", model: "Corolla",
year: 2020 }; for (let key in car) { console.log(`${key}: ${car[key]}`); }Outputmake: Toyota
model: Corolla

3 min read

JavaScript for...of Loop


The JavaScript for...of loop is a modern, iteration statement introduced in ECMAScript 2015
(ES6). Works for iterable objects such as arrays, strings, maps, sets, and more. It is better choice
for traversing items of iterables compared to traditional for and for in loops, especially when we
have bre

3 min read

JavaScript do...while Loop

A do...while loop in JavaScript is a control structure where the code executes repeatedly based
on a given boolean condition. It's similar to a repeating if statement. One key difference is that a
do...while loop guarantees that the code block will execute at least once, regardless of whether
the co

4 min read

JS Perfomance & Debugging

JS Object

JS Function

JS Array

Article Tags :

JavaScript

Web Technologies

javascript-basics

geeksforgeeks-footer-logo

Corporate & Communications Address:

A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)

Registered Address:

K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar
Pradesh, 201305

GFG App on Play Store

GFG App on App Store

Advertise with us
Company

About Us

Legal

Privacy Policy

In Media

Contact Us

Advertise with us

GFG Corporate Solution

Placement Training Program

Languages

Python

Java

C++

PHP

GoLang

SQL

R Language

Android Tutorial

Tutorials Archive

DSA

Data Structures

Algorithms

DSA for Beginners

Basic DSA Problems

DSA Roadmap
Top 100 DSA Interview Problems

DSA Roadmap by Sandeep Jain

All Cheat Sheets

Data Science & ML

Data Science With Python

Data Science For Beginner

Machine Learning

ML Maths

Data Visualisation

Pandas

NumPy

NLP

Deep Learning

Web Technologies

HTML

CSS

JavaScript

TypeScript

ReactJS

NextJS

Bootstrap

Web Design

Python Tutorial

Python Programming Examples

Python Projects
Python Tkinter

Python Web Scraping

OpenCV Tutorial

Python Interview Question

Django

Computer Science

Operating Systems

Computer Network

Database Management System

Software Engineering

Digital Logic Design

Engineering Maths

Software Development

Software Testing

DevOps

Git

Linux

AWS

Docker

Kubernetes

Azure

GCP

DevOps Roadmap

System Design

High Level Design


Low Level Design

UML Diagrams

Interview Guide

Design Patterns

OOAD

System Design Bootcamp

Interview Questions

Inteview Preparation

Competitive Programming

Top DS or Algo for CP

Company-Wise Recruitment Process

Company-Wise Preparation

Aptitude Preparation

Puzzles

School Subjects

Mathematics

Physics

Chemistry

Biology

Social Science

English Grammar

Commerce

World GK

GeeksforGeeks Videos

DSA
Python

Java

C++

Web Development

Data Science

CS Subjects

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

Lightbox

geeksforgeeks

My Profile

Edit Profile

My Courses

Join Community

Transactions

Logout

Home

Saved Videos

Courses

Data Structures and Algorithms

ML & Data Science


Web Development

Languages

Interview Corner

CS Subjects

Jobs

Practice

Contests

GBlog

Puzzles

What's New ?

Change Language

JS Tutorial

JS Exercise

JS Interview Questions

JS Array

JS String

JS Object

JS Operator

JS Date

JS Error

JS Projects

JS Set

JS Map

JS RegExp

JS Math
JS Number

JS Boolean

JS Examples

JS Free JS Course

JS A to Z Guide

JS Formatter

Open In App

Functions in JavaScript

Last Updated : 14 May, 2025

Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They
allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return
outputs.

Loading Playground...

function sum(x, y) {

return x + y;

console.log(sum(6, 9));

Output

15

Function Syntax and Working


A function definition is sometimes also termed a function declaration or function statement.
Below are the rules for creating a function in JavaScript:

Begin with the keyword function followed by,

A user-defined function name (In the above example, the name is sum)

A list of parameters enclosed within parentheses and separated by commas (In the above
example, parameters are x and y)

A list of statements composing the body of the function enclosed within curly braces {} (In the
above example, the statement is "return x + y").

Return Statement

In some situations, we want to return some values from a function after performing some
operations. In such cases, we make use of the return. This is an optional statement. In the above
function, "sum()" returns the sum of two as a result.

Function Parameters

Parameters are input passed to a function. In the above example, sum() takes two parameters, x
and y.

Calling Functions

After defining a function, the next step is to call them to make use of the function. We can call a
function by using the function name separated by the value of parameters enclosed between the
parenthesis.

Loading Playground...

// Function Definition
function welcomeMsg(name) {

return ("Hello " + name + " welcome to GeeksforGeeks");

let nameVal = "User";

// calling the function

console.log(welcomeMsg(nameVal));

Output

Hello User welcome to GeeksforGeeks

Why Functions?

Functions can be used multiple times, reducing redundancy.

Break down complex problems into manageable pieces.

Manage complexity by hiding implementation details.

Can call themselves to solve problems recursively.

Function Invocation

The function code you have written will be executed whenever it is called.

Triggered by an event (e.g., a button click by a user).

When explicitly called from JavaScript code.

Automatically executed, such as in self-invoking functions.

Function Expression

It is similar to a function declaration without the function name. Function expressions can be
stored in a variable assignment.
Syntax:

let geeksforGeeks= function(paramA, paramB) {

// Set of statements

Loading Playground...

const mul = function (x, y) {

return x * y;

};

console.log(mul(4, 5));

Output

20

Arrow Functions

Arrow functions are a concise syntax for writing functions, introduced in ES6, and they do not
bind their own this context.

Syntax:

let function_name = (argument1, argument2 ,..) => expression


Loading Playground...

const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];

const a2 = a.map(function (s) {

return s.length;

});

console.log("Normal way ", a2);

const a3 = a.map((s) => s.length);

console.log("Using Arrow Function ", a3);

Output

Normal way [ 8, 6, 7, 9 ]

Using Arrow Function [ 8, 6, 7, 9 ]

Immediately Invoked Function Expression (IIFE)

IIFE functions are executed immediately after their definition. They are often used to create
isolated scopes.
Loading Playground...

(function () {

console.log("This runs immediately!");

})();

Output

This runs immediately!

Callback Functions

A callback function is passed as an argument to another function and is executed after the
completion of that function.

Loading Playground...

function num(n, callback) {

return callback(n);

const double = (n) => n * 2;

console.log(num(5, double));

Output

10
Anonymous Functions

Anonymous functions are functions without a name. They are often used as arguments to other
functions.

Loading Playground...

setTimeout(function () {

console.log("Anonymous function executed!");

}, 1000);

Nested Functions

Functions defined within other functions are called nested functions. They have access to the
variables of their parent function.

Loading Playground...

function outerFun(a) {

function innerFun(b) {

return a + b;

return innerFun;

}
const addTen = outerFun(10);

console.log(addTen(5));

Output

15

Pure Functions

Pure functions return the same output for the same inputs and do not produce side effects. They
do not modify state outside their scope, such as modifying global variables, changing the state of
objects passed as arguments, or performing I/O operations.

Loading Playground...

function pureAdd(a, b) {

return a + b;

console.log(pureAdd(2, 3));

Output

Key Characteristics of Functions

Parameters and Arguments: Functions can accept parameters (placeholders) and be called with
arguments (values).

Return Values: Functions can return a value using the return keyword.
Default Parameters: Default values can be assigned to function parameters.

Advantages of Functions in JavaScript

Reusability: Write code once and use it multiple times.

Modularity: Break complex problems into smaller, manageable pieces.

Improved Readability: Functions make code easier to understand.

Maintainability: Changes can be made in one place without affecting the entire codebase.

Choosing the Right Function Type

Use function declarations for regular reusable functions.

Use arrow functions for concise, one-line functions.

Use IIFE for code that runs immediately.

Use callback functions for asynchronous operations like API calls.

Use pure functions for predictable behavior without side effects.

Advertise with us

Next Article

author

harsh.agarwal0

Follow

72

Similar Reads

JavaScript Tutorial

JavaScript is a programming language used to create dynamic content for websites. It is a


lightweight, cross-platform, and single-threaded programming language. JavaScript is an
interpreted language that executes code line by line, providing more flexibility.JavaScript on
Client Side : On client sid

11 min read

JavaScript Basics

JS Variables & Datatypes

JS Operators

JS Statements

JS Loops

JS Perfomance & Debugging

JS Object

JS Function

Functions in JavaScript

Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They
allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return
outputs.JavaScriptfunction sum(x, y) { return x + y; } console.log(sum(6, 9));Output15 Function
Syntax and W

5 min read

How to write a function in JavaScript ?

JavaScript functions serve as reusable blocks of code that can be called from anywhere within
your application. They eliminate the need to repeat the same code, promoting code reusability
and modularity. By breaking down a large program into smaller, manageable functions,
programmers can enhance cod

4 min read

JavaScript Function Call

The call() method is a predefined JavaScript method. It can be used to invoke (call) a method
with an owner object as an argument (parameter). This allows borrowing methods from other
objects, executing them within a different context, overriding the default value, and passing
arguments. Syntax: cal

2 min read
Different ways of writing functions in JavaScript

A JavaScript function is a block of code designed to perform a specific task. Functions are only
executed when they are called (or "invoked"). JavaScript provides different ways to define
functions, each with its own syntax and use case.Below are the ways of writing functions in
JavaScript:Table of

3 min read

Difference between Methods and Functions in JavaScript

Grasping the difference between methods and functions in JavaScript is essential for developers
at all levels. While both are fundamental to writing effective code, they serve different purposes
and are used in various contexts. This article breaks down the key distinctions between methods
and funct

3 min read

Explain the Different Function States in JavaScript

In JavaScript, we can create functions in many different ways according to the need for the
specific operation. For example, sometimes we need asynchronous functions or synchronous
functions. Â In this article, we will discuss the difference between the function Person( ) { }, let
person = Person ( )

3 min read

JavaScript Function Complete Reference

A JavaScript function is a set of statements that takes inputs, performs specific computations,
and produces outputs. Essentially, a function performs tasks or computations and then returns the
result to the user.Syntax:function functionName(Parameter1, Parameter2, ..) { // Function
body}Example: Be

3 min read

JS Array

Article Tags :

Misc

JavaScript

Web Technologies

javascript-functions
+1 More

Practice Tags :

Misc

geeksforgeeks-footer-logo

Corporate & Communications Address:

A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)

Registered Address:

K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar
Pradesh, 201305

GFG App on Play Store

GFG App on App Store

Advertise with us

Company

About Us

Legal

Privacy Policy

In Media

Contact Us

Advertise with us

GFG Corporate Solution

Placement Training Program

Languages

Python

Java

C++
PHP

GoLang

SQL

R Language

Android Tutorial

Tutorials Archive

DSA

Data Structures

Algorithms

DSA for Beginners

Basic DSA Problems

DSA Roadmap

Top 100 DSA Interview Problems

DSA Roadmap by Sandeep Jain

All Cheat Sheets

Data Science & ML

Data Science With Python

Data Science For Beginner

Machine Learning

ML Maths

Data Visualisation

Pandas

NumPy

NLP

Deep Learning
Web Technologies

HTML

CSS

JavaScript

TypeScript

ReactJS

NextJS

Bootstrap

Web Design

Python Tutorial

Python Programming Examples

Python Projects

Python Tkinter

Python Web Scraping

OpenCV Tutorial

Python Interview Question

Django

Computer Science

Operating Systems

Computer Network

Database Management System

Software Engineering

Digital Logic Design

Engineering Maths

Software Development
Software Testing

DevOps

Git

Linux

AWS

Docker

Kubernetes

Azure

GCP

DevOps Roadmap

System Design

High Level Design

Low Level Design

UML Diagrams

Interview Guide

Design Patterns

OOAD

System Design Bootcamp

Interview Questions

Inteview Preparation

Competitive Programming

Top DS or Algo for CP

Company-Wise Recruitment Process

Company-Wise Preparation

Aptitude Preparation
Puzzles

School Subjects

Mathematics

Physics

Chemistry

Biology

Social Science

English Grammar

Commerce

World GK

GeeksforGeeks Videos

DSA

Python

Java

C++

Web Development

Data Science

CS Subjects

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

Lightbox

geeksforgeeks

My Profile
Edit Profile

My Courses

Join Community

Transactions

Logout

Home

Saved Videos

Courses

Data Structures and Algorithms

ML & Data Science

Web Development

Languages

Interview Corner

CS Subjects

Jobs

Practice

Contests

GBlog

Puzzles

What's New ?

Change Language

JS Tutorial

JS Exercise

JS Interview Questions

JS Array
JS String

JS Object

JS Operator

JS Date

JS Error

JS Projects

JS Set

JS Map

JS RegExp

JS Math

JS Number

JS Boolean

JS Examples

JS Free JS Course

JS A to Z Guide

JS Formatter

Open In App

How to write a function in JavaScript ?

Last Updated : 15 May, 2024

JavaScript functions serve as reusable blocks of code that can be called from anywhere within
your application. They eliminate the need to repeat the same code, promoting code reusability
and modularity. By breaking down a large program into smaller, manageable functions,
programmers can enhance code organization and maintainability.

Functions are one of JavaScript's core building elements. In JavaScript, a function is comparable
to a procedure—a series of words that performs a task or calculates a value—but for a process to
qualify as a function, it must accept some input and produce an output with a clear link between
the input and the result. To utilize a function, it must be defined in some place within the scope
from which it will be called.

Function Definition

A Function Definition or function statement starts with the function keyword and continues with
the following.

Function's name.

A list of function arguments contained in parenthesis and separated by commas.

Statements are enclosed in curly brackets.

Syntax:

function name(arguments)

javascript statements

Function Calling:

Function Calling at a later point in the script, simply type the function's name. By default, all
JavaScript functions can utilize argument objects. Each parameter's value is stored in an
argument object. The argument object is similar to an array. Its values may be accessed using an
index, much like an array. It does not, however, provide array methods.

function welcome() {

console.log("welcome to GfG");

}
// Function calling

welcome();

Output

welcome to GfG

Function Arguments:

A function can contain one or more arguments that are sent by the calling code and can be
utilized within the function. Because JavaScript is a dynamically typed programming language, a
Function Arguments can have any data type as a value.

function welcome(name) {

console.log("Hey " + "" + name + "" + "welcome to GfG");

// Passing arguments

welcome("Rohan");

Output

Hey Rohan welcome to GfG

Return Value:

A return statement is an optional part of a JavaScript function. If you wish to return a value from
a function, you must do this. Return Value should be the final statement of a function.
function welcome() {

// Return statement

return "Welcome to GfG";

console.log(welcome());

Output

Welcome to GfG

Function Expression:

We may assign a function to a variable and then utilize that variable as a function in JavaScript.
Function Expression is known as a function expression.

let welcome = function () {

return "Welcome to GfG";

}
let gfg = welcome();

console.log(gfg);

Output

Welcome to GfG

Types Of Functions in JavaScript

1. Named function:

A Named function is one that we write in code and then use whenever we need it by referencing
its name and providing it with some parameters. Named functions come in handy when we need
to call a function several times to give various values to it or run it multiple times.

function add(a, b) {

return a + b;

console.log(add(5, 4));

Output

2. Anonymous function:

We can define a function in JavaScript without giving it a name. This nameless function is
referred to as the Anonymous function. A variable must be assigned to an anonymous function.
let add = function (a, b) {

return a + b;

console.log(add(5, 4));

Output

3. Nested Functions:

A function in JavaScript can contain one or more inner functions. These Nested Functions fall
within the purview of the outer function. The inner function has access to the variables and
arguments of the outer function. However, variables declared within inner functions cannot be
accessed by outer functions.

function msg(firstName) {

function hey() {

console.log("Hey " + firstName);

return hey();

}
msg("Ravi");

Output

Hey Ravi

4. Immediately invoked function expression:

The browser executes the invoked function expression as soon as it detects it. Immediately
invoked function expression has the advantage of running instantly where it is situated in the
code and producing direct output. That is, it is unaffected by code that occurs later in the script
and can be beneficial.

let msg = (function() {

return "Welcome to GfG" ;

})();

console.log(msg);

Output

Welcome to GfG

Advertise with us

Next Article

P
priyavermaa1198

Follow

Similar Reads

JavaScript Tutorial

JavaScript is a programming language used to create dynamic content for websites. It is a


lightweight, cross-platform, and single-threaded programming language. JavaScript is an
interpreted language that executes code line by line, providing more flexibility.JavaScript on
Client Side : On client sid

11 min read

JavaScript Basics

JS Variables & Datatypes

JS Operators

JS Statements

JS Loops

JS Perfomance & Debugging

JS Object

JS Function

Functions in JavaScript

Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They
allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return
outputs.JavaScriptfunction sum(x, y) { return x + y; } console.log(sum(6, 9));Output15 Function
Syntax and W

5 min read

How to write a function in JavaScript ?


JavaScript functions serve as reusable blocks of code that can be called from anywhere within
your application. They eliminate the need to repeat the same code, promoting code reusability
and modularity. By breaking down a large program into smaller, manageable functions,
programmers can enhance cod

4 min read

JavaScript Function Call

The call() method is a predefined JavaScript method. It can be used to invoke (call) a method
with an owner object as an argument (parameter). This allows borrowing methods from other
objects, executing them within a different context, overriding the default value, and passing
arguments. Syntax: cal

2 min read

Different ways of writing functions in JavaScript

A JavaScript function is a block of code designed to perform a specific task. Functions are only
executed when they are called (or "invoked"). JavaScript provides different ways to define
functions, each with its own syntax and use case.Below are the ways of writing functions in
JavaScript:Table of

3 min read

Difference between Methods and Functions in JavaScript

Grasping the difference between methods and functions in JavaScript is essential for developers
at all levels. While both are fundamental to writing effective code, they serve different purposes
and are used in various contexts. This article breaks down the key distinctions between methods
and funct

3 min read

Explain the Different Function States in JavaScript

In JavaScript, we can create functions in many different ways according to the need for the
specific operation. For example, sometimes we need asynchronous functions or synchronous
functions. Â In this article, we will discuss the difference between the function Person( ) { }, let
person = Person ( )

3 min read

JavaScript Function Complete Reference


A JavaScript function is a set of statements that takes inputs, performs specific computations,
and produces outputs. Essentially, a function performs tasks or computations and then returns the
result to the user.Syntax:function functionName(Parameter1, Parameter2, ..) { // Function
body}Example: Be

3 min read

JS Array

Article Tags :

JavaScript

Web Technologies

javascript-functions

JavaScript-Questions

geeksforgeeks-footer-logo

Corporate & Communications Address:

A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)

Registered Address:

K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar
Pradesh, 201305

GFG App on Play Store

GFG App on App Store

Advertise with us

Company

About Us

Legal

Privacy Policy

In Media

Contact Us

Advertise with us
GFG Corporate Solution

Placement Training Program

Languages

Python

Java

C++

PHP

GoLang

SQL

R Language

Android Tutorial

Tutorials Archive

DSA

Data Structures

Algorithms

DSA for Beginners

Basic DSA Problems

DSA Roadmap

Top 100 DSA Interview Problems

DSA Roadmap by Sandeep Jain

All Cheat Sheets

Data Science & ML

Data Science With Python

Data Science For Beginner

Machine Learning
ML Maths

Data Visualisation

Pandas

NumPy

NLP

Deep Learning

Web Technologies

HTML

CSS

JavaScript

TypeScript

ReactJS

NextJS

Bootstrap

Web Design

Python Tutorial

Python Programming Examples

Python Projects

Python Tkinter

Python Web Scraping

OpenCV Tutorial

Python Interview Question

Django

Computer Science

Operating Systems
Computer Network

Database Management System

Software Engineering

Digital Logic Design

Engineering Maths

Software Development

Software Testing

DevOps

Git

Linux

AWS

Docker

Kubernetes

Azure

GCP

DevOps Roadmap

System Design

High Level Design

Low Level Design

UML Diagrams

Interview Guide

Design Patterns

OOAD

System Design Bootcamp

Interview Questions
Inteview Preparation

Competitive Programming

Top DS or Algo for CP

Company-Wise Recruitment Process

Company-Wise Preparation

Aptitude Preparation

Puzzles

School Subjects

Mathematics

Physics

Chemistry

Biology

Social Science

English Grammar

Commerce

World GK

GeeksforGeeks Videos

DSA

Python

Java

C++

Web Development

Data Science

CS Subjects

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved


Lightbox

You might also like