Wk 8 JavaScript Part III
Wk 8 JavaScript Part III
JavaScript
[email protected] JavaScript 1 / 39
Object What it is?
Object
b An object is a collection of properties
- Property is an association between a name/key and a value.
- A property’s value can be a function, in which case the property is known as a method
- Curly brackets are used to denote object with key and value pair
objectName = {name1 : value1 , ... , nameN : valueN}
- course = {name: "Web Technology", code: "CS2015"};
b By default, properties created using object literals or direct assignment are enumerable.
[email protected] JavaScript 2 / 39
Object What it is?
Object
b An object is a collection of properties
- Property is an association between a name/key and a value.
- A property’s value can be a function, in which case the property is known as a method
- Curly brackets are used to denote object with key and value pair
objectName = {name1 : value1 , ... , nameN : valueN}
- course = {name: "Web Technology", code: "CS2015"};
b By default, properties created using object literals or direct assignment are enumerable.
b How to define a property?
[email protected] JavaScript 2 / 39
Object What it is?
Object
b An object is a collection of properties
- Property is an association between a name/key and a value.
- A property’s value can be a function, in which case the property is known as a method
- Curly brackets are used to denote object with key and value pair
objectName = {name1 : value1 , ... , nameN : valueN}
- course = {name: "Web Technology", code: "CS2015"};
b By default, properties created using object literals or direct assignment are enumerable.
b How to define a property?
Object.defineProperty(course, 'credit', {value: 4, writable: true, enumerable: true});
console.log(course);//Output: { name: 'Web Technology', code: 'CS2015', credit: 4 }
b Check the output of console.log(course); after changing the value of enumerable attribute to
false.
[email protected] JavaScript 2 / 39
Object What it is?
Object
b An object is a collection of properties
- Property is an association between a name/key and a value.
- A property’s value can be a function, in which case the property is known as a method
- Curly brackets are used to denote object with key and value pair
objectName = {name1 : value1 , ... , nameN : valueN}
- course = {name: "Web Technology", code: "CS2015"};
b By default, properties created using object literals or direct assignment are enumerable.
b How to define a property?
Object.defineProperty(course, 'credit', {value: 4, writable: true, enumerable: true});
console.log(course);//Output: { name: 'Web Technology', code: 'CS2015', credit: 4 }
b Check the output of console.log(course); after changing the value of enumerable attribute to
false.
b How to inspect the details of a property?
[email protected] JavaScript 2 / 39
Object What it is?
Object
b An object is a collection of properties
- Property is an association between a name/key and a value.
- A property’s value can be a function, in which case the property is known as a method
- Curly brackets are used to denote object with key and value pair
objectName = {name1 : value1 , ... , nameN : valueN}
- course = {name: "Web Technology", code: "CS2015"};
b By default, properties created using object literals or direct assignment are enumerable.
b How to define a property?
Object.defineProperty(course, 'credit', {value: 4, writable: true, enumerable: true});
console.log(course);//Output: { name: 'Web Technology', code: 'CS2015', credit: 4 }
b Check the output of console.log(course); after changing the value of enumerable attribute to
false.
b How to inspect the details of a property?
console.log(Object.getOwnPropertyDescriptor(course, 'name'));
console.log(Object.getOwnPropertyDescriptor(course, 'credit'));
b Thus, based on the value of the enumerable attribute, properties can be classified into two classes:
non-enumerable property and enumerable property.
[email protected] JavaScript 2 / 39
Object Ways to create an Object
b Using constructor
function course(a,b,c) {
this.code = a;
this.name = b;
this.instructor = c;
}
let course = new course("CS2015", "Web Technology", "Dr. N. Saharia");
[email protected] JavaScript 3 / 39
Object Ways to create an Object
b Properties of JavaScript object can be accessed using the . (dot) and [ ] (bracket) notation.
let course = {code: "CS2015",name: "Web Technology"}
console.log(course.code); //Output: CS2015
console.log(course["code"]); //Output: CS2015
b A property of an object can itself be an object. For example
let course = {
code: "CS2015",
name: "Web Technology",
credit: {lecture: 3, tutorial: 0, practical: 2, credit: 4},
description: function() {"A job oriented course used to study in BTech 2nd Year."},
}
console.log(course.code); //Output: CS2015
console.log(course["code"]); //Output: CS2015
console.log(course.credit.credit); //Output: 4
console.log(course["credit"]["credit"]); //Output: 4
[email protected] JavaScript 4 / 39
Object Methods associated with Object
Object
b Object.keys(): It returns an array containing the names of all enumerable properties of the given
object. The keys are returned as strings, regardless of how they are defined.
const aboutMe= { name: "Jigar Kumar", age:20}
console.log(Object.keys(aboutMe)); // Output: [ 'name', 'age' ]
[email protected] JavaScript 5 / 39
Object Methods associated with Object
Object
b Object.keys(): It returns an array containing the names of all enumerable properties of the given
object. The keys are returned as strings, regardless of how they are defined.
const aboutMe= { name: "Jigar Kumar", age:20}
console.log(Object.keys(aboutMe)); // Output: [ 'name', 'age' ]
b Object.values(): Introduced in ECMAScript 2017 (ES8). It returns a new array containing the
values of all enumerable properties of the given object.
console.log(Object.values(aboutMe)); // Output: [ 'Jigar Kumar', 20 ]
[email protected] JavaScript 5 / 39
Object Methods associated with Object
Object
b Object.keys(): It returns an array containing the names of all enumerable properties of the given
object. The keys are returned as strings, regardless of how they are defined.
const aboutMe= { name: "Jigar Kumar", age:20}
console.log(Object.keys(aboutMe)); // Output: [ 'name', 'age' ]
b Object.values(): Introduced in ECMAScript 2017 (ES8). It returns a new array containing the
values of all enumerable properties of the given object.
console.log(Object.values(aboutMe)); // Output: [ 'Jigar Kumar', 20 ]
b The order of values in the resulting array is based on the order of properties in the object. For string
keys, the order is typically insertion order, but for integer keys, the order is numeric ascending.
const obj = { two: 2, 5: 'five', one: 1, 1: 'one' };
console.log(Object.values(obj)); //Output: [ 'one', 'five', 2, 1 ]
console.log(Object.keys(obj)); //Output: [ '1', '5', 'two', 'one' ]
[email protected] JavaScript 5 / 39
Object Methods associated with Object
Object-I
b Object.assign(): Copies the values of all enumerable properties from one or more source objects to
a target object.
const source = {name: "Jigar Kumar"};
const target = {age: 20};
const newOb = Object.assign(target, source);
console.log(newOb);
b Returns the target object after copying properties from the source objects.
console.log(newOb); //Output: { name: 'Jigar Kumar', age: 20 }
console.log(newOb === target); //Output: true
console.log(target); //Output: { name: 'Jigar Kumar', age: 20 }
b Multiple sources can be copied to target
const target = {}; const s1 = {a: 1}; const s2 = {b: 2}; const s3 = {c: 3};
console.log(Object.assign(target, s1, s2, s3)); //Output:{a:1, b:2, c:3}
b If the target object already has properties with the same names as those in the source objects, the
properties in the source objects will overwrite the properties in the target object.
const target = {a: 1, b: 2}; const source = {b: 3, c: 4};
console.log(Object.assign(target, source)); //Output: {a: 1, b: 3, c: 4}
[email protected] JavaScript 6 / 39
Object Methods associated with Object
Object-II
b Object.create(): Creates new object, using an existing object as the prototype.
const me = {
name: "Tom",
eatsMilkDaily: true,
favouriteTask: "chasing",
printAbout: function(){return `I am ${this.name} and I ${this.eatsMilkDaily ?
,→ "drink" :"do not drink"} milk daily. I am good in ${this.favouriteTask}.`},
};
console.log(Object.keys(me));
console.log(me.printAbout());
[email protected] JavaScript 7 / 39
Object Methods associated with Object
Object-II
b Object.create(): Creates new object, using an existing object as the prototype.
const me = {
name: "Tom",
eatsMilkDaily: true,
favouriteTask: "chasing",
printAbout: function(){return `I am ${this.name} and I ${this.eatsMilkDaily ?
,→ "drink" :"do not drink"} milk daily. I am good in ${this.favouriteTask}.`},
};
console.log(Object.keys(me));
console.log(me.printAbout());
b Create a new object myFriend considering me as prototype.
const myFriend = Object.create(me);
myFriend.name = "Jerry";
myFriend.eatsMilkDaily = false;
myFriend.favouriteTask = "leading";
console.log(myFriend.printAbout());
[email protected] JavaScript 7 / 39
Object Methods associated with Object
Object-III
b Object.entries(): Returns array, where each element is a key-value pair of the object. Each
key-value pair is represented as an array with two elements: the key as the first element and the
corresponding value as the second element. The keys in the returned array will always be strings,
even if the original object uses symbols or non-string keys.
const me = { name:"Abhishek", age:21 }
console.log(Object.entries(me)) //Output: [ ['name', 'Abhishek'], ['age', 21] ]
b While displaying. the numeric keys will appear first, sorted in ascending order, followed by string
keys in insertion order.
let obj = { two: 2, one: 1, 5: "five", three : 3, 4: "four"};
for (let [k, v] of Object.entries(obj)) {
console.log(`${k}: ${v}`); }
b Object.fromEntries(): Transforms a list of key-value pairs into an object. Opposite of
Object.entries(). If the input is not an iterable object or does not consist of key-value pairs, it will
throw an TypeError.
const me = [ [ 'name', 'Abhishek' ], [ 'age', 21 ] ]
console.log(me) //output; [ [ 'name', 'Abhishek' ], [ 'age', 21 ] ]
console.log(Object.fromEntries(me)) //Output: { name: 'Abhishek', age: 21 }
[email protected] JavaScript 8 / 39
Object Methods associated with Object
Object-IV
b Object.freeze(): Freezes an object. Once an object is frozen, its properties can not be added,
removed, or modified, and its prototype cannot be changed.
let me = { name:"Abhishek", age:21 }
me.name = "Jigar Kumar";
console.log(me) //Output: { name: 'Jigar Kumar', age: 21 }
[email protected] JavaScript 9 / 39
Object Methods associated with Object
Object-V
b Object.freeze() freezes the direct properties of the object. If the object contains nested objects, the
nested objects are still alterable unless explicitly frozen.
const me = { name: 'Abhishek', details: { age: 21 } };
Object.freeze(me);
me.name = 'Vikas';
me.details.age = 15;
console.log(me); //Output: {name: 'Abhishek', details: { age: 15 } }
[email protected] JavaScript 10 / 39
Object Methods associated with Object
Object-VI
b Object.seal(): Seals an object that prevent new properties from being added to it and marks all
existing properties non-configurable. Object.seal() prevents structural changes, adding/removing
property names are not allowed, however, it allows modification of existing property values as
opposed to Object.freeze(). The Object.freeze() method completely lock down the object so
that no modifications can be made neither property name nor values.
let me = { name: 'Abhishek', age:21, occumpation: 'Student' };
delete me.occumpation;
console.log(me) //Output: { name: 'Abhishek', age: 21 }
Object.seal(me);
me.name = "Jigar Kumar";
console.log(me) //Output: { name: 'Jigar Kumar', age: 21 }
Object.freeze(me);
me.age = 20;
console.log(me) //Output: { name: 'Jigar Kumar', age: 21 }
b Object.isSealed(): Determines if an object is sealed.
const me = { name: 'Abhishek' , age: 21 }
[email protected] JavaScript 11 / 39
Array
b An special type of object that is used to store multiple items of different data-types in a single
variable. Arrays are ordered collections that allows to store elements of any type at numbered
positions called indices, which are zero-based.
let abc = [1, 'abc', true, [1, 2, 3, 4], { bcd: 20 , def: 30 } ];
console.log(abc);
b In programming languages, zero-based indexing refers to the practice, where the first element of a
collection is assigned an index 0 as opposed to one-based indexing, where index 1 is assigned to the
first element. C, C++, JavaScript, PHP, and Java are few examples of programming languages that
follows zero-based indexing. Matlab and Fortran follows one-based indexing
b Thus, keys of this special object of JS are positive integers and always start with zero. The first
element of an array is at index 0 and the last element is at the value of the array’s length property
minus 1.
b Not associative: Array elements cannot be accessed using arbitrary strings as indexes, but must be
accessed using nonnegative integers. That is keys are not directly associated with values
[email protected] JavaScript 12 / 39
Array
Sparse indices
b JavaScript arrays exhibits a properties called Sparse indices, where some indices may not contain
elements. In such cases, those indices will be considered as undefined. Arrays in JavaScript are
dynamic in size, that is the size of the array adjusts automatically.
let abc = [];
console.log(abc.length); //Output: 0
abc[100] = 'abc';
console.log(abc.length); //Output: 101
[email protected] JavaScript 13 / 39
Array Create Array
[email protected] JavaScript 14 / 39
Array Create Array
[email protected] JavaScript 14 / 39
Array Create Array
[email protected] JavaScript 14 / 39
Array Create Array
b Array.of(2) creates an array with one slot and assign the argument to that slot
[email protected] JavaScript 15 / 39
Array Create Array
b Array.of(2) creates an array with one slot and assign the argument to that slot
console.log(Array.of(0)); // [ 0 ]
console.log(Array.of(2)); // [ 2 ]
[email protected] JavaScript 15 / 39
Array Create Array
b Array.of(2) creates an array with one slot and assign the argument to that slot
console.log(Array.of(0)); // [ 0 ]
console.log(Array.of(2)); // [ 2 ]
[email protected] JavaScript 15 / 39
Array Create Array
[email protected] JavaScript 16 / 39
Array Create Array
b Array length can be changed by assignment beyond the current length. Arrays are sparse, that is,
space is only allocated for elements that have been assigned a value
colors[5] = 'cyan'; console.log(colors.length); //6
[email protected] JavaScript 16 / 39
Array Create Array
b Array length can be changed by assignment beyond the current length. Arrays are sparse, that is,
space is only allocated for elements that have been assigned a value
colors[5] = 'cyan'; console.log(colors.length); //6
b As opposed to C and Java, JavaScript has array of array instead of two or multi dimensional array.
let webTechAssessment = [["21010101", 10, 20],["21010102", 10, 10]];
console.log(webTechAssessment.length); //2
console.log(webTechAssessment[0].length); //3
[email protected] JavaScript 16 / 39
Array Create Array
Homework
output:
[ 1, 2, 3, <7 empty items>, 100, <999989 empty items>, 'abc', '10000000000': 1]
[email protected] JavaScript 17 / 39
Array Methods of Array
Array methods
b arrayName.push(…) → adds any number of new elements to the end of the array, and increases the
array’s length
b arrayName.pop() → removes and returns the last element of the array, and decrements the array’s
length
b arrayName.toString() → returns a string containing the values of the array elements, separated by
commas
[email protected] JavaScript 18 / 39
Array Two-dimentional Array
b Using array literal []: The following statement will create an two-dimentional array with 4 rows.
let arr = []; for (let i = 0; i < 4; i++) {arr[i] = [];}
[email protected] JavaScript 19 / 39
Array Two-dimentional Array
b Using array literal []: The following statement will create an two-dimentional array with 4 rows.
let arr = []; for (let i = 0; i < 4; i++) {arr[i] = [];}
b Using Array.prototype.map(): The following statement will create an two-dimentional array with 4
rows and 3 columns, where elements will be null
let arr = Array(4).fill().map(() => Array(3)); console.log(arr);
[email protected] JavaScript 19 / 39
Array Two-dimentional Array
b Using array literal []: The following statement will create an two-dimentional array with 4 rows.
let arr = []; for (let i = 0; i < 4; i++) {arr[i] = [];}
b Using Array.prototype.map(): The following statement will create an two-dimentional array with 4
rows and 3 columns, where elements will be null
let arr = Array(4).fill().map(() => Array(3)); console.log(arr);
b Using Array.from(): The following statement will create an two-dimentional array with 4 rows and 3
columns, where elements will be null
let arr = Array.from(Array(4), () => new Array(3));
[email protected] JavaScript 19 / 39
Array 2D Array Methods
[email protected] JavaScript 20 / 39
Array 2D Array Methods
[email protected] JavaScript 20 / 39
Array 2D Array Methods
[email protected] JavaScript 20 / 39
Array 2D Array Methods
[email protected] JavaScript 20 / 39
Array 2D Array Methods
Typed Array
b Low-level, array-like object that provides a mechanism for reading and writing binary data in a
specific format
b Unlike regular arrays, Typed Arrays have a fixed length and are designed to work with raw binary
data only
b Each entry in a JavaScript typed array is a raw binary value in one of a number of supported
formats, from 8-bit integers to 64-bit floating-point numbers
b Array.isArray() on a typed array returns false. Moreover, not all methods available for normal
arrays are supported by typed arrays
[email protected] JavaScript 21 / 39
Array Typed Array
typeView[0] = 12;
typeView[1] = 100;
b Combined approach
const abc = new Int32Array([10, 20, 30, 40]);
console.log(abc); //Output: Int32Array(4) [ 10, 20, 30, 40 ]
[email protected] JavaScript 22 / 39
Array Typed Array
Types of TypedArray?
b Types
Type Size in Bytes Range
Int8Array 1 -128 to 127
Uint8Array 1 0 to 255
Uint8ClampedArray 1 0 to 255 (with clamping)
Int16Array 2 -32,768 to 32,767
Uint16Array 2 0 to 65,535
Int32Array 4 -2,147,483,648 to 2,147,483,647
Uint32Array 4 0 to 4,294,967,295
Float16Array 2 -65504 to 65504
Float32Array 4 Approx ±3.4e38
Float64Array 8 Approx ±1.8e308
BigInt64Array 8 −263 to 263 -1
BigUint64Array 8 0 to 264 - 1
b The term clamped in Uint8ClampedArray means that the assign values to the array will
automatically be restricted (clamped) within the range of 0 to 255.
- Values less than 0 will be clamped to 0.
- Values greater than 255 will be clamped to 255.
[email protected] JavaScript 23 / 39
Array Typed Array
Kaprekar’s constant
b Write a JavaScript program print the final output of the following steps.
- Take any four-digit number, N, using at least three different digits
- Arrange the digits of N in descending and then in ascending order
- Subtract the smaller number from the bigger number and update the N
- Go back to step 2 and repeat. Break the loop once the process continue yielding the same
number
b The above process will always reach its fixed point in at most 7 iterations. Break the loop once the
process continue yielding the same number.
Example: 1201
2110-0112=1998
9981-1899=8082
8820-0288=8532
8532-2358=6174
7641-1467=6174
7641-1467=6174
7641-1467=6174
[email protected] JavaScript 25 / 39
Function Introduction
Function
b A reusable block of code or subprogram performs a specific task.
b A fundamental building block of JavaScript programs, and they enable code organization,
abstraction, and reusability.
b Syntax: function functionName(parameters){/* function body*/ return result;/*Optional*/ }
- function keyword is used to declare a function.
- functionName a valid JavaScript identifier to define the name of the function. Optional. Known
as anonymous, if no name.
- params, zero or more input values that the function accepts. Optional and specified inside the
parentheses.
- { }: The curly braces contain the code block to be executed when the function is called.
- return statement that specifies the value to be returned by the function. If omitted, the
function returns undefined
[email protected] JavaScript 26 / 39
Function Introduction
Function
b A reusable block of code or subprogram performs a specific task.
b A fundamental building block of JavaScript programs, and they enable code organization,
abstraction, and reusability.
b Syntax: function functionName(parameters){/* function body*/ return result;/*Optional*/ }
- function keyword is used to declare a function.
- functionName a valid JavaScript identifier to define the name of the function. Optional. Known
as anonymous, if no name.
- params, zero or more input values that the function accepts. Optional and specified inside the
parentheses.
- { }: The curly braces contain the code block to be executed when the function is called.
- return statement that specifies the value to be returned by the function. If omitted, the
function returns undefined
b Example:
- Function definition: function abc(a, b, c) { return a + b + c ; }
- Function invocation let sum = abc(1, 2, 3);
[email protected] JavaScript 26 / 39
Function Types
Type of Function
b In JavaScript, functions are first-class objects, because they can be passed to other functions,
returned from functions, and assigned to variables and properties. They can also have properties and
methods just like any other object
[email protected] JavaScript 27 / 39
Function Types
Type of Function
b In JavaScript, functions are first-class objects, because they can be passed to other functions,
returned from functions, and assigned to variables and properties. They can also have properties and
methods just like any other object
b Regular function: Can return anything; always runs to completion after invocation
[email protected] JavaScript 27 / 39
Function Types
Type of Function
b In JavaScript, functions are first-class objects, because they can be passed to other functions,
returned from functions, and assigned to variables and properties. They can also have properties and
methods just like any other object
b Regular function: Can return anything; always runs to completion after invocation
b Function Expressions: Functions can be defined using function expressions, where a function is
assigned to a variable.
const multiply = function(x, y) { return x * y;};
console.log(multiply(3, 4)); // Output: 12
[email protected] JavaScript 27 / 39
Function Types
Types of Function
b Named Function Expressions: Similar to function expressions, but with the advantage of having a
name that can be used within the function for recursion or stack traces.
b Unlike regular function declarations, named function expressions provide a way to create anonymous
functions with a name, which can be useful for self-referencing or for better stack traces in debugging.
const factorial = function calcFactorial(n) {return n <= 1 ? 1 : n * calcFactorial(n -
,→ 1);};
console.log(factorial(5));
[email protected] JavaScript 28 / 39
Function Types
Types of Function
b Named Function Expressions: Similar to function expressions, but with the advantage of having a
name that can be used within the function for recursion or stack traces.
b Unlike regular function declarations, named function expressions provide a way to create anonymous
functions with a name, which can be useful for self-referencing or for better stack traces in debugging.
const factorial = function calcFactorial(n) {return n <= 1 ? 1 : n * calcFactorial(n -
,→ 1);};
console.log(factorial(5));
b Arrow Function: Arrow Functions: Function with concise syntax, especially for short,
single-expression functions.
const abc = (a, b, c) => a + b + c;
const sum = abc(3, 7, 5);
console.log(sum);
[email protected] JavaScript 28 / 39
Function Types
b A function that allows pausing and resuming the execution, producing a sequence of values over time.
b Provides a powerful way to create iterators with a simpler syntax compared to traditional iterators
b Once paused, the generator’s code execution remains paused until it invokes next() method.
b If an optional value is passed to the generator’s next() method, that value becomes the value
returned by the generator’s current yield operation.
[email protected] JavaScript 29 / 39
Function Types
What is Cookie
b What is Cookie?
- Cookie is a small text file that is created by a website and stored on a user’s browser.
- Cookies are used to store information about the user’s interaction with the website, such as
login details, user preferences, and browsing behavior.
[email protected] JavaScript 31 / 39
Cookies Cookies
What is Cookie
b What is Cookie?
- Cookie is a small text file that is created by a website and stored on a user’s browser.
- Cookies are used to store information about the user’s interaction with the website, such as
login details, user preferences, and browsing behavior.
b Working Strategy
- When a user visits a website, the website’s server can set a cookie in the user’s browser by
sending an HTTP response header that includes a Set-Cookie header with the relevant
information.
- The browser then stores the cookie on the user’s computer and sends it back to the server with
each subsequent request to the website.
[email protected] JavaScript 31 / 39
Cookies Cookies
What is Cookie
b What is Cookie?
- Cookie is a small text file that is created by a website and stored on a user’s browser.
- Cookies are used to store information about the user’s interaction with the website, such as
login details, user preferences, and browsing behavior.
b Working Strategy
- When a user visits a website, the website’s server can set a cookie in the user’s browser by
sending an HTTP response header that includes a Set-Cookie header with the relevant
information.
- The browser then stores the cookie on the user’s computer and sends it back to the server with
each subsequent request to the website.
[email protected] JavaScript 31 / 39
Cookies Cookies
Website
User’s System Server
Cookies Cookies
Website
User’s System Server
Cookies Cookies
[email protected] JavaScript 32 / 39
Cookies Attributes of Cookies
Cookies: Attribute
b JavaScript method document.cookie is used to read cookies. E.g.: alert(document.cookie)
b Cookies have several attributes and are listed as key=value, delimited by ;. Splitting
document.cookie by ; will generate a particular cookie
- domain: A domain defines where the cookie is accessible. A cookie is accessible only at the
domain that sets it, even it is not shared with a subdomain.
document.cookie = "domain=abc.com" ;
- path: Refers to the specific (URL) path for which the cookie is valid. It makes the cookie
accessible for pages under that path. Usually, path attribute is set to the root of the website:
path=/ to make the cookie accessible from all website pages. By default, it is the current page.
document.cookie = "domain=abc.com; path=/new_site; secure" ;
- secure: A security feature that can be set to ensure that the cookie is only sent over secure,
encrypted connections. When the secure attribute is present, the cookie will only be
transmitted to the server if the request is being sent over HTTPS. Using HTTPS ensures that
the communication between the client and the server is encrypted, making it significantly more
difficult for malicious actors to intercept and manipulate the data.
document.cookie = "domain=abc.com; path=/new_site; secure" ;
[email protected] JavaScript 33 / 39
Cookies Attributes of Cookies
Cookies: Attribute
b samesite: Forbids the browser to send the cookie with requests coming from outside the site. It
helps to prevent XSRF (cross-site request forgery) attacks.
[email protected] JavaScript 34 / 39
Cookies Attributes of Cookies
Cookies: Attribute
b samesite: Forbids the browser to send the cookie with requests coming from outside the site. It
helps to prevent XSRF (cross-site request forgery) attacks.
b What is XSRF?
[email protected] JavaScript 34 / 39
Cookies Attributes of Cookies
Cookies: Attribute
b samesite: Forbids the browser to send the cookie with requests coming from outside the site. It
helps to prevent XSRF (cross-site request forgery) attacks.
b What is XSRF? It is a type of vulnerability that occurs when an attacker tricks a user’s web browser
into making an unintended and potentially malicious request on a website where the user is
authenticated. The attack takes advantage of the fact that web browsers automatically include
authentication cookies with each request to a specific domain.
[email protected] JavaScript 34 / 39
Cookies Attributes of Cookies
Cookies: Attribute
b samesite: Forbids the browser to send the cookie with requests coming from outside the site. It
helps to prevent XSRF (cross-site request forgery) attacks.
b What is XSRF? It is a type of vulnerability that occurs when an attacker tricks a user’s web browser
into making an unintended and potentially malicious request on a website where the user is
authenticated. The attack takes advantage of the fact that web browsers automatically include
authentication cookies with each request to a specific domain.
- Let us assume that an user logged into a site bank.com. That is the user’s browser has an
authentication cookie from bank.com and sends it to bank.com with every request so that it
recognizes the user and performs all sensitive financial operations.
- While browsing the web in another window, the user accidentally come to another site evil.com.
That site has JavaScript code that submits a form <form action="https://bank.com/pay"> to
bank.com with fields that initiate a transaction to the other account.
- The browser sends cookies every time you visit the site bank.com, even if the form was
submitted from evil.com. So the bank recognizes the user and performs the payment.
(Source: https://javascript.info/cookie#xsrf-attack)
[email protected] JavaScript 34 / 39
Cookies Attributes of Cookies
Cookies: Attribute
b The samesite has three values: strict, lex and none. Default is lex.
b When a cookie is set to samesite=Strict attribute, the cookie is only sent in a first-party context.
This means the cookie will only be sent if the site for the cookie matches the site currently shown in
the browser’s address bar. It provides the highest level of protection against CSRF attacks.
document.cookie = "user=abc; domain=abc.com; samesite=strict; secure"
b With samesite=lax, the cookie is sent with top-level navigations and first-party requests but is not
sent along with cross-site requests initiated by third-party websites, such as when loading images or
frames. This provides a balance between security and functionality, as it reduces the risk of CSRF
attacks while allowing some level of cross-site interaction.
document.cookie = "user=abc; domain=abc.com; samesite=lax; secure"
b Setting samesite=none allows the cookie to be sent with both first-party and third-party requests.
However, when using samesite=none , the Secure attribute must also be set, ensuring that the cookie
is only sent over secure, encrypted connections.
document.cookie = "user=abc; samesite=none; secure"
[email protected] JavaScript 35 / 39
Cookies Attributes of Cookies
Cookies: Attribute
b Cookies without expires or max-age attribute are known as session cookies. The accepted cookie will
disappear when the browser/tab is closed.
- expires or max-age attributes help to let cookies survive after closing the browser. Although,
expires and max-age are alternatively used, max-age has precedence if both are set.
[email protected] JavaScript 36 / 39
Cookies Attributes of Cookies
Third-party cookie
b Cookie that is set by a domain other than the page the user is visiting
b In the context of web browsing, websites often include resources from third-party domains, such as
advertisements, analytics scripts, or social media plugins. When these resources set and read cookies,
those cookies are classified as third-party cookies.
b These cookies are often used for tracking and analytics purposes, such as by advertisers or analytics
services. They can be used to track users across different websites and build profiles for targeted
advertising
b Working strategy
- A page at site.com loads a banner from another site ads.com
- Along with the banner, the remote server at ads.com may set the Set-Cookie header with an
ID. Such a cookie originates from ads.com domain, and will only be visible at ads.com
- Next time when ads.com is accessed, the remote server gets the id and recognizes the user.
- When the user moves from site.com to another site other.com, which also has a banner, then
ads.com gets the cookie, as it belongs to ads.com, thus recognizing the visitor and tracking him
as he moves between sites
(Source: https://javascript.info/cookie#appendix-third-party-cookies)
[email protected] JavaScript 37 / 39
Cookies Example
switch (String.fromCharCode(keyNm)){
case 'v': {clrNm = "violet"; break;}
case 'y': {clrNm = "yellow"; break;}
case 'b': {clrNm = "blue"; break;}
case 'g': {clrNm = "green"; break;}
case 'i': {clrNm = "indigo"; break;}
case 'o': {clrNm = "orange"; break;}
case 'r': {clrNm = "red"; break;}
default: {clrNm = "white";}
}
[email protected] JavaScript 38 / 39
Cookies Example