Trending December 2023 # Cookies In Javascript: Set, Get & Delete Example # Suggested January 2024 # Top 20 Popular

You are reading the article Cookies In Javascript: Set, Get & Delete Example updated in December 2023 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Cookies In Javascript: Set, Get & Delete Example

What are Cookies?

A cookie is a piece of data that is stored on your computer to be accessed by your browser. You also might have enjoyed the benefits of cookies knowingly or unknowingly. Have you ever saved your Facebook password so that you do not have to type it each and every time you try to login? If yes, then you are using cookies. Cookies are saved as key/value pairs.

Why do you need a Cookie?

The communication between a web browser and server happens using a stateless protocol named HTTP. Stateless protocol treats each request independent. So, the server does not keep the data after sending it to the browser. But in many situations, the data will be required again. Here come cookies into a picture. With cookies, the web browser will not have to communicate with the server each time the data is required. Instead, it can be fetched directly from the computer.

Javascript Set Cookie

You can create cookies using document. cookie property like this.

document.cookie = "cookiename=cookievalue" document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00 UTC"

You can also set the domain and path to specify to which domain and to which directories in the specific domain the cookie belongs to. By default, a cookie belongs to the page that sets the cookie.

document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00 UTC; path=/ "

//create a cookie with a domain to the current page and path to the entire domain.

JavaScript get Cookie

You can access the cookie like this which will return all the cookies saved for the current domain.

var x = document.cookie JavaScript Delete Cookie

To delete a cookie, you just need to set the value of the cookie to empty and set the value of expires to a passed date.

Try this Example yourself:

Special instructions to make the code work … Press the run button twice

function createCookie(cookieName,cookieValue,daysToExpire) { var date = new Date(); date.setTime(date.getTime()+(daysToExpire*24*60*60*1000)); } function accessCookie(cookieName) { var name = cookieName + “=”; var allCookieArray = document.cookie.split(‘;’); for(var i=0; i<allCookieArray.length; i++) { var temp = allCookieArray[i].trim(); if (temp.indexOf(name)==0) return temp.substring(name.length,temp.length); } return “”; } function checkCookie() { var user = accessCookie(“testCookie”); if (user!=””) alert(“Welcome Back ” + user + “!!!”); else { user = prompt(“Please enter your name”); num = prompt(“How many days you want to store your name on your computer?”); if (user!=”” && user!=null) { createCookie(“testCookie”, user, num); } } }

You're reading Cookies In Javascript: Set, Get & Delete Example

Http Cookies In Node Js

The cookies are the data stored in the user’s browser for quick access. For example, whenever we log in to any website, the server returns the access token, which can be stored in the browser’s cookie with the expiry time. So, whenever a user revisits the website, they don’t need to log in to the website repeatedly if the access token stored in the cookies has not expired.

We can also access the browser’s cookies on the server side in NodeJS. After that, we can check if any detailed data exists in the cookies we are looking at, and if not, we can set that data into cookies again.

Here, we will learn to access, set, and clear the cookies using NodeJS.

Syntax

Users can follow the syntax below to set and get the cookies using NodeJS.

res.cookie(“name”, value); });

res.send(req.cookies); });

In the above syntax, we set the cookies in the first route using the ‘res.cookie()’ method and get the cookie using the ‘req.cookies’ in the second route.

Before users start trying the example below, they should have created the Node application. Also, execute the below commands to install the app’s ‘express’ and ‘cookie-parser’ NPM packages.

npm i express cookie-parser Example

In the example below, we have created the basic server using express. Also, we have used the ‘cookieParse’ in the express app.

We show the welcome message whenever users go on the home route after running the application. Also, we have created the car object containing some properties.

Whenever the user goes to the ‘setcookies’ route, it sets the car data in the cookies. Users can go to the ‘getcookies’ route to access all cookies. Users can go on the ‘clear’ route to clear the cookies.

let express = require("express"); let cookieParser = require("cookie-parser"); let app = express(); app.use(cookieParser()); res.send("Express app is created successfully, and you are on homepage"); }); let car = { name: "BMW", model: "X5", price: 50000, }; res.cookie("carData", car); res.send("car data is stored in cookies"); }); res.send(req.cookies); }); res.clearCookie("carData"); res.send("Cookies are cleared!"); }); if (err) throw err; console.log("listening on port 8000"); }); Example 2

In the example below, we set the cookies with the expiry time. We have created the table and homeWindow object containing the various properties in the key-value pair.

