Our Objective: How To Use JavaScript Functions? With Examples!
JavaScript needs no introduction! Since it’s among the top most widely used programming languages. Out of 1.8 Billion websites in the world, JavaScript is used on approximately 95% of them. That’s the popularity of JavaScript. Its usage has been grown over the years and now it has finally become the most used language.
JavaScript growth over the years is commendable and is truly justifiable. It has some highlighting features that make it stand out from the others.
- JavaScript serves all
- whether it is a beginner, intermediate, or even an advanced developer
- Omni-platform
- it can run on any screen size, on any device, and everywhere, without any discrimination
- Open standards and community
- it has been around for 25 years and has a vast community behind it
- Modern frameworks
- frameworks like Vue, Express, Angular, React have made it even more popular and loved
JavaScript’s universal popularity is also because of its high demand in the web development sector. Not only it is the top choice in building websites, web applications, but also it is popularly needed in mobile app development and even game development. JavaScript is an easy-to-learn language. It is used to add functioning and behavior to a webpage. With all the recent framework development in JS, it is becoming the language of the future and surely is here to stay.
Like any other programming language, JS makes use of the functions too. So let’s first understand briefly what are functions in programming languages and why do we need them.
Table of Contents
What is a Function?
As proteins are the building blocks of life, a Function is also the building block of JavaScript. A Function is a block of code that performs a specific task. In JavaScript also, a function allows you to define a block of code, give it a name and then call it as many times to reuse the code. The functions can be in-built or user-defined. JS has a huge list of built-in functions too, but in this tutorial, we are focusing on the user-defined functions.
- A function is a reusable code block that can be executed as many times as you want. Thus, it becomes a great time saver.
- JavaScript supports a huge library of built-in functions.
- It allows code reusability.
- Functions make our program compact. Typing the same code, again and again, is not required anymore.
- Functions allow a programmer to divide a big program into manageable and smaller functions.
Built-in Functions | User-Defined Functions |
---|---|
Built-in functions come pre-installed with JavaScript. | User-defined function means you can create a function for your use. |
No need to name them. | Naming is required to execute them later. |
Example: isNan(), parseInt (string), String (object), parseFloat (string) etc. | Example: function sayHello() { alert(“Hello there”); } |
Defining a JavaScript Function
To use a JS function, defining it is necessary. A JS function is always defined with the keyword “Function”. Using the function
keyword depicts the starting of a function code block.
Syntax
The ‘function
‘ keyword is followed by the function name and the function body. By convention, the function names are in camelCase.
function functionName() {
// function body
}
- A function is declared using the
function
keyword. - The name of the function should always resemble the working of the function. Thus a descriptive name is always better.
- For example, if a function is used to add multiply two numbers, you could name the function
multiply
or product.
- For example, if a function is used to add multiply two numbers, you could name the function
- The body of the function is written within
{}
.
Complete Execution Cycle of a JavaScript Function
JS Code:
function Hello() {
alert("Hello there");}
HTML Code/ Calling a JS Function:
We will use this HTML code for all the examples that are shown further in the tutorial. So only the JavaScript function(sayHello()) will get replaced by the new JS function name every time, the rest of the HTML will remain constant.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p onclick="sayHello()">Click me</p>
<script src="index.js"></script>
</body>
</html>
Output:
Hello there
Examples of JavaScript Functions
Here we will learn and understand different functions that are used in JavaScript using various examples.
Example 1 Simple Greet Function Without Parameter
In this example, we will simply print a message on the console. To check the message on the console, follow the following steps:
- Open your webpage in the browser.
- Right-click on the webpage and hit “inspect”.
- Now chrome developer tools will get open, click on “Console”, which is placed right next to the “Elements”.
- In the console section, you will be able to see your logged message.
JavaScript Function Code
function greet() {
console.log("Good Morning!")
}
Output:
Good Morning!
Function Parameter
We have only seen functions without parameters till now. But functions with parameters allow the developer to pass different parameters when calling the function. A function can accept multiple parameters too. The parameter goes inside the function and the code gets executed based on the parameter.
function greet(parameter) {
//code
}
Function Argument
When we use parameterized functions, we also give arguments when calling the same function. An argument is a value that is passed when calling/invoking the function.
greet(argument);
Parameters vs. Arguments
function greet(parameter) {
console.log("Good Morning," + parameter)
}
greet(arguments);
Though both the terms are often used interchangeably, they have different meanings.
When declaring a function, parameters are specified. And when calling a function, you pass the arguments resembling the parameters.
Example 2: Personalised Greet Function With 1 Parameter
JavaScript can also be executed directly in the console. So from here, I have used the console only, to print my javascript functions output.
function greet(name) {
console.log("Good Morning," + name)
}
greet("Vaishali");
Output:
Good Morning,Vaishali
Example 3: Multiplication Function With 2 Parameters
function multiply(a, b) {
console.log(a * b);
}
// calling function
multiply(6,4);
Output:
24
So in the above program, the multiply function is used to find the product of two numbers.
- The function is declared with two parameters
a
andb
. - The function is called using its name and passing arguments 6 and 4.
You can call a function as many times as you want. You can write one function block and then call it numerous times with different arguments.
Example 4: Display Age Function With 2 Parameters
function displayAge(name, age) {
console.log(name + " is " + age + " years old.");
}
//calling function
displayAge("Ram", 54)
Output:
Ram is 54 years old.
The return
Statement
The ‘return
‘ statement can be used to specify the value returned by the function. It denotes that the function has been ended. Since it is the last statement of the function, anything after the return statement gets ignored.
Unless the return statement is specified, the default return value of a JavaScript function remains “undefined”.
Example 5: Checking the Cube
function cube(number) {
return number * number * number;
}
Example 6: Comparing 2 numbers
function compare(a, b) {
if (a > b) {
return ( a + " which is 'a' is bigger");
} else if (a < b) {
return (b + " which is 'b' is bigger");
}
return ("both are equal");
}
That’s it for this article. I hope this tutorial must have helped you in understand the JavaScript Functions with examples better. I will continue to make such short topic articles more often now. Please share the article if it has helped you, it will boost my motivation a lot.
Share the article and don’t forget to write your suggestions/ feedback in the comments section down below.
Some reliable resources to learn more about Js Functions:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
- https://www.w3schools.com/js/js_functions.asp
Let’s greet() each other on our Social Media Handles too:
Here’s a link to some of our recent posts:
- Want To Become a Pythoneer? Try Out These 11 Simple Python Projects Now!
- With “Bhailang”, learn Programming the easy and fun way
- Make an Attractive Responsive Navigation Bar Using HTML and CSS
- The Most Asked HTML Interview Questions Of All Time
- How To Instantly Make Internet Speedtest App Using Speedtest Python?
- CSS 01: How To Use Bulma CSS To Style Your Next Login Form?
0 Comments