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

JavaScript Introduction 1

The document provides a comprehensive guide on JavaScript, covering installation, variable types, declaration rules, and various operations. It explains the differences between var, let, and const, as well as string and number methods, logical operators, and function definitions. Additionally, it introduces JavaScript collections such as arrays, objects, maps, and sets, along with examples and exercises for practical understanding.

Uploaded by

maha24743
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

JavaScript Introduction 1

The document provides a comprehensive guide on JavaScript, covering installation, variable types, declaration rules, and various operations. It explains the differences between var, let, and const, as well as string and number methods, logical operators, and function definitions. Additionally, it introduces JavaScript collections such as arrays, objects, maps, and sets, along with examples and exercises for practical understanding.

Uploaded by

maha24743
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 92

Java Script

IT Industry-Academia Bridge Program


Vscode for JavaScript
Step-1:- Install Node.js (A runtime environment for JavaScript or an engine to run
JavaScript locally outside the browser)
https://nodejs.org/en
Step-2:- Create a file in VSCode with extension .js
Open VSCode terminal from VSCode => View => Terminal
Terminal > node –v //to verify, node is installed
Note: If you get the error, The term 'node' is not recognized as the name, ensure that you have closed and re-
opened all terminals or VSCode.
Step-3:- Run This command from terminal
> cd folder-name //move to folder path, where your javascript file exist.
> node file-name.js
To automatically run JavaScript code in the VSCode terminal upon saving a file, you can use the
"Code Runner" extension.
Run Code: Click on the small "Run Code" button located at the top right of the VS Code
window or use the shortcut Ctrl + Alt + N.
JavaScript
Java script is a browser programming language, which was released in
1995 by Netscape with the help of Sun microsystems for Netscape-2
browser.
It was developed to make interactive web frontend.
Who owns trademark of JS ----- Oracle
Java Script need a engine to convert code into machine language.
Every Browser has a javascript engine,

IT Industry-Academia Bridge Program


Variables Data Types
JavaScript is a dynamic language with dynamic types. Variables in
JavaScript are not directly associated with any particular value type,
and any variable can be assigned (and re-assigned) values of all types.
There are three different variable types: var , let , and const . A variable
can contain any types of data, such as a string, a number a boolean
value (true/false), an object({key: value}).
var students = [ { name: "Hannah", age: 12 }, { name: "Alex", age: 13 } ]; //Array of objects
var name = "Alexander Smith";
var grade = 82;
var passed = true;
Variables
Variable Declareation Rules
• Variable names can contain numbers, letters, underscores (_), and dollar signs ($)
• Variable names cannot contain whitespace characters
• Variable names are case sensitive. Name and name are different
• Variable names cannot contain any reserved words or reserved keywords (i.e. break,
default, function, false, let etc. )
• Variable names should not begin with numbers
• Further, if you declare a variable using the const keyword, every letter
should be in uppercase. (Although you can declare it in lower as well)
• Camel Caseing Rule: If we only have one word in our variable, every letter
should be in lowercase or writing the first word of a variable in lower case,
then capitalizing every future word in the variable.
Variable-var
The var declaration declares function-scoped var x = 1;
global variables. if (x === 1) {
var x = 2;
The value of a var can be changed through console.log(x);
reassignment using the assignment operator; }
console.log(x); //output 2 2

var x = 15;
The var can be re-declared at functional or block var x = 25;
if(x > 15){
level. let x = 20;
console.log(x);
}
console.log(x); //output 20 20
Variable-let
Syntax:- let name1 = value1;
let name1 = value1, name2 = value2;
let name1, name2 = value2;
let x = 1;
The let declaration is block-scoped local variables, value re- if (x === 1) {
assignable. let x = 2;
console.log(x); }
let declarations are scoped to blocks as well as functions. console.log(x);
Output:- 2 1
let declarations cannot be redeclared by any other declaration in
let x = 1;
the same scope. if (x === 1) {
x = 2;
console.log(x); }
console.log(x);
Output:- 2 2
Variable- const
The const declaration declares block-scoped local variables.
The value of a constant can't be changed through reassignment using
the assignment operator, but if a constant is an object, its properties
can be added, updated, or removed.
Syntax:- const name1 = value1; const name1 = value1, name2 = value2
‘const’ declaration must be initialized.

IT Industry-Academia Bridge Program


Difference var, let, const Variable
Variable Reassign Re-declare
Keyword Value Variable
Scope
var variable can be accessed throughout
our entire program, whereas const and Functio
var Yes Yes
let are declared locally within the scope n
of a certain block of code const Block No
No, in any
Block = {code} block
No, in same
Redeclaring Variables let Block yes
block
var variables can be redeclared. This means that you can create a new variable with the same name
and keep its value, or assign the variable a different value.
var value = 123
var value;
console.log( value) //output = 123 //the last variable value will prevail.
Variables
- In javascript, variable data type can be primitive(immutable- which
canot modified) or object
- Primitives are number, string, boolean, null, undefined, etc.
- A number data-type can be decimal/binary/octal/hexadecimal
- A boolean type is recognize by decision output as 6>7 = true
- A variable without any value has undefined type.
- A variable without any value can be assigned as null.
let a = null
- You can find the type of a variable by
console.log(typeof(num))
IT Industry-Academia Bridge Program
Variable Type Conversion &
Operations
String(number): This will convert number into string.
Number(string): This will convert string into number.
Boolean(number): This will return true.
Boolean(!number): This will return false.
JavaScript use triple equal sign for comparison as a===b and a!==b for
not equal.

IT Industry-Academia Bridge Program


String And String Methods
String can be present by single colon‘’ or double colon “”. With single colon, you
can use multiple line, which is not allowed in double colon.
Use the {$} sign to get a value from a variable in string as ‘Your nam is ${name}’
• str.length
• str.toUpperCase()
• str.toLowerCase()
• str.replace(first match of x, with y) // replace(“school”, “collage”)
• str.concat(str1,str2,…) //same as adding string(+)
• str.split(“seperator”) //converts strings to an array
• str.includes(“value”) //retrun true if value is available in str
• str.startsWith(“value”) // return true if str start with value
• str.endsWith(“value”) //return true if str ends with value
IT Industry-Academia Bridge Program
String and String Methods
str1.indexOf(str2); // indexOf() method checks if str2 is found within str1 and
returns the index of the first occurrence. If str2 is not found in str1, indexOf will
return -1.