We can set both objects with different expiry times by making a get request on the ‘setCookies’ route. Also, users can access and delete particular cookies by passing the name as a parameter. In the output, users can observe that we accessed only table objects.

let express = require("express"); let cookieParser = require("cookie-parser"); let app = express(); app.use(cookieParser()); res.send("Express app is created successfully, and you are on homepage"); }); let table = { color: "brown", material: "wood", size: "small", price: 100, }; let homeWindow = { color: "white", material: "glass", size: "big", price: 200, }; res.send("Cookies are set with different expiry time"); }); res.send(req.cookies); }); res.send(req.cookies[req.params.name]); }); res.clearCookie(req.params.name); res.send("Cookies with name " + chúng tôi + " is deleted"); }); if (err) throw err; console.log("listening on port 8000"); });

Users learned to set and get cookies from NodeJS. We use the res.cookie() method to set cookies and req.cookies to get cookies. Also, we can use the res.clearCookies() method to clear any particular or all cookies.

Algorithm To Get The Combinations Of All Items In Array Javascript

In this problem statement, our task is to get the combinations of all items in an array with the help of Javascript functionalities. So for doing this task we can use a recursive approach that iteratively adds items to a running list of combinations.

Understanding the problem statement

The problem statement is to write a function in Javascript that will help to find out the combinations of all the elements in an array and create a separate array to show these combinations. For example, if we have an array [ 1, 2 ] so the combinations of this array will be [ [ 1, 2 ], [ 2 ] ].

Logic for the given problem

To create a function to get all the possible combinations of items in an array in Javascript can be done using a recursive algorithm which will iteratively add items to a list of combinations. So first we will define an array and initialize it as empty. Inside the created function we will define another function to recurse the running list of combinations.

Algorithm

Step 1 − Declare a function called getCombinations which is using a parameter of array.

Step 2 − Declare a result array inside the function which will hold our final list of combinations.

Step 3 − Define another function called recurse which will take two arguments cur and rem, here cur is the running list of items and rem is the array of items we have left to add in the combinations.

Step 4 − And after this if there are no items left in the rem array we will push current into the result array because we have reached the required result.

Step 5 − Otherwise we will iterate every item in the rem array and recursively call a recursive function with a new cur array that will include the current item.

Step 6 − Call recurse initially with an empty cur array and the full array we want to generate combinations for.

Step 7 − Return the final result array which contains all possible combinations of the input array.

Code for the algorithm function getCombinations(array) { const result = []; function recurse(cur, rem) { if (rem.length === 0) { result.push(cur); } else { for (let i = 0; i < rem.length; i++) { recurse([...cur, rem[i]], rem.slice(i + 1)); } } } recurse([], array); return result; } const array = [10, 20, 30, 40]; const combinations = getCombinations(array); console.log(combinations); Complexity

The time complexity for the above created function is O(2^n) because the algorithm generates all possible combinations of items in the array and there are 2^n possible combinations. And the space complexity for the code is also O(2^n) because the algorithm generates a list of 2^n combinations.

Conclusion

The above code provides a simple solution to generate all possible combinations of items in an array in Javascript. So it has an O(2^n) time and space complexity which can make it less efficient for large arrays. So it is important to note the size of the array when deciding whether to use this algorithm.

How Do I Get The Current Date And Time In Javascript?

This tutorial teaches us to get the date and time in JavaScript. Nowadays, JavaScript is the most popular programming language used for user interaction with the browser. We can say that it is hard to find a single web application that does not use JavaScript.

The purpose of creating this tutorial is to make programmers familiar with the Date() object. Users can get today’s date and current time using the date class. While developing the applications, programmers maybe need to show the current date and time according to the user’s local zone, and we can fill this requirement using the date class. Also, sometimes we need to store the user’s session start and end times in our app database.

To solve all the problems, we just create an object of date class and use its various methods to get the current date and time in this tutorial.

Get Date and Time using the Date Object

Get date and time using the toLocaleString() Method

Get Date and Time using the Date Object

The Date class contains several methods; we can fetch the current date, day, and time by using them. Also, it includes hundreds of different methods that programmers can use according to their requirements.

Syntax

Users can follow the below syntax for different methods-

let newDate = new Date();

Using the below syntax users can get the year, month and date.

let year = newDate.getFullYear(); let month = newDate.getMonth(); let todaySDate = newDate.getDate()

Using the below syntax users can get hours, minutes, and second.

