JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Functions


📘 JavaScript Functions – Reusable Blocks of Code

A function is a set of statements that performs a task or returns a value. Functions help you write modular, DRY (Don't Repeat Yourself) code.


🔹 Syntax – Declaring a Function

function functionName(parameters) {
  // code to execute
}
  • functionName is the name you give to the function.

  • parameters are input values passed to the function.

  • return is used to send back a result.


🔹 Example 1 – Basic Function

function greet(name) {
  return "Hello, " + name;
}

console.log(greet("Alice")); // Output: Hello, Alice

🔹 Example 2 – Function Without Parameters

function sayHi() {
  console.log("Hi there!");
}

sayHi(); // Output: Hi there!

🔹 Function Expressions

const add = function(a, b) {
  return a + b;
};

console.log(add(2, 3)); // Output: 5

🔹 Arrow Functions (ES6+)

const multiply = (x, y) => x * y;

console.log(multiply(4, 5)); // Output: 20

🔹 Function with Default Parameters

function greet(name = "Guest") {
  return "Welcome, " + name;
}

console.log(greet()); // Output: Welcome, Guest

🔹 Function Return vs Console.log

  • return sends a value back to the caller.

  • console.log() just prints the value in the console.


Practice Questions

Q1. How do you define a named function in JavaScript?

Q2. What is the difference between a function declaration and a function expression?

Q3. How can you write a function that takes two numbers and returns their sum?

Q4. What is the purpose of the return statement in a function?

Q5. Write a function that takes a string and returns it in uppercase.

Q6. What are arrow functions, and how do they differ from regular functions?

Q7. How do default parameters work in JavaScript functions?

Q8. Can a function be stored in a variable? Show with an example.

Q9. What happens if a function is called with fewer arguments than parameters?

Q10. Write a function that calculates the factorial of a number using a loop.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top