0% found this document useful (0 votes)
3 views

Lecture 5 - Function in JavaScript

Uploaded by

muhammad.ayub85
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture 5 - Function in JavaScript

Uploaded by

muhammad.ayub85
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Syntax of a function in JavaScript:

Defining the function:


function functionName(parameters) {
// code to be executed
}
Calling the function:
functionName(arguments);
Breakdown:
1. function: This keyword is used to define a function.
2. functionName: This is the name of the function. It can be any valid name that
describes what the function does.
3. parameters: These are values that the function can take as input. They are
optional.
4. { }: Curly braces define the block of code where the function’s tasks are
written.
5. // code to be executed: This is where you write the code that will run when
the function is called.
6. Calling the function: To call the function and make it run, you write
functionName(arguments);. The arguments (if any) are passed to the function,
and the task inside { } gets executed.
Example:
Define function:
function sayHello(name) {
console.log("Hello, " + name);
}
Calling function:
sayHello("Ayub");
Output: Hello, Ayub.

Explanation:
 The function sayHello takes a parameter name.
 Inside the function, it prints "Hello" followed by the name.
 sayHello("Ayub") calls the function, passing "Ayub" as the argument, so it
outputs: Hello, Ayub.
Which part of the function syntax represents this definition. “"a function is a
block of code that performs a specific task":
The part of the function syntax that represents the definition "a function is a block of
code that performs a specific task" is:
{
// code to run
}
The curly braces { } contain the block of code that performs the specific task when the
function is called. This is where the logic or actions of the function are written.

Exercise Questions:
Here are six examples for each type of function: one that doesn’t need parameters and
one that does. Each example includes a brief explanation.
Functions That Don’t Need Parameters
Example 1: Say Hello
function sayHello() {
console.log("Hello!");
}
// Calling the function
sayHello(); // Outputs: Hello!
This function simply prints "Hello!" when called.
Example 2: Print Current Year
function printYear() {
const year = new Date().getFullYear();
console.log("Current Year: " + year);
}
// Calling the function
printYear(); // Outputs: Current Year: (current year)
This function prints the current year.

Explanations
Imagine you have a magic mirror that tells you about the year whenever you
ask.
1. Ask the mirror: We ask the mirror the year by using new Date().
2. Get the answer: The mirror tells us the year using getFullYear().
3. Tell someone the answer: We tell someone the year the mirror said using
console.log().
So, when you run the code, it's like asking the mirror, "What year is it?" and then telling
someone the answer.

Example 3: Show a Message


function showMessage() {
console.log("Welcome to the JavaScript world!");
}
// Calling the function
showMessage(); // Outputs: Welcome to the JavaScript world!
This function displays a welcome message.
Example 4: Count to Five
function countToFive() {
for (let i = 1; i <= 5; i++) {
console.log(i);
}
}
// Calling the function
countToFive(); // Outputs: 1, 2, 3, 4, 5
This function counts from 1 to 5.
Example 5: Draw a Line
function drawLine() {
console.log("----------");
}
// Calling the function
drawLine(); // Outputs: ----------
This function draws a line using dashes.
Example 6: Print Goodbye
function printGoodbye() {
console.log("Goodbye!");
}
// Calling the function
printGoodbye(); // Outputs: Goodbye!
This function prints "Goodbye!" when called.

Example 7: Print a Constant Value


function printConstantValue() {
let constantValue = 42; // A constant value
console.log("Constant Value: " + constantValue);
}
// Calling the function
printConstantValue(); // Outputs: Constant Value: 42

Functions That Need Parameters


Example 1: Greet a Person
function greet(name) {
console.log("Hello, " + name + "!");
}
// Calling the function with a name
greet("Ayub"); // Outputs: Hello, Ayub!
This function greets the person with the given name.
Example 2: Add Two Numbers
function add(a, b) {
return a + b;
}
// Calling the function with two numbers
console.log(add(3, 5)); // Outputs: 8
This function adds two numbers and returns the result.
Example 3: Calculate Square
function square(number) {
return number * number;
}
// Calling the function with a number
console.log(square(4)); // Outputs: 16
This function returns the square of the given number.
Example 4: Repeat a Word
function repeatWord(word, times) {
let result = "";
for (let i = 0; i < times; i++) {
result += word + " ";
}
console.log(result);
}
// Calling the function
repeatWord("Hello", 3); // Outputs: Hello Hello Hello
This function repeats a word a specified number of times.
Example 5: Calculate Area of Rectangle
function areaOfRectangle(length, width) {
return length * width;
}
// Calling the function with length and width
console.log(areaOfRectangle(5, 10)); // Outputs: 50
This function calculates the area of a rectangle.
Example 6: Create a Full Name
function fullName(firstName, lastName) {
return firstName + " " + lastName;
}
// Calling the function with first and last name
console.log(fullName("Muhammad", "Ayub")); // Outputs: Muhammad Ayub
This function combines a first name and last name into a full name.

Can we store functions in variables, pass them as parameters, and return them
in JavaScript?
In JavaScript, functions are very flexible and can be treated like regular values. This
means you can:
1. Store a function in a variable:
Just like you can save a number or a string in a variable, you can save a function in a
variable as well. Once saved, you can use the variable name to call the function
whenever you need it.
2. Pass a function as an argument:
You can pass a function as an input (or argument) to another function. This is useful
when you want one function to decide when or how to run another function. It makes
functions reusable and helps in creating more dynamic programs.
3. Return a function from another function:
A function can give back (or return) another function. This returned function can then be
used elsewhere. This is especially helpful when you want to generate new functions
dynamically based on some conditions or data.
Summary:
 Functions in JavaScript can be stored, passed, and returned, making them
highly flexible.
 This allows you to create powerful and reusable code, as functions can be
treated like any other data type.
Good question! What you're noticing is the difference between function declarations
and function expressions in JavaScript.
1. Function Declaration:
This is the usual way to define a named function. You use the function keyword, followed
by the function name.
function printHello() {
console.log("Hello!");
}
In this case, the function has a name (printHello), and you can call it directly by its name.
2. Function Expression:
In a function expression, you can define a function without giving it a name, and
assign it to a variable. This is called an anonymous function because it has no name.
The function is stored in a variable, and you call it using the variable's name.
Example:
let greet = function() {
console.log("Hello!");
};
Here, the function doesn't have its own name. Instead, it’s assigned to the variable
greet, and you can call it by using greet().
Why use function expressions?
 Flexibility: You can pass functions as arguments or return them easily.
 Anonymous functions: Sometimes you don't need a name for a function if
it's only going to be used once.
In summary:
 Function Declaration: Named function, can be called directly by its name.
 Function Expression: Function stored in a variable, can be anonymous, called
by the variable name.
Both are valid ways to create functions in JavaScript, and which one you use depends on
the situation!

You might also like