let hours = newDate.getHours(); let minutes = newDate().getMinutes();       let date = document.getElementById("date");       let time = document.getElementById("time");             let newDate = new Date();       let year = newDate.getFullYear();       let month = newDate.getMonth();       let todaySDate = newDate.getDate();       let hours = newDate.getHours();       let minutes = newDate.getMinutes();       let seconds = newDate.getSeconds();       date.innerHTML = " " + todaySDate + "/ " + month + "/ " + year;       time.innerHTML = hours + ": " + minutes + ": " + seconds; let dateAndTime = date.toLocaleString(); let date = date.toLocaleDateString(); let time = date.toLocaleTimeString();

Users can follow the below syntax, if they want to get date and time for any local region.

let options = {    year: ‘numeric’,    month: ‘long’,    day: ‘numeric’,    weekday: ‘long’, }       let dateAndTime = document.getElementById("dateAndTime");       let date = document.getElementById("date");       let time = document.getElementById("time");       let dateIN = document.getElementById("dateIN");       let dateUs = document.getElementById("dateUs");

            let newDate = new Date();       dateAndTime.innerHTML = newDate.toLocaleString();       date.innerHTML = newDate.toLocaleDateString();       time.innerHTML = newDate.toLocaleTimeString();

            var options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long', };       dateIN.innerHTML = newDate.toLocaleString("en-IN", options);       dateUs.innerHTML = newDate.toLocaleString("en-US", options);

How To Get The Smallest Of Zero Or More Numbers In Javascript?

In this tutorial, we shall learn to find the smallest among numbers in JavaScript.

Let’s discuss the available methods one after the other

Using the Math.min() Method

Here, the Math.min() is a static function of the placeholder object Math. If no parameters, the result is -Infinity. If the parameters are numbers, the result is the smallest among them. If any one of the parameters is not a number, the method returns NaN. This is an ECMAScript1 feature.

Syntax

Following is the syntax of Math.min() method −

Math.min(a1, a2,…an)

Here, we need to give numbers as parameters.

Parameters

a1, a2,…an − the numbers.

Example

Here, Math.min() directly finds the smallest value.

var

m1

=

Math

.

min

(

0

,

7

,

20

,

0.8

)

;

document

.

getElementById

(

“firstId”

)

.

innerHTML

=

“The smallest “

+

m1

;

Using Array.min() and Math.min().apply()

Here, an array of numbers is the input. The Math.min() applies this array and gives us the smallest number.

Syntax

Following is the syntax to use Array.min() method and Array.min.apply() −

Array.min = function(array) { return Math.min.apply(Math, array); }; var minimum = Array.min(arr);

Here, an array of numbers has to be given as the input.

Parameters

arr − The array.

Example

Here, Array.min() takes the input array and Math.min() applies it and returns the output.

Array

.

min

=

function

(

array

)

{

return

Math

.

min

.

apply

(

Math

,

array

)

;

}

;

var

array

=

[

24

,

2

,

1

,

0

]

;

var

minimum

=

Array

.

min

(

array

)

;

document

.

getElementById

(

“result”

)

.

innerHTML

=

“The smallest : “

+

minimum

;

Using the Destructuring Assignment Syntax/Spread Operator

Using the spread operator … we can extract values from an array or object into different variables. We can use this method because the Math.min() method does not support a direct array as an input.

Syntax

Users can follow the syntax below.

Math.min(...[p, q, r]);

Here, the spread operator helps the Math.min() method to return the smallest value.

Parameters

p, q, r − The array of numbers

Example

Here, Math.min() with the spread operator directly evaluates our input and displays the output.

var

res

=

Math

.

min

(

[

21

,

2

,

3

,

2

,

0

,

23

]

)

;

document

.

getElementById

(

“result”

)

.

innerHTML

=

res

;

Using the for Loop

As we know, here we consider the first number in an array as the smallest. Then we compare the remaining numbers in the array with this. Finally, we get the smallest value.

Syntax

Users can follow the syntax below.

for (var i = 0; i<arr.length; i++) { if (arr[i] < arr[0]) { } }

Here, the for loop evaluates the array of numbers and compares all with the first number and returns the smallest.

Parameters

arr − The array

i − The array index

Example

Here, the general array elements compare logic in the loop, and the output is displayed.

const

numbers

=

[

11

,

4

,

9

,

0

,

2

]

;

let

min

=

numbers

[

0

]

;

for

(

let

i

=

0

;

i

<

numbers

.

length

;

i

++

)

{

if

(

numbers

[

i

]

<

min

)

{

min

=

numbers

[

i

]

;

}

}

