Functions In JavaScript:
A function is a block of code designed to perform a particular task.It only runs when
called/invoked.
Or
A function in JavaScript is like a reusable set of instructions
Function Definition
Function Call/invoke
4 ways to create a function
1. Without parameter list & without return.
2. Without parameter list & with return.
3. With parameter list & without return.
4. With parameter list & with return.
s;
Note:
❑ Parameters: placeholders used
when creating the function.
❑ Arguments: actual values passed
when calling the function.
❑ Parameters in a function is like
local variable having block scope.
Default Parameters
default parameters allow you to assign default values to function parameters.
If no value (or undefined) is passed for that parameter when the function is called, the default
value is used instead.
Example:
Note:
❑ Only undefined triggers the default value.
❑ You can use expressions as default values.
Types of functions
# Function Type Description Example
Function Declaration Declared with the function keyword, can be
1
(normal function) hoisted
2 Function Expression Stored in a variable; not hoisted
Arrow Function
3 Shorter syntax, introduced in ES6
(fat arrow function)
A function without a name, often used in
4 Anonymous Function
expressions
IIFE
5 (Immediately Invoked A function that runs as soon as it's defined
Function Expression)
1. Write a regular function that takes a string and returns it with the first letter capitalized.
2. Show an alert message that says “Please login” after 5 seconds on your website.
3. Make an arrow function that takes a price and a discount, and returns the price after
discount.
4. Create a function that builds a username from a full name.
5. Write a function that takes a traffic light color and gives the correct instruction (e.g. "go"
for green, "stop" for red, "caution" for yellow, and "invalid color" for anything else).