IT Industry-Academia Bridge Program


Numbers Methods
Num.toFixed(numOfDecimalPlaces)
let price = 2.3433
price.toFixed(2) = > 2.34
Number(value To Convert To Number)
let price = “34.5”
Number(price) =>34.5
num.toString() //convert num to string
let price = 3.4
price.toString(price) => 3.4
parseInt(val) // returns whole number
let price 3.4445
parseInt(price) => 3
IT Industry-Academia Bridge Program
Math Class
JavaScript use the Math class to perform arithmetic function like power,
max or min: Math.pow(x,y)
Math.random
Math.random() // generate number between 0(inclusive) to
1(exclusive)
Math.random() * 10 // between 0(in) to 10 (ex): 0-9
Math.random() * 11 // between 0(in) to 11 (ex): 0-10
[Math.random()* (max – min + 1)] + min

IT Industry-Academia Bridge Program


Template Literal
JavaScript use ‘+’ sign to add two strings or variables like
var str = “hello”+3

JavaScript use plus (+) sign to concatenate two string in output console.
console.log(‘Your answer of ’ + value1 + ‘ + ’ + value2 + ‘ is equal to ’ + ans);
Template literal are used to display a variable value inside a string as
console.log(‘Your answer of ${value1} + ${value2} is equal to ${ans}’);

Logical Operators
&& for logical and
|| for logical or
! For logical not
- Escape charater “ \n” for next line, “ \t” for tab space
Ternary Operators
The conditional (ternary) operator takes three operands:
• a condition followed by a question mark (?),
• then an expression to execute if the condition is truthy followed by a colon (:),
• finally the expression to execute if the condition is falsy.
condition ? exprIfTrue : exprIfFalse
This operator is frequently used as an alternative to an if…else statement.
const age = 26;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage);
Use of double condition(if – else if - else)
Let z = ( x < y ) ? “less”: (x === y) ? “equal” : “bigger”
IT Industry-Academia Bridge Program
Function
A JavaScript function is defined with the function keyword, followed by
a name, followed by parentheses ().
function multiply(a, b = 1) {
return a * b;
}
multiply(5);
Function in JavaScript can be declared as
Þfunction functionName() {} //named function
Þconst functionName = function(){} //anonymous function
Þconst functionName = () =>{} //arrow function

IT Industry-Academia Bridge Program


Named Function
In JavaScript, you can declare a normal function using the keyword
function before function declaration.
function map(f, a) { const f = function (x) {
const result = new Array(a.length); return x * x * x;
for (let i = 0; i < a.length; i++) { };
result[i] = f(a[i]);
}
return result;
}
const numbers = [0, 1, 2, 5, 10];
const cube = map(f, numbers);
console.log(cube);

IT Industry-Academia Bridge Program


Anonymous Function
Anonymous, meaning the function has no name. Function expressions
are usually assigned to a variable, and can be anonymous, meaning the
function has no name. console.log(cal(5,6));
function cal(a,b) {
return a+b;
}

Normally function declarations load into the execution context before


any code runs. This is known const
as hoisting, meaning you can use the
cal = function (a, b) {
function before you declare it. return a + b
}
console.log(cal(5,6))

Attempting to execute the anonymous function before it is declared will


result in an error:
Arrow Function
Arrow functions are a way to write anonymous function expressions
and its body consist on single line without using curly braces and
‘return’ keyword.
function isEven(num) {
return num % 2 == 0 let isEven = (num) => num % 2 == 0
} console.log(isEven(45))
console.log(isEven(90))

Arrow functions automatically/implicit return the value of the


expression without needing the return keyword. It is normally used as a
callbacks in function like ‘map’, ‘filter’, and ‘forEach’

IT Industry-Academia Bridge Program


Arrow Function
Its expressions are represented by an equals sign followed by a greater than
sign: =>
const multiply = (x, y) => {
return x * y;
}
console.log(multiply(30, 4)) ;

In the case of only one parameter, the parentheses can be excluded.


const square = x => { return x * x; }
console.log(5);

The function body can consist on multiple lines or single line. If the function
is only a single line return, both the curly brackets and the return statement
can be omitted, const square = x => x * x; // Invoke function to find product
console.log(square(10));
Exercise
Write a JavaScript program to add "JS" in front of a given string.
JavaScript program to count the number of vowels in a given string.
JavaScript program to reverse a given string.
JavaScript program to find the maximum of two numbers.
JavaScript program to calculate the factorial of a number.
JavaScript program to find the length of the longest word in a
sentence.
JavaScript program to check if a given number is even or odd.
JavaScript program to calculate the factorial of a number.
Exercise
• Write a JavaScript program that takes a year as input and determines
whether it is a leap year or not. A leap year is divisible by 4 but not
divisible by 100 unless it is also divisible by 400. The program should
output "Leap year" if the input year is a leap year, otherwise, it should
output "Not a leap year".

• Write a JavaScript program that takes a number as input and


determines whether it is a prime number or not. A prime number is a
natural number greater than 1 that has no positive divisors other than
1 and itself. The program should output "Prime" if the input number is
prime, otherwise, it should output "Not prime".
Exercise
Write a JavaScript program to create a new string adding “JS” in front of
a given string. If the given string begins with “JS” then return the
original string.
(hint:- str.startWith())
Write a JavaScript program that takes a number as input and finds its
reverse. The reverse of a number is obtained by reversing the order of
its digits. The program should output the reverse of the input number.
hint:- numberString.split('').reverse().join('');
You can also use number.toString(number) & parseInt(string)

IT Industry-Academia Bridge Program


Collection in JavaScript

IT Industry-Academia Bridge Program


