FUNCTIONS:
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.
PARAMETERS AND ARGUMENTS:Understanding Functions
In functions, parameters are placeholders defined in the function, while arguments are the actual values you pass when calling the function.
Example:
function greet(name) { // 'name' is a parameter
console.log("Hello "+ name);
}
greet("Alice"); // "Alice" is the argument
OUTPUT FOR THE ABOVE CODE IS Hello Alice.
Declaring a function
To declare a function, you use the function keyword, followed by the function name, a list of parameters, and the function body as follows:
function functionName(parameters) {
// function body
// ...
}
Code language: JavaScript (javascript)
The function name must be a valid JavaScript identifier. By convention, the function names are in camelCase and start with verbs like getData(), fetchContents(), and isValid().
Camel Case is a naming convention where:
The first word starts with a lowercase letter.
Every new word after that starts with a capital letter.
No spaces or underscores are used.
Rules for giving function name :
- Start with a letter, _, or $
You can start a function name with:
Letters (a-z, A-Z)
Underscore (_)
Dollar sign ($)
Cannot contain spaces
Can contain letters, numbers, _, and $
Cannot use JavaScript reserved words like if ,for,return.
use camelcase--- eg:veryGOOD starts with small letter and next word starts with capital letter.
we need to use meaningful names for function name.
A function can accept zero, one, or multiple parameters. In the case of multiple parameters, you need to use a comma to separate two parameters.
The following declares a function say() that accepts no parameter:
function say() {
}
Code language: JavaScript (javascript)
The following declares a function named square() that accepts one parameter:
function square(a) {
}
Code language: JavaScript (javascript)
The following declares a function named add() that accepts two parameters:
function add(a, b) {
}
Code language: JavaScript (javascript)
Inside the function body, you can write the code to implement an action.
Calling a function
To use a function, you need to call it. Calling a function is also known as invoking a function.
To call a function, you use its name followed by arguments enclosed in parentheses like this:
functionName(arguments);
Code language: JavaScript (javascript)
When calling a function, JavaScript executes the code inside the function body. For example, the following shows how to call the say() function:
say('Hello');
Code language: JavaScript (javascript)
In this example, we call the say() function and pass a literal string 'Hello' into it.
Top comments (0)