Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • 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 Course Functions in JavaScript

Last Updated : 13 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Javascript functions are code blocks that are mainly used to perform a particular function. We can execute a function as many times as we want by calling it(invoking it).

Function Structure: To create a function, we use function() declaration.

// Anonymous function function(){      // function...body }  // function with a name function displayMessage(){      // function..body }

Functions in JavaScript can be both anonymous and named, it totally depends on who's writing them. We make use of the name when we want to call(invoke) the function and use the value that the function return.

Example: In this example, we will call the same function 2 times.

JavaScript
function displayMessage() {     console.log(`How you doin'?`); } // Calling the function twice displayMessage(); displayMessage(); 

Output:

How you doin'? How you doin'? 

In the above code we simply wrote a function that creates a simple alert pop-up with a simple message inside it and the way we run it is by calling the function name. Variable declaration with function has a twist there can be a local variable and can a global variable.

Local Variable: A Variable that is declared inside the function body is only available inside the function block.

Example: In this example, we will see the example of a local variable.

javascript
// JS local variable example function displayMessage() {     let message = 'This is the message';     console.log(message); } displayMessage();  console.log(message); // Gives an error 

Output:

JavaScript Local Variable

We declared a function named displayMessage() and then inside it declared a variable and then printed that variable and also tried to print that variable outside the function block. Trying to use of variable outside of its declared block will result in an error.

Outer/Global Variable: Outer variables allow us to use them inside the function code block and also outside it.

Example: In this example, we will see the example of an outer variable.

javascript
// Outer variable let message = 'This is the message'; function displayMessage() {     console.log('Listen ' + message); }  displayMessage(); console.log(message); 

Output:

Listen This is the message This is the message

Example: Let's see another example where we learn about how the function can modify the message as well.

javascript
// Modifying outer variable let message = 'This is a message'; function displayMessage() {     message = 'This is the updated message';     console.log('Listen ' + message); }  console.log(message); displayMessage(); console.log(message); 

Output:

This is a message Listen This is the updated message This is the updated message

The outer variable remains unchanged before we invoke the function but after calling the function the value changes and hence even the last alert function prints the changed value to the screen.

Passing Parameter: We can even arbitrary data to functions using parameters.

Example: Let's see another example where we learn about how the function can modify the message as well.

javascript
// Passing data using parameters function sayHello(from, via) {     console.log('You have a message from '                   + from + ' via ' + via); } sayHello('Mom', 'WhatsApp'); sayHello('Dad', 'Telegram'); 

Output:

You have a message from Mom via WhatsApp You have a message from Dad via Telegram

In the above example, we simply passed two parameters and used them inside the main function. If somehow, one or all the parameters are not provided then javascript uses default parameters. In that case, it basically prints 'undefined' in place of the expected output.

Example: Let's see another example where we learn about how the function can modify the message as well.

javascript
// No parameter assigned function sayHello(from, via) {     console.log('You have a message from '                   + from + ' via ' + via); } sayHello('Mom'); // default 2 parameter 

Output:

You have a message from Mom via undefined

Example: We can also make use of the default parameter. We simply assign the value in the argument body itself like.

javascript
// Using default parameter function sayHello(from, via = 'not mentioned') {     console.log('You have a message from '                   + from + ' via ' + via); } sayHello('Mom'); 

Output:

You have a message from Mom via not mentioned

Returning a value: A function can return a value back to the code which is calling it.

Example:  A function can return a value back to the code which is calling it.

javascript
// Simple function function sum(a, b) {     return a + b; }  let result = sum(5, 10); console.log(result); // 15 

Output:

15

In the above code, we simply create a function and passed two values in the function arguments and then store the value in a variable result and finally alert it. This is generally the most used scenario in which functions are used.

To know more about the JavaScript Function please follow the attached link.


I

immukul
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Course

Similar Reads

    Introduction to JavaScript Course - Learn how to build a task tracker using JavaScript
    This is an introductory course about JavaScript that will help you learn about the basics of javascript, to begin with, the dynamic part of web development. You will learn the basics like understanding code structures, loops, objects, etc. What this course is about? In this course we will teach you
    4 min read
    JavaScript Course What is JavaScript ?
    JavaScript is a very famous programming language that was originally started in the year of 1995 with the motive of making web pages alive. It is also an essential part of the web developer skillset. In simple terms, if you want to learn web development then learn HTML & CSS before starting JavaScri
    3 min read
    JavaScript Hello World
    The JavaScript Hello World program is a simple tradition used by programmers to learn the new syntax of a programming language. It involves displaying the text "Hello, World!" on the screen. This basic exercise helps you understand how to output text and run simple scripts in a new programming envir
    2 min read
    JavaScript Course Understanding Code Structure in JavaScript
    Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and </script> tags is called a script blog. The 'type' attribute was the most important a
    3 min read
    JavaScript Course Variables in JavaScript
    Variables in JavaScript are containers that hold reusable data. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is only a name given to a memory location, all the operations done on the variable effects that memory loca
    4 min read
    JavaScript Data Types
    In JavaScript, each value has a data type, defining its nature (e.g., Number, String, Boolean) and operations. Data types are categorized into Primitive (e.g., String, Number) and Non-Primitive (e.g., Objects, Arrays).Primitive Data Type1. NumberThe Number data type in JavaScript includes both integ
    5 min read
    JavaScript Course Operators in JavaScript
    An operator is capable of manipulating a certain value or operand. Operators are used to performing specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands. In JavaScript, operators are used for comparing values, performing arithm
    7 min read
    JavaScript Course Interaction With User
    Javascript allows us the privilege to which we can interact with the user and respond accordingly. It includes several user-interface functions which help in the interaction. Let's take a look at them one by one. JavaScript Window alert() Method : It simply creates an alert box that may or may not h
    2 min read
    JavaScript Course Logical Operators in JavaScript
    logical operator is mostly used to make decisions based on conditions specified for the statements. It can also be used to manipulate a boolean or set termination conditions for loops. There are three types of logical operators in Javascript: !(NOT): Converts operator to boolean and returns flipped
    3 min read
    JavaScript Course Conditional Operator in JavaScript
    JavaScript Conditional Operators allow us to perform different types of actions according to different conditions. We make use of the 'if' statement. if(expression){ do this; } The above argument named 'expression' is basically a condition that we pass into the 'if' and if it returns 'true' then the
    3 min read
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
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences