KEMBAR78
Unit I FSD Notes | PDF | Java Script | World Wide Web
0% found this document useful (0 votes)
6 views32 pages

Unit I FSD Notes

Uploaded by

yasothapriya.m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views32 pages

Unit I FSD Notes

Uploaded by

yasothapriya.m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

INTRODUCTION:

JavaScript is a versatile, dynamically typed programming language that brings life to web
pages by making them interactive. It is used for building interactive web applications,
supports both client-side and server-side development, and integrates seamlessly with
HTML, CSS, and a rich standard library.

 JavaScript is a single-threaded language that executes one task at a time.


 It is an interpreted language which means it executes the code line by line.
 The data type of the variable is decided at run-time in JavaScript, which is why it is
called dynamically typed.

<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript program
console.log("Hello, World!");
</script>
</body>
</html>
In this example
 The<script> tag is used to include JavaScript code inside an HTML document.
 console.log() prints messages to the browser's developer console. Open the browser
console to see the "Hello, World!" message.

"Hello World" Program in Server Console


We can also print the "Hello World" program directly into the console terminal without
embedded it into HTML. Create an index.js file and add the code to it.
// This is a comment
console.log("Hello, World!");
Run it in your terminal with:
node hello.js
Output:
Hello, World!

Comments in JavaScript
Comments are notes in your code that the JavaScript interpreter ignores. They’re great for
explaining what your code does or for testing purposes.
 Single-line comment: Starts with //
// This is a single-line comment
 Multi-line comment: Enclosed in /* */
/* This is a multi-line comment
spanning multiple lines */

Key Features of JavaScript


Here are some key features of JavaScript that make it a powerful language for web
development:
 Client-Side Scripting: JavaScript runs on the user's browser, so has a faster response
time without needing to communicate with the server.
 Versatile: Can be used for a wide range of tasks, from simple calculations to complex
server-side applications.
 Event-Driven: Responds to user actions (clicks, keystrokes) in real-time.
 Asynchronous: It can handle tasks like fetching data from servers without freezing the
user interface.
 Rich Ecosystem: There are numerous libraries and frameworks built on JavaScript,
such as React, Angular, and Vue.js, which make development faster and more efficient.

Client Side and Server Side nature of JavaScript

JavaScript's flexibility extends to both the client-side and server-side, allowing developers
to create complete web applications. Here’s how it functions in each environment:
Client-Side:
 Involves
controlling the
browser and its
DOM (Document
Object Model).
 Handles user
events like clicks
and form inputs.
 Common libraries
include
AngularJS,
ReactJS, and
VueJS.
Server-Side:
 Involves interacting with databases, manipulating files, and generating responses.
 Node.js and frameworks like Express.js are widely used for server-side JavaScript,
enabling full-stack development.

Limitations of JavaScript
 Security Risks : Can be used for attacks like Cross-Site Scripting (XSS), where
malicious scripts are injected into a website to steal data by exploiting elements like
<img>, <object>, or <script> tags.
 Performance : Slower than traditional languages for complex tasks, but for simple
tasks in a browser, performance is usually not a major issue.
 Complexity : To write advanced JavaScript, programmers need to understand core
programming concepts, objects, and both client- and server-side scripting, which can be
challenging.
 Weak Error Handling and Type Checking : Weakly typed, meaning variables don’t
require explicit types. This can lead to issues as type checking is not strictly enforced.
JavaScript Versions

Version Year Key Features

ES5 2009 strict mode, JSON, getters/setters

ES6 2015 let/const, classes, arrow functions

ES7-ES13 2016-2022 async/await, BigInt, optional chaining

ES14 2023 toSorted, findLast, static blocks

VARIABLES AND DATATYPES IN JAVASCRIPT

Variables and data types are foundational concepts in programming,


serving as the building blocks for storing and manipulating information within a
program
Variables
A variable is like a container that holds data that can be reused or updated later in
the program. In JavaScript, variables are declared using the keywords var, let,
or const.

1. var Keyword

The var keyword is used to declare a variable. It has a function-scoped or


globally-scoped behaviour.

var n = 5;
console.log(n);

var n = 20; // reassigning is allowed


console.log(n);

Output
5
20
2. let Keyword

The let keyword is introduced in ES6, has block scope and cannot be re-declared in
the same scope.

let n= 10;
n = 20; // Value can be updated
// let n = 15; //can not redeclare
console.log(n)

Output
20
const Keyword

The const keyword declares variables that cannot be reassigned. It's block-scoped
as well.

const n = 100;
// n = 200; This will throw an error
console.log(n)

Output
100

DATA TYPES
JavaScript supports various datatypes, which can be broadly categorized into primitive and
non-primitive types.

1. PRIMITIVE DATATYPES

Primitive datatypes represent single values and are immutable.

1. Number: Represents numeric values (integers and decimals).

let n = 42;
let pi = 3.14;

2. String: Represents text enclosed in single or double quotes.

let s = "Hello, World!";

3. Boolean: Represents a logical value (true or false).

let bool= true;

4. Undefined: A variable that has been declared but not assigned a value.

let notAssigned;
console.log(notAssigned);
Output
undefined

5. Null: Represents an intentional absence of any value.

let empty = null;

6. Symbol: Represents unique and immutable values, often used as object keys.

let sym = Symbol('unique');

7. BigInt: Represents integers larger than Number.MAX_SAFE_INTEGER.

let bigNumber = 123456789012345678901234567890n;

2. NON-PRIMITIVE DATATYPES

Non-primitive types are objects and can store collections of data or more complex entities.

1. Object: Represents key-value pairs.

let obj = {
name: "Amit",
age: 25
};

2. Array: Represents an ordered list of values.

let a = ["red", "green", "blue"];

3. Function: Represents reusable blocks of code.

function fun() {
console.log("GeeksforGeeks");
}

Exploring JavaScript Datatypes and Variables: Understanding Common Expressions

 console.log(null === undefined)


 Expression: null === undefined
 Result: false

In JavaScript, both null and undefined represent "empty" values but are
distinct types. null is a special object representing the intentional absence of a
value, while undefined signifies that a variable has been declared but not
assigned a value. Despite their similar purpose, they are not strictly equal (===)
to each other.
null === undefined evaluates to false because JavaScript does not perform type
coercion with ===.

 console.log(5 > 3 > 2)

 Expression: 5 > 3 > 2


 Result: false

At first glance, this expression may appear to be checking if 5 is greater than


3 and 3 is greater than 2, but JavaScript evaluates it left-to-right due to its
operator precedence.
 First, 5 > 3 evaluates to true.
 Then, true > 2 is evaluated, which in JavaScript results in 1 > 2 (since true is
coerced to 1), which evaluates to false.
So, 5 > 3 > 2 evaluates to false.
 console.log([] === [])
 Expression: [] === []
 Result: false

In JavaScript, arrays are objects. Even if two arrays have the same content, they are still
different objects in memory.
When compare two arrays with ===, are comparing their references, not their contents.
Since [] and [] are different instances in memory, the result is false.

JAVASCRIPT ARRAYS
In JavaScript, an array is an ordered list of values. Each value, known as an
element, is assigned a numeric position in the array called its index. The indexing
starts at 0, so the first element is at position 0, the second at position 1, and so on.
Arrays can hold any type of data—such as numbers, strings, objects, or even
other arrays—making them a flexible and essential part of JavaScript
programming.
 Create Array using Literal

Creating an array using array literal involves using square brackets [] to


define and initialize the array.
// Creating an Empty Array
let a = [];
console.log(a);

// Creating an Array and Initializing with Values


let b = [10, 20, 30];
console.log(b);

Output
[]
[ 10, 20, 30 ]
 Create using new Keyword (Constructor)

The "Array Constructor" refers to a method of creating arrays by invoking


the Array constructor function.
// Creating and Initializing an array with values
let a = new Array(10, 20, 30);

