Friday, 29 November 2024

Functions in JavaScript

Functions are one of the fundamental building blocks in JavaScript. They allow you to encapsulate code into reusable blocks, making your programs more modular, maintainable, and readable.

What is a Function?

A function is a block of code designed to perform a particular task. A JavaScript function is executed when "something" invokes it (calls it).

 

Declaring a Function

You can declare a function in JavaScript using the function keyword. Here’s a basic example:

function greet() {
    console.log('Hello, world!!!!');
}

 

In this example:

 

1.   function is the keyword used to declare a function.

2.   greet is the name of the function.

3.   The code inside the curly braces {} is the function's body, which is executed when the function is called.

 

How to call a function?

To execute the code inside a function, you need to call the function by its name followed by parentheses.

greet();

 

helloWorld.js

function greet() {
    console.log('Hello, World!!!!');
}

greet();
greet();
greet();

 

Output

Hello, World!!!!
Hello, World!!!!
Hello, World!!!!

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment