Unit I FSD Notes
Unit I FSD Notes
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.
<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.
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 */
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
1. var Keyword
var n = 5;
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
let n = 42;
let pi = 3.14;
4. Undefined: A variable that has been declared but not assigned a value.
let notAssigned;
console.log(notAssigned);
Output
undefined
6. Symbol: Represents unique and immutable values, often used as object keys.
2. NON-PRIMITIVE DATATYPES
Non-primitive types are objects and can store collections of data or more complex entities.
let obj = {
name: "Amit",
age: 25
};
function fun() {
console.log("GeeksforGeeks");
}
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 ===.
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
Output
[]
[ 10, 20, 30 ]
Create using new Keyword (Constructor)
console.log(a);
Output
[ 10, 20, 30 ]
BASIC OPERATIONS ON JAVASCRIPT ARRAYS
Output
HTML
CSS
Output
First Item: HTML
Accessing the Last Element of an Array
Output
First Item: JS
a[1]= "Bootstrap";
console.log(a);
Output
[ 'HTML', 'CSS', 'JS' ]
[ 'HTML', 'Bootstrap', 'JS' ]
console.log(a);
Output
[ 'Web Development', 'HTML', 'CSS', 'JS', 'Node.js' ]
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.
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"];
Output
Array Length: 3
Output
After Increasing Length: [ 'HTML', 'CSS', 'JS', <4 empty items> ]
After Decreasing Length: [ 'HTML', 'CSS' ]
Output
HTML
CSS
JS
Example: It is the example of Array.forEach() loop.
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"];
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.
Output
HTML,CSS,JS
Output
object
JAVASCCRIPT STRINGS
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.
let s = `
This is a
multiline
string`;
console.log(s);
Output
This is a
multiline
string
Output
String Length: 10
2. String Concatenation
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");
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
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' }
console.log(obj);
Output
{ name: 'Sourav', age: 23, job: 'Developer' }
Output
Sourav
23
obj.age = 23;
console.log(obj);
Output
{ name: 'Sourav', age: 22 }
{ name: 'Sourav', age: 23 }
You can dynamically add new properties to an object using dot or bracket
notation.
console.log(obj);
Output
{ model: 'Tesla', color: 'Red' }
console.log(obj);
Output
{ model: 'Tesla' }
Output
false
true
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};
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
Output
true
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"];
Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
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);
}
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
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
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.