console.log(a);
Output
[ 10, 20, 30 ]
BASIC OPERATIONS ON JAVASCRIPT ARRAYS

 Accessing Elements of an Array

Any element in the array can be accessed using the index


number. The index in the arrays starts with 0.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Accessing Array Elements


console.log(a[0]);
console.log(a[1]);

Output
HTML
CSS

 Accessing the First Element of an Array

The array indexing starts from 0, so we can access first element of


array using the index number.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Accessing First Array Elements


let fst = a[0];

console.log("First Item: ", fst);

Output
First Item: HTML
 Accessing the Last Element of an Array

We can access the last array element using [array.length - 1] index


number.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];

// Accessing Last Array Elements


let lst = a[a.length - 1];

console.log("First Item: ", lst);

Output
First Item: JS

 Modifying the Array Elements

Elements in an array can be modified by assigning a new value to their


corresponding index.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
console.log(a);

a[1]= "Bootstrap";
console.log(a);

Output
[ 'HTML', 'CSS', 'JS' ]
[ 'HTML', 'Bootstrap', 'JS' ]

 Adding Elements to the Array

Elements can be added to the array using methods


like push() and unshift().
 The push() method add the element to the end of the array.
 The unshift() method add the element to the starting of the array.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Add Element to the end of Array


a.push("Node.js");

// Add Element to the beginning


a.unshift("Web Development");

console.log(a);

Output
[ 'Web Development', 'HTML', 'CSS', 'JS', 'Node.js' ]

 Removing Elements from an Array

To remove the elements from an array we have different methods


like pop(), shift(), or splice().

 The pop() method removes an element from the last index of the array.
 The shift() method removes the element from the first index of the array.
 The splice() method removes or replaces the element from the array.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];
console.log("Original Array: " + a);

// Removes and returns the last element


let lst = a.pop();
console.log("After Removing the last: " + a);

// Removes and returns the first element


let fst = a.shift();
console.log("After Removing the First: " + a);

// Removes 2 elements starting from index 1


a.splice(1, 2);
console.log("After Removing 2 elements starting from index 1: " + a);

Output
Original Array: HTML,CSS,JS
After Removing the last: HTML,CSS
After Removing the First: CSS
After Removing 2 elements starting from index 1: CSS

 Array Length
We can get the length of the array using the array length property .
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];

let len = a.length;

console.log("Array Length: " + len);

Output
Array Length: 3

 Increase and Decrease the Array Length


We can increase and decrease the array length using the JavaScript length
property.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"]

// Increase the array length to 7


a.length = 7;

console.log("After Increasing Length: ", a);

// Decrease the array length to 2


a.length = 2;
console.log("After Decreasing Length: ", a)

Output
After Increasing Length: [ 'HTML', 'CSS', 'JS', <4 empty items> ]
After Decreasing Length: [ 'HTML', 'CSS' ]

 Iterating Through Array Elements


We can iterate array and access array elements using for loop and forEach
loop.
Example: It is an example of for loop.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];
// Iterating through for loop
for (let i = 0; i < a.length; i++) {
console.log(a[i])
}

Output
HTML
CSS
JS
Example: It is the example of Array.forEach() loop.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Iterating through forEach loop


a.forEach(function myfunc(x) {
console.log(x);
});

Output
HTML
CSS
JS
 Array Concatenation
Combine two or more arrays using the concat() method. It returns new array
containing joined arrays elements.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS", "React"];
let b = ["Node.js", "Expess.js"];

// Concatenate both arrays


let concateArray = a.concat(b);

console.log("Concatenated Array: ", concateArray);

Output
Concatenated Array: [ 'HTML', 'CSS', 'JS', 'React', 'Node.js',
'Expess.js' ]
 Conversion of an Array to String
We have a builtin method toString() to converts an array to a string.

// Creating an Array and Initializing with Values


let a = ["HTML", "CSS", "JS"];

// Convert array ot String


console.log(a.toString());

Output
HTML,CSS,JS

 Check the Type of an Arrays


The JavaScript typeof operator is used ot check the type of an array. It returns
"object" for arrays.
// Creating an Array and Initializing with Values
let a = ["HTML", "CSS", "JS"];

// Check type of array


console.log(typeof a);

Output
object

JAVASCCRIPT STRINGS

A JavaScript String is a sequence of characters, typically used to represent text.


 In JavaScript, there is no character type (Similar to Python and different from
C, C++ and Java), so a single character string is used when we need a
character.
 Like Java and Python, strings in JavaScript are immutable .

 Create using Literals


We can either use a single quote or a double quote to create a string.
We can use either of the two, but it is recommended to be consistent
with your choice throughout your code.
// Using Single Quote
let s1 = 'abcd';
console.log(s1);

// Using Double Quote


let s2 = "abcd";
console.log(s2);

Output
abcd
abcd
 Create using Constructor
The new String() constructor creates a string object instead of a
primitive string. It is generally not recommended because it can
cause unexpected behavior in comparisons
let s = new String('abcd');
console.log(s);

Output
[String: 'abcd']
 Template Literals (String Interpolation)
create strings using Template Literals. Template literals allow you to
embed expressions within backticks (`) for dynamic string creation,
making it more readable and versatile.
let s1 = 'gfg';
let s2 = `You are learning from ${s1}`;

console.log(s2);

Output
You are learning from gfg
 Empty String
create an empty string by assigning either single or double quotes
with no characters in between.
let s1 = '';
let s2 = "";

console.log(s1);
console.log(s2);

Output
Since the strings are empty, console.log will print two blank lines.

 Multiline Strings (ES6 and later)


create a multiline string using backticks (``) with template literals. The
backticks allows you to span the string across multiple lines, preserving
the line breaks within the string.

let s = `
This is a
multiline
string`;

console.log(s);

Output
This is a
multiline
string

Basic Operations on JavaScript Strings

1. Finding the length of a String


find the length of a string using the length property.
let s = 'JavaScript';
let len = s.length;

console.log("String Length: " + len);

Output
String Length: 10
2. String Concatenation

combine two or more strings using + Operator.


let s1 = 'Java';
let s2 = 'Script';
let res = s1 + s2;

console.log("Concatenated String: " + res);


Output
Concatenated String: JavaScript
3. Escape Characters
We can use escape characters in string to add single quotes, dual quotes,
and backslash.
\' - Inserts a single quote
\" - Inserts a double quote
\\ - Inserts a backslash
const s1 = "\'GfG\' is a learning portal";
const s2 = "\"GfG\" is a learning portal";
const s3 = "\\GfG\\ is a learning portal";

console.log(s1);
console.log(s2);
console.log(s3);

Output
'GfG' is a learning portal
"GfG" is a learning portal
\GfG\ is a learning portal
4. Breaking Long Strings
Using a backslash (\) to break a long string is not recommended, as it is not
supported in strict mode. Instead, use template literals or string concatenation.
const s = "'GeeksforGeeks' is \
a learning portal";

console.log(s);

Output
'GeeksforGeeks' is a learning portal
Note: This method might not be supported on all browsers. A better way to
break a string is by using the string addition.
const s = "'GeeksforGeeks' is a"
+ " learning portal";

console.log(s);

Output
'GeeksforGeeks' is a learning portal
5. Find Substring of a String
We can extract a portion of a string using the substring() method.
let s1 = 'JavaScript Tutorial';
let s2 = s1.substring(0, 10);

console.log(s2);

Output
JavaScript
6. Convert String to Uppercase and Lowercase
Convert a string to uppercase and lowercase
using toUpperCase() and toLowerCase() methods.
let s = 'JavaScript';
let uCase = s.toUpperCase();
let lCase = s.toLowerCase();

console.log(uCase);
console.log(lCase);

Output
JAVASCRIPT
javascript
7. String Search in JavaScript
Find the first index of a substring within a string using indexOf() method.
let s1 = 'def abc abc';
let i = s1.indexOf('abc');

console.log(i);

Output
4
8. String Replace in JavaScript
Replace occurrences of a substring using the replace() method. By default,
replace() only replaces the first occurrence. To replace all occurrences, use a
regular expression with the g flag.
let s1 = 'Learn HTML at GfG and HTML is useful';
let s2 = s1.replace(/HTML/g, 'JavaScript');

console.log(s2);
Output
Learn JavaScript at GfG and JavaScript is useful
9. Trimming Whitespace from String
Remove leading and trailing whitespaces using trim() method.
let s1 = ' Learn JavaScript ';
let s2 = s1.trim();

console.log(s2);

Output
Learn JavaScript
10. Access Characters from String
Access individual characters in a string using bracket notation and charAt()
method.
let s1 = 'Learn JavaScript';
let s2 = s1[6];
console.log(s2);

s2 = s1.charAt(6);
console.log(s2);

Output
J
J
11. String Comparison in JavaScript
There are some inbuilt methods that can be used to compare strings such as the
equality operator and another like localeCompare() method .
let s1 = "Ajay"
let s2 = new String("Ajay");

console.log(s1 == s2); // true (type coercion)


console.log(s1 === s2); // false (strict comparison)
console.log(s1.localeCompare(s2)); // 0 (means they are equal
lexicographically)

Output
true
false
0
Note: The equality operator (==) may return true when comparing a string
object with a primitive string due to type coercion. However, === (strict
equality) returns false because objects and primitives are different types. The
localeCompare() method compares strings lexicographically.
12. Passing JavaScript String as Objects
We can create a JavaScript string using the new keyword.
const str = new String("HAI");

console.log(str);

Output
[String: 'HAI']
Are the strings created by the new keyword is same as normal strings?
No, the string created by the new keyword is an object and is not the same as
normal strings.
const str1 = new String("GeeksforGeeks");
const str2 = "GeeksforGeeks";

console.log(str1 == str2);
console.log(str1 === str2);

Output
true
false

JAVASCRIPT OBJECTS

An object in JavaScript is a data structure used to store related data


collections. It stores data as key-value pairs, where each key is a unique
identifier for the associated value. Objects are dynamic, which means the
properties can be added, modified, or deleted at runtime.
There are two primary ways to create an object in JavaScript: Object
Literal and Object Constructor.
1. Creation Using Object Literal

The object literal syntax allows you to define and initialize an object with
curly braces {}, setting properties as key-value pairs.
let obj = {
name: "Sourav",
age: 23,
job: "Developer"
};
console.log(obj);

Output
{ name: 'Sourav', age: 23, job: 'Developer' }

2. Creation Using new Object() Constructor


let obj = new Object();
obj.name= "Sourav",
obj.age= 23,
obj.job= "Developer"

console.log(obj);

Output
{ name: 'Sourav', age: 23, job: 'Developer' }

Basic Operations on JavaScript Objects

1. Accessing Object Properties


You can access an object’s properties using either dot notation or bracket
notation
let obj = { name: "Sourav", age: 23 };

// Using Dot Notation


console.log(obj.name);

// Using Bracket Notation


console.log(obj["age"]);

Output
Sourav
23

2. Modifying Object Properties

Properties in an object can be modified by reassigning their values.


let obj = { name: "Sourav", age: 22 };
console.log(obj);

obj.age = 23;
console.log(obj);

Output
{ name: 'Sourav', age: 22 }
{ name: 'Sourav', age: 23 }

3. Adding Properties to an Object

You can dynamically add new properties to an object using dot or bracket
notation.

let obj = { model: "Tesla" };


obj.color = "Red";

console.log(obj);

Output
{ model: 'Tesla', color: 'Red' }

4. Removing Properties from an Object


The delete operator removes properties from an object.
let obj = { model: "Tesla", color: "Red" };
delete obj.color;

console.log(obj);

Output
{ model: 'Tesla' }

5. Checking if a Property Exists


You can check if an object has a property using the in operator
or hasOwnProperty() method.
let obj = { model: "Tesla" };
console.log("color" in obj);
console.log(obj.hasOwnProperty("model"));

Output
false
true

6. Iterating Through Object Properties


Use for...in loop to iterate through the properties of an object.
let obj = { name: "Sourav", age: 23 };
for (let key in obj) {
console.log(key + ": " + obj[key]);
}

Output
name: Sourav
age: 23

7. Merging Objects
Objects can be merged using Object.assign() or the spread syntax
{ ...obj1, ...obj2 }.
let obj1 = { name: "Sourav" };
let obj2 = { age: 23};

let obj3 = { ...obj1, ...obj2 };


console.log(obj3);

Output
{ name: 'Sourav', age: 23 }
8. Object Length
You can find the number of properties in an object using Object.keys().
let obj = { name: "Sourav", age: 23 };
console.log(Object.keys(obj).length);

Output
2

Recognizing a JavaScript Object


To check if a value is an object, use typeof and verify it's not null.
let obj = { name: "Sourav" };
console.log(typeof obj === "object" && obj !== null);

Output
true

Key Differences Between {} and new Object()


new Object() (Object
Feature {} (Object Literal) Constructor)

More concise and


Ease of Use Less commonly used.
readable.

Slightly slower due to the


Performance Faster and more efficient.
constructor call.

Prototypal Directly inherits from Same, but adds an extra


Inheritance Object.prototype. layer of abstraction.

Literal syntax is sufficient Useful only in rare


Customization
for most use cases. scenarios.
Functions in JavaScript


Functions in JavaScript are reusable blocks of code designed to perform


specific tasks. They allow you to organize, reuse, and modularize code. It
can take inputs, perform actions, and return outputs.
function sum(x, y) {
return x + y;
}
console.log(sum(6, 9)); // output: 15
Function Syntax and Working
A function definition is sometimes also termed a function declaration or
function statement. Below are the rules for creating a function in
JavaScript:
 Begin with the keyword function Keyword
 A user-defined function name (In the above example, the name is sum)
 A list of parameters enclosed within parentheses and separated by
commas (In the above example, parameters are x and y)
 A list of statements composing the body of the function enclosed within
curly braces {} (In the above example, the statement is "return x + y").
Return Statement
A function can return a result using the return keyword. This is optional but
useful when you want to send data back from the function.
Function Parameters
Parameters are input passed to a function. In the above example, sum(x ,
y) takes two parameters, x and y.
Calling Functions
After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by
the value of parameters enclosed between the parenthesis.
// Function Definition
function welcomeMsg(name) {
return ("Hello " + name + " welcome ");
}

let nameVal = "User";

// calling the function


console.log(welcomeMsg(nameVal));

Output
Hello User welcome

Why Functions
 Functions can be used multiple times, reducing redundancy.
 Break down complex problems into manageable pieces.
 Manage complexity by hiding implementation details.
 Can call themselves to solve problems recursively.
Function Invocation
The function code you have written will be executed whenever it is called.
 Triggered by an event (e.g., a button click by a user).
 When explicitly called from JavaScript code.
 Automatically executed, such as in self-invoking functions.
Function Expression
It is similar to a function declaration without the function name. Function
expressions can be stored in a variable assignment.
Syntax:
let geeksforGeeks= function (paramA, paramB) {

// Set of statements
}
const mul = function (x, y) {
return x * y;
};
console.log(mul(4, 5));

Output
20

Arrow Functions
Arrow functions are a concise syntax for writing functions, introduced
in ES6, and they do not bind their own this context.
Syntax:
let function_name = (argument1, argument2 ,..) => expression
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];

const a2 = a.map(function (s) {


return s.length;
});

console.log("Normal way ", a2);

const a3 = a.map((s) => s.length);

console.log("Using Arrow Function ", a3);

Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]

Immediately Invoked Function Expression (IIFE)


IIFE functions are executed immediately after their definition. They are
often used to create isolated scopes.
(function () {
console.log("This runs immediately!");
})();

Output
This runs immediately!

Callback Functions
A callback function is passed as an argument to another function and is
executed after the completion of that function.
function num(n, callback) {
return callback(n);
}

const double = (n) => n * 2;

console.log(num(5, double));

Output
10

Anonymous Functions
Anonymous functions are functions without a name. They are often used as
arguments to other functions.
setTimeout(function () {
console.log("Anonymous function executed!");
}, 1000);
Nested Functions
Functions defined within other functions are called nested functions. They
have access to the variables of their parent function.
function outerFun(a) {
function innerFun(b) {
return a + b;
}
return innerFun;
}
const addTen = outerFun(10);
console.log(addTen(5));

Output
15

Pure Functions
Pure functions return the same output for the same inputs and do not
produce side effects. They do not modify state outside their scope, such as
modifying global variables, changing the state of objects passed as
arguments, or performing I/O operations.
function pureAdd(a, b) {
return a + b;
}

console.log(pureAdd(2, 3));

Output
5

Characteristics of Functions
 Parameters vs Arguments: Parameters are placeholders for function
and arguments are actual value for those placeholders.
 Return Values: Functions can return a value using the return keyword.
 Default Parameters: Default values can be assigned to function
parameters.

JavaScript Loops


Loops in JavaScript are used to reduce repetitive tasks by repeatedly


executing a block of code as long as a specified condition is true. This
makes code more concise and efficient.
Suppose we want to print 'Hello World' five times. Instead of manually
writing the print statement repeatedly, we can use a loop to automate the
task and execute it based on the given condition.

for (let i = 0; i < 5; i++) {


console.log("Hello World!");
}

Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

1. JavaScript for Loop


The for loop repeats a block of code a specific number of times. It contains
initialization, condition, and increment/decrement in one line.
Syntax
for (initialization; condition; increment/decrement) {
// Code to execute
}

for (let i = 1; i <= 3; i++) {


console.log("Count:", i);
}

Output
Count: 1
Count: 2
Count: 3
In this example
 Initializes the counter variable (let i = 1).
 Tests the condition (i <= 3); runs while true.
 Executes the loop body and increments the counter (i++).
2. JavaScript while Loop
The while loop executes as long as the condition is true. It can be thought
of as a repeating if statement.
Syntax
while (condition) {
// Code to execute
}

let i = 0;
while (i < 3) {
console.log("Number:", i);
i++;
}

Output
Number: 0
Number: 1
Number: 2
In this example
 Initializes the variable (let i = 0).
 Runs the loop body while the condition (i < 3) is true.
 Increments the counter after each iteration (i++).
3. JavaScript do-while Loop
The do-while loop is similar to while loop except it executes the code block
at least once before checking the condition.
Syntax
do {
// Code to execute
} while (condition);
let i = 0;
do {
console.log("Iteration:", i);
i++;
} while (i < 3);

Output
Iteration: 0
Iteration: 1
Iteration: 2
In this example:
 Executes the code block first.
 Checks the condition (i < 3) after each iteration.

3. JavaScript for-in Loop

The for...in loop is used to iterate over the properties of an object. It only
iterate over keys of an object which have their enumerable property set to
“true”.
Syntax
for (let key in object) {
// Code to execute
}
const obj = { name: "Ashish", age: 25 };
for (let key in obj) {
console.log(key, ":", obj[key]);
}

Output
name : Ashish
age : 25
In this example:
 Iterates over the keys of the person object.
 Accesses both keys and values.
5. JavaScript for-of Loop
The for...of loop is used to iterate over iterable objects like arrays, strings,
or sets. It directly iterate the value and has more concise syntax than for
loop.
Syntax
for (let value of iterable) {
// Code to execute
}
let a = [1, 2, 3, 4, 5];
for (let val of a) {
console.log(val);
}

Output
1
2
3
4
5
 Use for loop when the number of iterations is known.
 Use while loop when the condition depends on dynamic factors.
 Use do-while loop to ensure the block executes at least once.
 Use for...in loop to iterate over object properties.
 Use for...of loop for iterating through iterable objects.

You might also like