JavaScript Collection
A collection refers to data structures that allow you to store and manage
multiple values, often as key-value pairs or as lists of items.
JavaScript provides three main types of collection objects:
• Arrays
• Objects
• Maps
• Sets
An Array is an ordered collection of values, where each value is identified by
an index.
A Map is a collection of key-value pairs where both the keys and values can
be of any type (objects, functions, primitives).
A Set is a collection of unique values (no duplicates allowed).
Object
const presonObj = {
name: “Ali”
}
Array
const colors = [“red”, “blue”]

IT Industry-Academia Bridge Program


Array
JavaScript array is an object that represents a collection of similar/multiple type of
elements. It is a collection of multiple items under a single variable name.
let mixedArray = [42, "Hello", true, { name: "John" }, [1, 2, 3]];
There are 3 ways to construct array in JavaScript
• By array literal:-
var arrayname=[value1,value2.....valueN];
OR
var arrayname = [];
arrayname[0] = 5;
• By creating instance of Array directly (using new keyword)
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
• By using an Array constructor (using new keyword)
var emp=new Array("Jai","Vijay","Smith");
Array
Arrays Characteristics
• Array declare in square parentheses [ ]
• Resizable and contain a mix of different data types.
• Start from zero-Indexed
• Can contain different data type
var array1 = ['hello',3,4,5, {value1:'valuable', number: 5}];
• array-copy operation create a shallow copies (new array)
Methods
concat() / copyWithin() / every() / filter() / flat() / flatMap() / forEach() /
indexOf() / map() / reverse() / reduce() / splice() / sort()
Arrays Common Methods
Example:- Swapping Example:- Push / Pop / Shift / Unshift
Let a = 5; Let data = [5,6,7,8];
Let b = 6; data.push(2); //[5,6,7,8,2] add in last
[a,b] = [b,a] // swap the value data.pop(); //[5,6,7,8] last out
data.shift(); //[6,7,8] first out
Example:- Assign Variables data.unshift(2) //[2,6,7,8] add in first
let num = [5,4,3,2];
let [a,b,c,d] = num; array.length // display length of array
console.log(d); Array.isArray(variable) //display ture if variable type is array

Example:- Split
let words = “My Name is Naveed”.split(‘ ’);
console.log(words); // [‘My’, ‘Name’, ‘is’, ‘Naveed’]
let [a,b,c,d,e] = words;
console.log(a, b); // My Name
Let [a,b,, …d] = words;
Console.log(a,b,d); // a = My, b = Name d = is Naveed
Array Common Methods
const array1 = [“BMW”, “Toyta”, “Honda”, “Suzuki”]

Console.log(array1.concat(arr2, arr3)) //array1 will concat with arr2 and arr3