document

.

getElementById

(

“result”

)

.

innerHTML

=

“The smallest is “

+

min

;

Using the Array.reduce() Method

Here, we give the input to a call-back function. This function iterates through the input and gives the smallest value.

Syntax

Here, two values are compared every time of an array iteration and the smallest value is returned at the end.

Parameters

r1, r2 − r1 is the accumulator, and r2 is the current value respectively. During array iteration, if the current value becomes smaller than the accumulator, the current value becomes the next accumulator.

Example

Here, our input is processed by reduce(), and Math.min() returns the result.

const

nums

=

[

6

,

7

,

0.3

]

;

document

.

getElementById

(

“numb”

)

.

innerHTML

=

nums

;

document

.

getElementById

(

“result”

)

.

innerHTML

=

“The smallest is “

+

res

;

Using the Array.sort() Method

In the Array sort method, we get the minimum value at the start of the array.

Syntax arr.sort()[0]

Here, arr is the array of numbers.

Example

Here, the JavaScript sort is done on the input array and the first value is returned.

const

srtArr

=

[

60

,

10

,

80

]

;

document

.

getElementById

(

“numb”

)

.

innerHTML

=

srtArr

const

res

=

srtArr

.

sort

(

)

[

0

]

document

.

getElementById

(

“result”

)

.

innerHTML

=

“Smallest is “

+

res

;

This tutorial helped us to learn about the six methods to find the smallest of all numbers given.

The Math.min() method does not accept an array of elements. The reduce array method, loop method, and array apply method is more logical.

Among all the methods that we learned, the spread operator method and default array sort method is simple to use and work well.

Implementation Of Linkedlist In Javascript

A linked list is a data structure that consists of a sequence of elements, each of which contains a reference (or “link”) to the next element in the sequence. The first element is called the head and the last element is called the tail.

Defining the Node Class and the LinkedList class

This is basically the prerequisite in order to implement a linked list in JavaScript. In this step, 2 classes namely one for the nodes and the other for the linked list need to be created.

The Node class represents a single node in the linked list. It has two properties which are data and next. The data property is used to store the actual data of the node, whereas the next property is a reference to the next node in the list. The Node class consists of a constructor that initializes the data and next property when creating a new Node.

class Node { constructor(data) { chúng tôi = data; chúng tôi = null; } }

The LinkedList class is a representation of the linked list itself. It has a head property that refers to the first node in the list. The LinkedList class also has a constructor that initializes the head property when creating a new LinkedList.

class LinkedList { constructor() { chúng tôi = null; chúng tôi = null; this.length = 0; } }

The LinkedList class also consists of a method that allows you to insert, delete, and search for nodes in the list while simultaneously allowing other operations like printing the list, counting the elements, reversing the list and so on.

Printing the linked list

You can print the elements of a linked list by traversing through the list and printing the data of each node.

printAll() { let current = this.head; while (current) { console.log(current.data); current = current.next; } } Adding Node to the Linked List

There are multiple methods to add data to a linked list depending on where the new node has to be inserted, and are as follows −

Adding node to the beginning of the linked list

To add node/ element at the start of a linked list, once a new node is created with the data, simply set its next property to the current head of the list. Then you can update the head of the list to the new node. This is also known as Insertion at the head of the linked list and is the most basic type of addition of data. It is simply done by calling the add function defined below.

add(data) { const newNode = new Node(data); if (!this.head) { chúng tôi = newNode; chúng tôi = newNode; } else { chúng tôi = newNode; chúng tôi = newNode; } this.length++; return this; } Adding node to the end of the linked list

To add node/ element at the end of a linked list, we need to traverse the list and find the last node. After which a new node with data is created and we set the next property of the last node to the new node. This is also known as Insertion at the tail of the linked list and is the second most basic type of addition of data. It is simply done by calling the addToTail function defined below.

addToTail(data) { let newNode = new Node(data); if (this.head === null) { chúng tôi = newNode; return; } let current = this.head; while (current.next !== null) { current = current.next; } chúng tôi = newNode; } Adding node at a specific position

To add node/ element at a specific position in a linked list, you can traverse the list to find the node at the position before the insertion point, create a new node with the data, set the next property of the new node to the current node at the position, and set the next property of the previous node to the new node.

