JavaScript Introduction 1
JavaScript Introduction 1
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.
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
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".
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”]
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]]
entries() Returns an iterator object with the [key, value] pairs in a Map
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]);
}
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;
}
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] }
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