console.log(array1.join(“”)) //array1 elements separate with
sapce.
console.log(array1.join(“-”)) //array1 elements separate with “-”
console.log(array1.include(“BMW”)) // return true if array1 has BMW
console.log(array1.include(“Toyta”, 3)) // second parameter for position,
therefore if at position 3, Toyta do not exist, the return value should be false.
console.log(array1.slice(2)) //This will cut the first two elements from array
console.log(array1.slice(0,2) //This will cut 2 array element start from 0.
Array Method - Splice
The splice() method in JavaScript can remove, add, and replace elements
in an array. It consist on three arguments
array.splice(start, deleteCount, item1, item2, ...);
• start: The index at which to start changing the array.
• deleteCount: The number of elements to remove from the array (optional).
• item1, item2, ...: The items to add to the array (optional).
Assume:- let array = ['a', 'b', 'c', 'd', 'e'];
• Removing Elements:-
let removed = array.splice(2, 2); // Remove 2 elements starting from index 2
• Adding Elements:-
array.splice(2, 0, 'x', 'y'); // Add 'x' and 'y' at index 2
• Updateing/Replacing Elements:
array.splice(1, 2, 'x', 'y'); // Remove 2 elements from index 1, and add 'x' and 'y'
Array Methods – Splice
Key Points
• splice() removes elements from the array if deleteCount is greater than 0.
• It returns an array containing the elements that were removed.
• It modifies the original array in place (i.e., changes the array directly).
• splice() can add new elements if deleteCount is 0 or if you provide
additional items to insert.
Scenarios
1. Case: Task Management (Adding, Removing, and Updating Tasks)
2. Case: Shopping Cart (Adding, Removing, and Updating Items)
3. Case: Student Records (Adding, Removing, and Updating Students)
Objects
JavaScript is designed on a simple object-based paradigm. An object is a
collection of properties, and methods. A property consist on a name
(or key) and a value.
const obj = { a: 1, b: function() {return 12} }
In above object obj has two properties. The first one has "a" as the key and 1 as the value. The
second one has "b" as the key and a function as the value.

An empty object with no properties can be created like this:


const object = {};
let obj = new Object();
const a = 'foo'; const myHonda = {
You can also create object as const b = 42; color: "red",
const c = {}; wheels: 4,
const object2 = { a: a, b: b, c: c }; engine: { cylinders: 4, size: 2.2 },
console.log(object2.b); };
Retrieve & Add Object Properties
You can access and add object properties value by DOT notation or by BRACKET
notation. // Object Properties
Object Methods
const person = { const person = {
firstName: ‘abc’, firstName : “abc’”
age: 55 age:55,
} fullName: function(){
console.log(person.age); // access key value by DOT return “abc”
person.age = 25 //update key value or
console.log(person.age); return this.firstName
}
console.log(person[“age”]); //access key value by BRACKET }
person[“age”] = 55 //update key value console.log(person.fullName())
console.log(person[“age”]); //access key value console.log(person[“fullName”]())
You can also add the property in object
person.location = “UK” // Add property in object
or
person[“location”] = “USA”
console.log(person) // { firstName: ‘abc’, age:55, location: ‘USA’}
Retrieve & Add Object Properties
You can also access object value through loop as
const person = {
firstName: "Jamil",
lastName: "Ali",
age: 100
}

for(key in person) {
console.log(key)
}
You also use method “object” to access key and value of an object.
console.log(object.keys(person)) //output [‘firstName’, ‘lastName’, ‘age’]
console.log(object.values(person)) //output [‘jamil’, ‘Ali’, 100]
IT Industry-Academia Bridge Program
Object Common Methods
• Object.keys(): Returns an array of keys in an object.
console.log(Object.keys(person)); // Output: ['name', 'age', 'greet']
• Object.values(): Returns an array of values in an object.
console.log(Object.values(person)); // Output: ['Jane', 30, function]
• Object.entries(): Returns an array of key-value pairs as arrays.
console.log(Object.entries(person)); // Output: [['name', 'Jane'], ['age', 30],
['greet', function]]

IT Industry-Academia Bridge Program


Set in Javascript
A JavaScript Set is a collection of unique values as compared to arrays. You
can store any type of data like Primitive values (number, string, boolean),
objects, or functions. Here are some methods of Set…
let numbers = new Set([1, 2, 3, 3, 4, 4]);
console.log(numbers); // Output: Set { 1, 2, 3, 4 }

let nums = new Set();


To retrieve value, use forEach(); nums.add(3);
nums.add(4);
nums.add(‘Adnan’);
nums.forEach((n => {
console.log(n);
})
Set() Common Methods
new Set() Creates a new Set

add() Adds a new element to the Set

delete() Removes an element from a Set

has() Returns true if a value exists

clear() Removes all elements from a Set

forEach() Invokes a callback for each element

values() Returns an Iterator with all the values in a Set

keys() Same as values()

size (Properties) Returns the number elements in a Set


IT Industry-Academia Bridge Program
Set Scenarios
Scenario-1: You are developing a web application, and you want to
keep track of users who are currently logged in without duplicates.
Scenario-2: You are given two arrays of student IDs who have
submitted assignments and attended classes. You want to find out
which students submitted the assignment but didn’t attend class.
Scenario-3: You want to count how many unique products were sold in
a day from a list of sales transactions.
Scenario-4: You have a list of scores from a sports event, but some
scores are repeated. You want to remove duplicates and then display
the scores in ascending order.
Scenario-5: Imagine you have a list of emails entered by users, and you
want to ensure that each email is only listed once.
Set Scenarios
Scenario-6: You have two sets of students, one for a math class and
one for a science class. You want to find:
• The union of both classes (students in either class)
• The intersection (students in both classes)
• The difference (students in math class but not in science class)
Scenario-7: You're building a simple web analytics tool to track unique
visitors based on IP addresses. You want to ensure that duplicate visits
from the same IP are not counted multiple times.
Map in JavaScript
Map is a collection of elements where each element is stored as a Key, value pair. Map
object can hold objects, functions and primitive values as either key or value. Map always use
the concept of key-value pair.
You can create a JavaScript Map by:
• Passing an Array to new Map() let map = new Map()
• Create a Map and use map.set() to add value in

const fruits = new Map([ const fruits = new Map();


["apples", 500], // Set Map Values
["oranges", 200] fruits.set("apples", 500);
]); fruits.set("oranges", 200);
for(let [k,v] of fruits) forEach((k,v) => {
console.log(k, “ : ”, v); console.log(k, “ : ”, v);
})
Map key as object
const user = { id: 1, name: "John" };
const permissionsMap = new Map();
permissionsMap.set(user, "Admin");
console.log(permissionsMap.get(user)); // "Admin"
Map() Common Methods
Method Description

new Map() Creates a new Map object

set() Sets the value for a key in a Map

get() Gets the value for a key in a Map

clear() Removes all the elements from a Map

delete() Removes a Map element specified by a key

has() Returns true if a key exists in a Map

forEach() Invokes a callback for each key/value pair in a Map

entries() Returns an iterator object with the [key, value] pairs in a Map

keys() Returns an iterator object with the keys in a Map

values() Returns an iterator object of the values in a Map

size it a property and return the number of Map elements


Map Scenarios
Scenario-1: You're creating a system to store user preferences in an
application. Each user has a unique ID, and you want to store their
preferences using these IDs as keys. (hint has & size)
Scenario-2: You're managing an e-commerce site, and you need to keep
track of the available quantities of different products. You want to loop
through the product list and display available quantities.
Scenario-3: You're managing a web service and need to track the number
of API requests made by each user within a certain time period. You use a
Map to store the user's ID as the key and the number of requests as the
value.
Scenario-4: You are running an online marketplace and want to track
active sales. When a sale ends, you need to remove it from the list. The
Map allows you to easily delete items based on a key.
Map Scenarios
Scenario-5: You’re building a system that manages employee records. Each
employee has an object with detailed information, and you want to use these
objects as keys to store additional data, like their salary.
Scenario-6: You're building a text analytics tool, and you need to count how
many times each word appears in a paragraph. The Map is ideal for this
scenario because it allows you to track each word's occurrence.
Scenario-7: You are managing an online store and need to keep track of
product prices. Occasionally, prices will change, and the Map allows you to
update the prices dynamically.
Scenario-8: You are running a timed contest where you need to clear the
participant records at the end of each round. After the round ends, you can use
the Map's clear() method to remove all participants.
Scenario-9: You want to log all the keys (products) and values (prices) in a
store's inventory.
Loops in JavaScript

IT Industry-Academia Bridge Program


For…Of loop
The for..of loop in JavaScript allows you to iterate over iterable objects
(arrays, sets, maps, strings etc). For..of loop also execute for empty
elements.
Syntex:- for (variable of iterable) { // code block to be executed }
In normal for
const students = ['John', 'Sara', 'Jack'];
for(let index = 0; index > students.length; index++)
console.log(student[index])
With for..of
const students = ['John', 'Sara', 'Jack'];
for ( let element of students )
console.log(element);
For…Of loop
Best of Array, Set and Map
For Array For Set
let arr = [10, 20, 30]; let set = new Set([1, 2, 3]);

for (let value of arr) { for (let value of set) {


console.log(value); // Output: 10, 20, 30 console.log(value); // Output: 1, 2, 3
} }

For Map
For Map
let map = new Map([['a', 1], ['b', 2]]);
let map = new Map([['a', 1], ['b', 2]]);
for (let value of map) {
for (let [key, value] of map) {
console.log(value); // Output: ['a', 1], ['b', 2]
console.log(key, value); // Output: a 1, b 2
}
}
For…In Loop
The for-in loop is a basic control statement that allows you to loop
through the properties of an object. It returns the key of an object.
for (variable in object) { // statements }
Examples: var totn_colors = { primary: 'blue', secondary: 'gray', tertiary:
'white' };
for (var color in totn_colors) {
console.log( totn_colors[color]);
}

let x = [{'name': 'Ahmad', 'Age': 33},{'name': 'Noman', 'Age':


46}];
for(var y in x)
for(var z in x[y])
console.log(x[y][z]);
For…In Loop
The for..in loop in JavaScript allows you to iterate over all property keys
of an object. For..in loop do not execute for empty elements.
const salaries= { Jack : 24000, Paul : 34000, Monica : 55000 }
// using for...in
for ( let i in salaries) {
// add a currency symbol
let salary = "$" + salaries[i];
// display the values
console.log(`${i} : ${salary}`);
}
For…In Loop
for..of used to get Values from Array, Maps, Sets
for..in used to get Keys from Object
Both for…of & for…in can return or discontinued with break;
Collection Type Best Loop to Use Why
Array For…of Directly iterates over the values of the array.
Objects For…in Iterates over the properties (keys) of an object.
Maps For…of Iterates over the values or key-value pairs of the map.
Sets For…of Iterates over the unique values in the set.
Array’s Functions

IT Industry-Academia Bridge Program


forEach Method
The forEach() method calls a function for each element in an array.
array.forEach(
function(currentValue, index, array) { //Your logic here }
);
foreach execute a function once for each element through looping
• currentValue: The current element being processed in the array.
• index (optional): The index of the current element being processed.
• array (optional): The array that forEach() was called upon.
foreach do not return any value and do not implement break
const fruits = ['Apple', 'Banana', 'Orange'];
fruits.forEach(function(fruit) {
console.log(fruit);
});
forEach Method
The forEach() method is not executed for empty elements.
let num = [23,45,23,456,56]; let sum = 0;
num.forEach ((n) => { const numbers = [65, 44, 12, 4];
console.log(n); numbers.forEach(myFunction);
});
function myFunction(item) {
Let num = [1,2,3,4,5] sum += item;
Num.forEach((el, index, arr) => { }
arr[index] = el*2; //doubling each number
})
//Here el mean element , index mean element position , array mean numbers.forEach(item =>
full array console.log(sum+=item);)
Output
[2,4,6,8,10]
Key Points
• Unlike for...of or for...in, you cannot use break, continue, or return to
exit early from a forEach loop. Once it starts, it processes all items.
• It is best for Arrays and Sets

IT Industry-Academia Bridge Program


Scanrio
You work for an online e-commerce platform that sells products to customers. You are
tasked with calculating the total value of products in a user's shopping cart. The cart
contains an array of items, each with a name, price, and quantity. You need to calculate
the total cost of all items in the cart.
// Array of items in the shopping cart
const shoppingCart = [
{ name: "Laptop", price: 1000, quantity: 1 },
{ name: "Phone", price: 700, quantity: 2 },
{ name: "Headphones", price: 150, quantity: 3 },
{ name: "Smartwatch", price: 250, quantity: 1 }
];
let totalCost = 0;
shoppingCart.forEach(item => {
totalCost += item.price * item.quantity; // Multiply price by quantity and add to totalCost
});
console.log(`The total cost of the shopping cart is: $${totalCost}`);
Map Function
The Javascript map() method in JavaScript creates an array by calling a
specific function on each element present in the parent array.
const newArray = array.map(function(currentValue, index, arr) {} );

The callback function can take three arguments (currentValue, index, and
array) and return the modified value.
• currentValue: The current element being processed in the array.
• index (Optional): The index of the current element.
• arr: The array that map() was called upon.
The map() always returns a new array of the same length as the original
array. It does not modify the original array.
Map function Examples
Example-1
Example-2
const number = [45,63,12,98]
const persons = [
const newArr = numbers.map(function(el){
{firstName: "Ali", lastName: "Khan"}
return el*5
{firstName: "Noman", lastName: "Asghar"}
})
{firstName: "Nadeem", lastName: "Ali"}
console.log(newArr)
]
Or
const newArr = numbers.map((el) => el*5)
const fullName = persons.map((el) =>
Or
el.firstName + " " + el.lastName)
const newArr = numbers.map(multiply)
console.log(fullName);
function multiply(el) {
return el *5;
}

IT Industry-Academia Bridge Program


Key-Points
The map() method is often compared with forEach(), but there is
significant difference
- map() returns a new array with the results of applying a transformation
to each element.
- Use map() when:
• You need to transform data:
• You want a new array:

IT Industry-Academia Bridge Program


Scenario
You are working for a travel booking website, and you are tasked with processing a list of
customers who have made bookings for a vacation package. Each booking includes the
customer’s name, the destination city, and the total price of the vacation package.
Your task is to create a new list of customer names where the price of each booking has
been discounted by 10% to provide a special promotion. The list should show the names
of customers and the new price after applying the discount.
const truckDistances = [
{ truckId: "Truck A", dailyDistances: [50, 60, 70, 80, 90] },
{ truckId: "Truck B", dailyDistances: [40, 60, 55, 65, 70] },
{ truckId: "Truck C", dailyDistances: [100, 120, 130, 110, 115] },
{ truckId: "Truck D", dailyDistances: [30, 40, 50, 60, 45] }
];
const discountedBookings = bookings.map(booking => {
const discountedPrice = booking.price * 0.90; // Calculate the discounted price (10% off)
return { name: booking.name, discountedPrice: discountedPrice.toFixed(2) };
});
console.log(discountedBookings);
Reduce Function
The reduce() method in JavaScript is used to apply a function to all elements
of an array and accumulate a single value. The function has the following
syntax:
function callbackFn( previousValue, currentValue, currentIndex, array ) { /**/ }
previousValue:- The value returned from the previous call of the callbackFn
function. On the first call, the initialValue is the previousValue.
currentValue:- The value of the current array element. On the first call, it
is array[0].
currentIndex:- The index of the currentValue in the array.
array:- The array to loop through.
IT Industry-Academia Bridge Program
Grouping Objects by a Property:

Examples
const students = [
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 21 },
Summing an Array: { name: 'Charlie', age: 20 },
const numbers = [1, 2, 3, 4, 5]; { name: 'Dave', age: 22 }
const sum = numbers.reduce((accumulator, currentValue) ];
=> accumulator + currentValue); const groupedByAge = students.reduce(
console.log(sum); // Output: 15 (accumulator, currentValue) => {
const age = currentValue.age;
if (!accumulator[age]) {
Finding the Maximum Value in an Array: accumulator[age] = [];
const values = [10, 5, 8, 20, 3]; }
const max = values.reduce((accumulator, currentValue) accumulator[age].push(currentValue);
=> Math.max(accumulator, currentValue)); return accumulator; }, {}
console.log(max); // Output: 20 );
console.log(groupedByAge);
Flattening an Array of Arrays: // Output: { 20: [ { name: 'Alice', age: 20 },
const nestedArray = [[1, 2], [3, 4], [5, 6]]; { name: 'Charlie', age: 20 }],
const flattened = nestedArray.reduce((accumulator, currentValue) 21: [ { name: 'Bob', age: 21 }],
=> [...accumulator, ...currentValue], []); 22: [ { name: 'Dave', age: 22 }]
console.log(flattened); // Output: [1, 2, 3, 4, 5, 6] }

IT Industry-Academia Bridge Program


Scenario
You work for an online marketplace, and you're tasked with calculating the total
revenue generated by a list of orders. Each order in the marketplace includes the
order ID, the price of the product, and the quantity of the product purchased. You
need to calculate the total revenue by summing up the product of the price and
quantity for each order.
const orders = [
{ orderId: "ORD001", price: 25.99, quantity: 3 },
{ orderId: "ORD002", price: 45.50, quantity: 2 },
{ orderId: "ORD003", price: 12.99, quantity: 5 },
{ orderId: "ORD004", price: 20.00, quantity: 4 }
];
const totalRevenue = orders.reduce((acc, order) => {
const orderRevenue = order.price * order.quantity;
return acc + orderRevenue;
}, 0);
// Output the total revenue
console.log(`The total revenue generated by all orders is: $${totalRevenue.toFixed(2)}`);
Map() vs Reduce() vs forEach()
- map() returns a new array of the same size as the original array with each
element.
Therefore output is always an array with the same number of elements as
the input array.
- reduce() returns a single value (can be a number, string, array, object, etc.)
that is the result of applying a reducing operation to all elements in the
array.
Therefore output is a single value regardless of the number of elements in
the array.
- forEach() used for iterating over all elements in an array. It does not return
anything; it simply executes a provided function on each array element.
IT Industry-Academia Bridge Program
Filter Function
The filter() method creates a new array filled with elements that pass a
test provided by a function.
const newArray = array.filter(function(element) { return /* condition */; });
This method is used for selectively extracting elements from an array
based on a given condition.

const number = [1,2,3,4,5,6,7,8] const names = ["Ali", "Ahsan", "Noman", "Mohsin"]


const greaterThanFive = number.filter(el => el >= 5) const filterNames = names.filter(el => el.include('a'))
console.log(greaterThanFive) console.log(filterNames)
Find Function
The find() method in JavaScript is used with arrays to retrieve the value of
the first element that satisfies a given condition. It executes a provided
callback function for each element in the array until a truthy value is
returned.
const names = [
{id:1, name:"Ali"}, const number = [1,2,3,4,5,6,7,8]
{id:2, name:"Ahsan"}, const foundNumber = number.find(el => el > 5)
{id:3, name:"Noman"},
{id:4, name:"Mohsin"} console.log(foundNumber) //Output 6
]
const foundPerson = names.find(el => el.id === 1)
console.log(foundPerson) // {id:1, name: "Ali"}
Difference between filter() & find()
‘filter’ function
• The filter function creates a new array with all elements that pass the test implemented by
the provided function.
• It iterates through each element of the array and applies the provided function to each
element.
• The provided function should return true to include the element in the new array or false
to exclude it.
• If no elements pass the test, an empty array is returned.
‘find’ function
• The find function returns the first element in the array that satisfies the provided testing
function.
• It stops once the first matching element is found and returns that element.
• If no element satisfies the condition, undefined is returned.
• The find function does not create a new array; it just returns the first matching element.
Sort function
The sort() function in JavaScript is used to sort the elements of an array
in place (i.e., It modifies the original array).
array.sort(compareFunction);
compareFunction (optional) function defines the sort order. If omitted,
JavaScript will sort the array elements as strings provided.
let fruits = ["Banana", "Apple", "Orange", "Mango"];
fruits.sort(); // sorting answer = ["Apple", "Banana", "Mango", "Orange"]
By default fruits values will be sorted according to alphabetically.
Similarly number can be sort as
[11,15,12,9,20].sort((a,b)=> a - b )
Sorting Arrays of Objects
Sort by Number Property
Sorting by String Property const products = [
const products = [ { name: "Apple", price: 1.2 },
{ name: "Apple", price: 1.2 }, { name: "Banana", price: 0.5 },
{ name: "Banana", price: 0.5 }, { name: "Orange", price: 0.8 }
{ name: "Orange", price: 0.8 } ];
]; products.sort((a, b) => a.price - b.price);
products.sort((a, b) => a.name.localeCompare(b.name));
Here compareFunction will do
To sort an array of objects by a string property (e.g., by name), - If a - b is negative, a is placed before b.
you can use localeCompare() for string comparison. The - If a - b is positive, b is placed before a.
localeCompare() method compares two strings in a case-sensitive - If a - b is zero, their positions stay unchanged.
manner based on ..
- A negative number if the first string comes before the second.
- Zero if they are equal.
- A positive number if the first string comes after the second.
Another Method by Using Simple String Comparison (<, >)
products.sort((a, b) => a.name > b.name ? 1 : (a.name < b.name ? -1 : 0));
- If a.name is greater than b.name, it returns 1, meaning a should come after b.
- If a.name is less than b.name, it returns -1, meaning a should come before b.
- If a.name is equal to b.name, it returns 0, meaning their relative order remains unchanged.
Performance Evaluation
In JavaScript, loop (for, while, do-while) methods are
For-Of Loop:- Best among the methods listed here for iterating through arrays.
ForEach Loop: Slightly slower than for-of due to the callback function call for each element.
Some Loop: Very fast for finding a match because it stops iterating once it finds the first matching
element.
Find Loop:- Similar to some since find also short-circuits once it finds a match. The key difference is that
find returns the value of the first matching element instead of a boolean.
Every Loop:- Slower than some because it checks every element to ensure the condition holds for all
elements.
Filter Loop :- Slower than some and find, as it creates a new array with all elements that satisfy the
condition.
Map Loop:- Similar to filter, but it creates a new array based on transformed elements.
Reduce Loop:- Slower than map and filter because it requires a callback function that accumulates a
value. It’s not just a simple iteration, it’s a reduction process.
Fore-In:- The slowest for arrays, since it iterates over all enumerable properties, including prototype
chain properties.
Summary of Performance (Best to
Worst):
For-Of Loop – Best for simple iteration with minimal overhead.
forEach Loop – Good for readability but slightly slower due to the callback function.
Some Loop – Efficient for checking if any element meets a condition, especially on large datasets.
Find Loop – Similar to some but returns the first matching element instead of a boolean.
Filter Loop – Slower due to creating a new array, but useful for filtering elements.
Map Loop – Similar to filter, but used for transforming elements. Slower because of array
creation.
Every Loop – Checks all elements for a condition, even if the first few match, making it slower
than some.
Reduce Loop – Slower due to additional complexity of accumulating a result.
For-In Loop – The least performant for arrays, due to the overhead of iterating over all
properties, not just the array elements.
Recomendation
Best Performance for basic iteration: for-of loop.
When you need to transform data: Use map or filter depending on
whether you're transforming or filtering.
When searching for an element: Use some or find, depending on
whether you want the first match or just to know if one exists.
For accumulating data: Use reduce when you need to combine all
elements into one result.

IT Industry-Academia Bridge Program


Examples

IT Industry-Academia Bridge Program


Exercises
Write a JavaScript function to reverse the elements of an array.
function reverse(arr){
const reversedArr = []
arr.forEach(el => {
reversedArr.unshift(el) })
return reversedArr
}

console.log(reverse([1,2,3,4,5])) Write a JavaScript function to get the first element of an array.


passing a parameter 'n' will return the first 'n' elements of the array.
function getFe(arr,n){
if(!n) return arr[0]
return arr.slice(0,n)
}
Sample Input
console.log(getFe([7,8,9], 3))
IT Industry-Academia Bridge Program
Excercise
Write a JavaScript program that adds an element to cart. if the element is already in cart then it should return
an error saying item is already in card.
Sample Input
console.log(addToCart([1,2,3],4))
console.log(addToCart([1,2,3],3))
Sample Output
New Item "4" added successfully
Item "3" already in Cart

Solution
function addToCart(cart,el){
if(cart.includes(el)){
return console.log("Item ${el} already in Cart")
}
cart.push(el)
console.log("New item ${el} added successfully")
}
console.log(addToCart([1,2,3],4))
console.log(addToCart([1,2,3],3)) IT Industry-Academia Bridge Program
Destructing
JavaScript destructring is an expression that enables extracting values
from arrays, objects, and maps, and assigning them to variables in a
concise manner.
For objects, you can use object destructuring to extract properties
const person = { firstName: 'John', lastName: 'Doe' };
const { firstName, lastName } = person;
console.log(firstName); // Output: John
Array destructuring works similarly for arrays
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(second); // Output: 2

IT Industry-Academia Bridge Program


Destructing Example
const person = {
firstName: "Jamil",
lastName: "Ali"
age: 100,
fullName: function(){
return this.firstName + " " + this.lastName
}
location: {
city: "Lahore",
country: "Pakistan"
}
}

function message({firstName, lastName, location:{country,city}}){


console.log("My name is ${firstName} ${lastName} and I'm from ${country}")
}
message(person)
//Here in above example message function argument are replaced with
const {firstName, lastName, , location:{country,city}} = person
IT Industry-Academia Bridge Program
Object Initializer
You can create an object using an object initializer (comma-delimited
list of zero or more pairs of property names and associated values of an
object, enclosed in curly braces ({}).). Alternatively, you can first create
a constructor function and then instantiate an object by invoking that
function with the new operator.
Objects created with initializers are called plain objects, because they
are instances of Object, but not any other object type. The values of
object properties can either contain primitive data types or other
objects. const myHonda = {
color: "red",
wheels: 4,
engine: { cylinders: 4, size: 2.2 },
};
Summary
Objects are variables, that hold multiple key-value pairs and the value
can be string, number, array or even a function/method.
We can access object values by DOT or BRACKAT. .key or [“key”]
We can access object values by for loop. for(val in object)
Keyword ‘this’ in object represent the current object. this.key
Object destructing is a way of picking up specific property or method
out of an object.
An Object function is attached with every object to access object keys
and values

IT Industry-Academia Bridge Program


Questions
Q:1 - Write a JavaScript function that takes in two inputs, an object and a string. which the key to delete from
the object and it simply return a new object without the key
SAMPLE INPUT:
const person = {
name: 'Qasim',
location: 'Kararchi',
age: 34
}
del(person, "age")
SAMPLE OUTPUT
{
name:"Qasim",
location: "Karachi"
}
Q:2- Write a JavaScript program to get the length of a JavaScript object
Q:3 Write a JavaScript function that takes in two inputs, an object and a string and simply check if the object
has a property of the same name as the string
Solution-1
function del(obj, keyToDel){
let newObj = {}
for(key in obj){
if(key !== keyToDel)
newObj[key] = obj[key]
}
return newObj;
}
const person = {
name: 'Qasim',
location: 'Kararchi',
age: 34
}
console.log(del(person, "location"))
In JavaScript, the delete operator is used to remove a property from an object. It operates on an object's property and returns true if the
deletion is successful. Therefore the above del function code can replace with
Function del(obj, keyToDel){
delete obj[keyToDel]
return obj
Constructor Function
The constructor function is a special function for creating and
initializing an object with the following convention:
• The name of a constructor function starts with a capital letter like Person,
Document, etc.
• A constructor function should be called only with the new operator.
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
To create a new instance of the Person, you use the new operator:
let person1 = new Person('John','Doe');
let person2 = new Person(‘Naveed',‘Imtiaz');
Constructor Function
Methods for Constructor Function: An object may have methods that
manipulate its data. To add a method to an object created via the
constructor function, you can use the this keyword.
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.getFullName = function () {
return this.firstName + " " + this.lastName;
};
}
let person = new Person("John", "Doe");
console.log(person.getFullName());
Typically, a constructor function implicitly returns this that set to the
newly created object.
Summary
Array variable hold many values. To access these values, array index is
used.
Array methods are concat() / copyWithin() / every() / filter() / flat() /
flatMap() / forEach() / indexOf() / map() / reverse() / reduce() /
splice() / sort()
To access arrays elements, different loop styles can be used like for..in /
for..of / foreach
To access particular information from Array, JavaScript methods map,
filter, and find are powerful assets.

IT Industry-Academia Bridge Program


Recursion
Recursion is a process of calling itself. A function that calls itself is called a
recursive function. It always has a condition to stop calling itself. Otherwise, it
will call itself indefinitely. To prevent infinite recursion, you can use
if...else statement (or similar approach) where one branch makes the recursive call,
and the other doesn't.
Example-2
function factorial(x) {
if (x === 0) { // if number is 0
Example-1 return 1;
function countDown(fromNumber) { }
console.log(fromNumber); else { // if number is positive
let nextNumber = fromNumber - 1; return x * factorial(x - 1);
if (nextNumber > 0) { }}
countDown(nextNumber); const num = 3;
} if (num > 0) { // calling factorial() if num is non-negative
} let result = factorial(num);
countDown(3); console.log(`The factorial of ${num} is ${result}`);
}
Spread
The JavaScript spread operator ( ... ) allows us to quickly copy all or
part of an existing array or object into another array or object.
Example-1
const numbersOne = [1, 2, 3]; Example-3
const numbersTwo = [4, 5, 6]; //Combine two objects:
const combined = [...numbersOne, ...numbersTwo]; const myVehicle = {
console.log(combined); // 1,2,3,4,5,6 brand: 'Ford',
model: 'Mustang',
Example-2 color: 'red' }
const numbers = [1, 2, 3, 4, 5, 6]; const updateMyVehicle = {
//Assign the first and second items from numbers variables type: 'car',
//and put the rest in an array:
year: 2021,
const [one, two, ...rest] = numbers;
color: 'yellow' }
console.log(one); // 1
const myVehicle = {...myVehicle, ...updateMyVehicle}
console.log(two); // 2
console.log(rest); // 3, 4, 5, 6
IT Industry-Academia Bridge Program
Rest
The rest operator in JavaScript allows a function to take an indefinite number of
arguments and bundle them in an array.
function fname(a,b,...myRest) {
//statements
}
Here, a and b are normal parameters which will map to first and second argument
respectively. Whereas myRest is the rest parameter, that will contain contains the
third, fourth, and fifth ... nth arguments i.e all the remaining arguments other than
the values of a and b. function addition(...myArgs) {
let sum = 0;
for (let i of myArgs)
const toArray = (…args) => {
sum += i;
return args; return sum;
} }
console.log(toArray(1,2,3,4)); console.log(addition(5, 6));
console.log(addition(5, 6, 7));
console.log(addition(5, 6, 7, 8, 9));
Destructuring
Destructuring is a JavaScript expression that makes it possible to unpack values
from arrays, or properties from objects, into distinct variables. That is, we can
extract data from arrays and objects and assign them to variables.
Array Destructuring:- Extract data from arrays, using the destructuring
assignment.
let introduction = ["Hello", "I" , "am", "Sarah"];
let [greeting, pronoun] = introduction;
console.log(greeting);//"Hello"
console.log(pronoun);//"I"
When destructuring arrays, the order that variables are declared is important. If
we want “Hello” and “am” then we can simply leave out the “I” but keep the
comma.
let introduction = ["Hello", "I" , "am", "Sarah"];
let [greeting, ,pronoun] = introduction; // output => Hello am
le [,leter2, , lletter] = introduction; //output => I Sarah
Destructuring
Destructuring Objects: Extract data from an object and assign to new
variables.
let person = {name: "Sarah", country: "Nigeria"};
let {name, country, job} = person;
console.log(name);//"Sarah"
console.log(country);//"Nigeria"

IT Industry-Academia Bridge Program


Exercise-1
1. Write a javascript program that swaps two variable values without reassigning
them to a value directly
Sample Input: x=2, y=3
Sample Output: x=3, y=2
2. Write a JavaScript program to get the difference between a given number and 13.
if the number is greater than 13 log double the absolute difference
Sample Input: difference(32) and difference(11)
Sample Outputs: 32 and 2 respectively
3. Write a JavaScript program to compute the sum of the two given integers. If the
two values are same, the log triple their sum.
Sample Input: sumTriple(10,20)
Sample Output: 30 and 60 respectively.
4. Write a JavaScript program to check from two given integer, whether one is
positive and another one is negative.
Sample Inputs: PositiveNegative(2,-2) and positiveNegative(2,2)
Sample Output: true and false respectively
IT Industry-Academia Bridge Program

You might also like