addAtPosition(data, position) { let newNode = new Node(data); if (position === 1) { chúng tôi = this.head; chúng tôi = newNode; return; } let current = this.head; let i = 1; while (i < position - 1 && current) { current = current.next; i++; } if (current) { chúng tôi = current.next; chúng tôi = newNode; } } Example (Adding Nodes to the Linked List)

In the below example, we implement adding nodes at beginning, at end and at a specific position.

class Node { constructor(data) { chúng tôi = data; chúng tôi = null; } } class LinkedList { constructor() { chúng tôi = null; chúng tôi = null; this.length = 0; } add(data) { const newNode = new Node(data); if (!this.head) { chúng tôi = newNode; chúng tôi = newNode; } else { chúng tôi = newNode; chúng tôi = newNode; } this.length++; return this; } addToTail(data) { let newNode = new Node(data); if (this.head === null) { chúng tôi = newNode; return; } let current = this.head; while (current.next !== null) { current = current.next; } chúng tôi = newNode; } addAtPosition(data, position) { let newNode = new Node(data); if (position === 1) { chúng tôi = this.head; chúng tôi = newNode; return; } let current = this.head; let i = 1; while (i < position - 1 && current) { current = current.next; i++; } if (current) { chúng tôi = current.next; chúng tôi = newNode; } } it printAll() { let current = this.head; while (current) { console.log(current.data); current = current.next; } } } const list = new LinkedList(); list.add("node1"); list.add("node2"); list.add("node3"); list.add("node4"); console.log("Initial List:"); list.printAll(); list.addAtPosition("nodex",2); list.printAll(); list.addToTail("nodey"); list.printAll(); Output Initial List: node1 node2 node3 node4 List after adding nodex at position 2 node1 nodex node2 node3 node4 List after adding nodey to tail node1 nodex node2 node3 node4 nodey Removing Node

Removal of data too, can be done via several methods depending upon the requirement.

Removing a specific node

To remove a specific node from a linked list, we need to traverse the list and find the node before the one you want to remove, update its next property to skip over the node you want to remove, and update the reference to the next node. This removes the node based upon the value.

remove(data) { if (!this.head) { return null; } if (this.head.data === data) { chúng tôi = this.head.next; this.length--; return this; } let current = this.head; while (current.next) { if (current.next.data === data) { chúng tôi = current.next.next; this.length--; return this; } current = current.next; } return null; } Removing a node at a Specific Position

To remove a node at a specific position in a linked list, we need to traverse the list and find the node before the one you want to remove, update its next property to skip over the node you want to remove, and update the reference to the next node. This is basically removing the node based upon the index value of it.

removeAt(index) { if (index === 0) return this.remove(); let current = this.head; for (let i = 0; i < index - 1; i++) { current = current.next; } chúng tôi = current.next.next; this.length--; return this; } Example (Removing Nodes from the Lined List)

In the below example, we implement removing a specific node and a node at a specific position.

class Node { constructor(data) { chúng tôi = data; chúng tôi = null; } } class LinkedList { constructor() { chúng tôi = null; chúng tôi = null; this.length = 0; } add(data) { const newNode = new Node(data); if (!this.head) { chúng tôi = newNode; chúng tôi = newNode; } else { chúng tôi = newNode; chúng tôi = newNode; } this.length++; return this; } remove(data) { if (!this.head) { return null; } if (this.head.data === data) { chúng tôi = this.head.next; this.length--; return this; } let current = this.head; while (current.next) { if (current.next.data === data) { chúng tôi = current.next.next; this.length--; return this; } current = current.next; } return null; } removeAt(index) { if (index === 0) return this.remove(); let current = this.head; for (let i = 0; i < index - 1; i++) { current = current.next; } chúng tôi = current.next.next; this.length--; return this; } printAll() { let current = this.head; while (current) { console.log(current.data); current = current.next; } } } const list = new LinkedList(); list.add("node1"); list.add("node2"); list.add("node3"); list.add("node4"); console.log("Initial List:"); list.printAll(); list.remove("node2"); list.printAll(); list.removeAt(2); list.printAll(); Output Initial List: node1 node2 node3 node4 List after removing node2 node1 node3 node4 List after removing node at index 2 node1 node3 Conclusion

Implementing a linked list in JavaScript involves creating a Node class to represent each node in the list and a LinkedList class to represent the list itself, and adding methods to the LinkedList class to perform operations such as adding and removing data, and printing the list. It’s important to also consider edge cases and handle them accordingly in your implementation. There are several ways of adding or removing data from a LinkedList based upon the use case.

Update the detailed information about Cookies In Javascript: Set, Get & Delete Example on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!