Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

js_programming-14-06-2024-1

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

js_programming-14-06-2024-1

Js programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Javascript Programming - 2

NITHIN
nithin@pentagonspace.in
The + operator
The ‘+’ operator works differently for numbers and strings. For
numbers, the operator performs mathematical addition whereas for
strings, it performs concatenation

Try It Yourself –
let x = 10 + 20;
let x = 10 + “20”;
let x = “10” + 20;
let x = 10 + 20 + “30”;
let x = “10” + 20 + 30;
let x = “Hello” + “world”;

Except +, all other numeric operators cast strings to numbers


NaN
Indicates that a number is not a legal number.
Obtained when performing arithmetic operations with non-numeric
strings.

Use isNaN() to find out if a value is NaN.

let x = 100 / "Apple";


isNaN(x);

If NaN is manually assigned, the result of the expression is also NaN


With strings, concatenation is performed (typeof NaN = number)
Infinity
The value JS returns when the result is greater than the largest
possible number.

When can I generate Infinity?


On dividing a number by 0. Good guess.

Eg –
let x = 2 / 0;
let y = -2 / 0;

NOTE – typeof Infinity = number


More on arrays
Easiest way to declare and initialize an array
const array_name = [item1, item2, ...];

Tip: Declare arrays using const.

Can I create an array first and then add elements?


const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
Access elements using the index. (typeof array = object)
Arrays again 
.length -> property
.sort()

How do I access the first element of an array?

How do I access the last element of an array?

Solutions:
array_name[0]
array_name[array_name.length - 1]
For of loop
const cars = ["BMW", "Benz", "Mini Cooper", "Audi"];

for (let car of cars) {


console.log(car);
}

Works for arrays and strings.


Arrays – element-wise
Strings – character-wise
For in loop
Use this for objects.
Iterates through object keys. (can be used to access values too.

const student = {
firstName: "Suraj",
lastName: "S",
age: 10,
};

for (let key in student) {


console.log(`key: ${key}, value: ${student[key]}`);
}
Array methods
.length
.toString() -> array to comma separated values
.at(position) [solves problem of negative indexing in JS]
.join(separator) [joins array elements with separator, returns str]
.pop() [returns (removes) element at the last index of array]
.push(element) [add element at the end of the array, returns length]
.shift() [removes first element of the array]
.unshift(element) [add element at the start of the array]
delete array[index] : replaces element at index with undefined
.concat(array) [original unaffected. Returns new array, var. args]
.flat()
More array methods
.indexOf(element, startPos)
.lastIndexOf(element) [returns the index of the last occurrence]
.includes(element)
.sort()
.reverse()
.toSorted() [original unchanged, returns new array]
.toReversed() [original unchanged, returns new array]

Try sorting the following array of numbers


[122, 37, 255, 70, 400]
Compare Function
Helps us define an alternative sort order.
The function should return a negative, zero, or positive value.
function(a, b){return a - b}

When sort() compares two values, it sends them to the compare


function.
If the result is negative, a is sorted before b
If the result is positive, b is sorted before a
If the result is 0, no changes are done.

Trace : [40, 100, 10]


Array Iteration
.forEach(callback)
.map(callback)

NOTE: The callback function takes 3 arguments:


1. The item value
2. The item index (optional)
3. The array itself (optional)

const nums = [10, 20, 30, 40];


function myFunction(item, index, array) {array[index] = item + 5;}
nums.forEach(myFunction);
console.log(nums);
Spread operator
The … operator expands an iterable (like an array) into more
elements.

const q1 = ["Jan", "Feb", "Mar"];


const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];
const year = [...q1, ...q2, ...q3, ...q4];

… is an ES6 feature, and is not supported in Internet Explorer


Are arrays constants?
The keyword ‘const’ is a little misleading.
In the code snippet below

const arr = [10, 20, 30];

We are not declaring and initializing a constant array.


Rather, we define a constant reference to an array.

Because of this,
We can still change the elements of the array even on using const.
.map()
Creates a new array by invoking a callback on each element.
It skips array elements without values.
Does not change the original array.

const numbers1 = [45, 4, 9, 16, 25];


const numbers2 = numbers1.map(myFunction);

function myFunction(value, index, array) {


return value * 2;
}
Callback functions
Raj calls Suresh.
Suresh picks up.
He says “I’m in a meeting. I’ll call you back in a while”

Can you guess what a callback does?

- In simple terms, a callback function is like leaving a message for


someone and asking them to call you back when they're ready.
- Imagine you're ordering food from a restaurant over the phone. After
you place your order, the person taking your order might say, "We'll
call you back when your food is ready." That's a callback. Instead of
waiting on the line for your food to be ready, you can go about your
day, and the restaurant will call you back when your order is prepared.
What on earth are callbacks?
In programming, callback functions work in a similar way. When you
call a function, you can pass another function (the callback) as an
argument. The main function then executes its task and, when it's
done, it "calls back" the function you provided, passing along any
necessary information. This is commonly used in asynchronous
programming, like handling events in web development or managing file
operations in a computer program.
Questions
1. Find the sum and average of a given array of numbers.
2. Check if a number or a string is a palindrome.
3. Check if two strings are anagrams.

You might also like