Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Sunday, 13 November 2022

ES6 Spread Operator

The ES6 (ECMAScript 2015) spread operator is a powerful feature in JavaScript that allows you to expand or spread elements from an array or object into another array or object. It is represented by three consecutive dots (...). Here’s a breakdown of how it works and some common use cases:

1. Spreading Elements in Arrays

You can use the spread operator to spread elements of an existing array into a new array.

  const fruits = ['apple', 'banana', 'cherry'];
  const moreFruits = ['orange', ...fruits, 'mango'];
  console.log(moreFruits);
 
  // Output: ['orange', 'apple', 'banana', 'cherry', 'mango']

In this example, the ...fruits spreads out the elements of the fruits array into the moreFruits array.

2. Copying Arrays

The spread operator is often used to create a shallow copy of an array.

Example:

  const originalArray = [1, 2, 3];
  const copiedArray = [...originalArray];
  console.log(copiedArray);
 
  // Output: [1, 2, 3]

3. Spreading Elements in Function Calls

You can use the spread operator to pass elements of an array as individual arguments to a function.

Example:

  const numbers = [1, 2, 3];
  const sum = (a, b, c) => a + b + c;
  console.log(sum(...numbers));
 
  // Output: 6

Here, ...numbers spreads the array elements as individual arguments to the sum function.

4. Combining Arrays

You can use the spread operator to combine multiple arrays into one.

Example:

  const array1 = [1, 2];
  const array2 = [3, 4];
  const combinedArray = [...array1, ...array2];
  console.log(combinedArray);
  // Output: [1, 2, 3, 4]

5. Spreading Properties in Objects

The spread operator can also be used to spread properties from one object into another. This is especially useful for creating new objects based on existing ones.

Example:

  const person = { name: 'John', age: 30 };
  const job = { title: 'Developer', company: 'XYZ Corp' };
  const personWithJob = { ...person, ...job };
  console.log(personWithJob);
  // Output: { name: 'John', age: 30, title: 'Developer', company: 'XYZ Corp' }

6. Merging Objects

You can use the spread operator to merge objects, where properties from later objects will overwrite properties from earlier ones if they have the same key.

Example:

  const obj1 = { a: 1, b: 2 };
  const obj2 = { b: 3, c: 4 };
  const mergedObj = { ...obj1, ...obj2 };
  console.log(mergedObj); // Output: { a: 1, b: 3, c: 4 }

In this case, the value of b in obj2 overrides the value of b in obj1.

The spread operator is a versatile tool that simplifies many common programming tasks related to arrays and objects.


Continue Reading →

ES6 Modules

 Modules

JavaScript modules allow you to break up your code into separate files. This makes it easier to maintain the code-base.

ES Modules rely on the import and export statements.

Export

You can export a function or variable from any file.

Let us create a file named person.js, and fill it with the things we want to export.

There are two types of exports: Named and Default.

Named Exports

You can create named exports two ways. In-line individually, or all at once at the bottom.

//In-line individually:
//person.js

export const name = "Jesse"
export const age = 40

//All at once at the bottom:
//person.js

const name = "Jesse"
const age = 40

export { name, age }


Default Exports

Let us create another file, named message.js, and use it for demonstrating default export.

You can only have one default export in a file.

//message.js

const message = () => {
  const name = "Jesse";
  const age = 40;
  return name + ' is ' + age + 'years old.';
};

export default message;


Import

You can import modules into a file in two ways, based on if they are named exports or default exports.

Named exports must be destructured using curly braces. Default exports do not.

Import from named exports

Import named exports from the file person.js:

import { name, age } from "./person.js";

Import from default exports

Import a default export from the file message.js:

import message from "./message.js";


Continue Reading →

ES6 Destructuring

Destructuring in ES6 (ECMAScript 2015) is a feature that allows you to unpack values from arrays or properties from objects into distinct variables. It provides a more concise and readable way to extract data compared to traditional methods. Here's a breakdown of how destructuring works for arrays and objects:

Array Destructuring

Array destructuring allows you to extract values from an array and assign them to variables.

  const [a, b, c] = [1, 2, 3];
  console.log(a); // 1
  console.log(b); // 2
  console.log(c); // 3

Skipping Items: You can skip items in the array by leaving the position empty:

  const [first, , third] = [1, 2, 3];
  console.log(first); // 1
  console.log(third); // 3

Default Values: You can provide default values for variables:

  const [a = 1, b = 2] = [undefined, 3];
  console.log(a); // 1 (default value)
  console.log(b); // 3

Rest Operator: The rest operator (...) can be used to collect remaining elements into an array:

  const [first, ...rest] = [1, 2, 3, 4, 5];
  console.log(first); // 1
  console.log(rest);  // [2, 3, 4, 5]

Object Destructuring

Object destructuring allows you to extract properties from an object and assign them to variables.

  const { name, age } = { name: 'John', age: 30 };
  console.log(name); // John
  console.log(age);  // 30

Default Values: You can provide default values for variables:

  const { name = 'Anonymous', age = 25 } = { name: 'John' };
  console.log(name); // John
  console.log(age);  // 25 (default value)

Renaming Variables: You can rename variables while destructuring:

  const { name: userName, age: userAge } = { name: 'John', age: 30 };
  console.log(userName); // John
  console.log(userAge);  // 30

Nested Destructuring: You can destructure nested objects or arrays:

  const person = {
    name: 'John',
    address: {
      city: 'New York',
      zip: '10001'
    }
  };
 
  const { name, address: { city, zip } } = person;
  console.log(name); // John
  console.log(city); // New York
  console.log(zip);  // 10001

Rest Operator in Objects: The rest operator can also be used to collect remaining properties into a new object:

  const { name, ...rest } = { name: 'John', age: 30, city: 'New York' };
  console.log(name); // John
  console.log(rest); // { age: 30, city: 'New York' }

Destructuring can make your code more readable and reduce the need for repetitive property access or array indexing.

Continue Reading →

Wednesday, 2 June 2021

Deep and Shallow Copy in Javascript

 Shallow copy

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

Deep copy

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

Lets take an example

Shallow Copy: It makes a copy of the reference to X into Y. Think about it as a copy of X’s Address. So, the addresses of X and Y will be the same i.e. they will be pointing to the same memory location.

Deep copy: It makes a copy of all the members of X, allocates different memory location for Y and then assigns the copied members to Y to achieve deep copy. In this way, if X vanishes Y is still valid in the memory.

The correct term to use would be cloning, where you know that they both are totally the same, but yet different (i.e. stored as two different locations in the memory space).

Consider this example:

var employeeDetailsOriginal =
        {name: 'Manjula'age: 25Profession: 'Software Engineer'};

Let’s say you want to create a duplicate of this, so that even if you change the original values, you can always return to the original.

//Shallow copy!
var employeeDetailsDuplicate = employeeDetailsOriginal

If we change a value:

employeeDetailsDuplicate.name = 'NameChanged';

This statement will also change name from employeeDetailsOriginal, since we have a shallow copy, or a reference to var employeeDetailsOriginal. This means, you’re losing the original data as well.

But, creating a brand new variable by using the properties from the original employeeDetailsOriginal variable, you can create a deep copy.

//Deep copy!
var employeeDetailsDuplicate = { name: employeeDetailsOriginal.name,
    age: employeeDetailsOriginal.age
    Profession: employeeDetailsOriginal.Profession};

Now if you change employeeDetailsDuplicate.name, it will only affect employeeDetailsDuplicate and not employeeDetailsOriginal

Diagramatic example


Reference: https://medium.com/

Continue Reading →

Friday, 23 April 2021

Event Bubbling in JS

 The bubbling principle is simple.

When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.

Let’s say we have 3 nested elements FORM > DIV > P with a handler on each of them:

<!DOCTYPE html>
<html>
<!doctype html>
<body>
<style>
  body * {
    margin10px;
    border1px solid blue;
  }
</style>

<form onclick="alert('form')">FORM
  <div onclick="alert('div')">DIV
    <p onclick="alert('p')">P</p>
  </div>
</form>
</body>
</html>

Click here for demo. https://www.w3schools.com/

A click on the inner <p> first runs onclick:

On that <p>.

Then on the outer <div>.

Then on the outer <form>.

And so on upwards till the document object.

So if we click on <p>, then we’ll see 3 alerts: p → div → form.

The process is called “bubbling”, because events “bubble” from the inner element up through parents like a bubble in the water.

Stopping bubbling

A bubbling event goes from the target element straight up. Normally it goes upwards till <html>, and then to document object, and some events even reach window, calling all handlers on the path.

But any handler may decide that the event has been fully processed and stop the bubbling.

The method for it is event.stopPropagation().

For instance, here body.onclick doesn’t work if you click on <button>:

<body onclick="alert(`the bubbling doesn't reach here`)">
    <button onclick="event.stopPropagation()">Click me</button>
  </body>

Reference : https://javascript.info/

Continue Reading →

Tuesday, 13 October 2020

Local Storage vs Session Storage vs Cookie

With Advent of Html5 , we have got various option to cache or store info on client browser. Previously we were having only cookies , which were very restrictive and size of cookies was very small. but now we local storage and session storage as well. and cookies has been talk of past , though it is getting used for various purposes. let's talk about all these

LocalStorage
localStorage is a way to store data on the client’s computer. It allows the saving of key/value pairs in a web browser and it stores data with no expiration date. localStorage can only be accessed via JavaScript, and HTML5. However, the user has the ability to clear the browser data/cache to erase all localStorage data.

//Set the value in a local storage object
localStorage.setItem('name'myName);

//Get the value from storage object
localStorage.getItem('name');

//Delete the value from local storage object
localStorage.removeItem(name);//Delete specifice obeject from local storege
localStorage.clear();//Delete all from local storege

Pros:
  1. stores data with no expiration date
  2. storage limit is about 5MB
  3. data is never transferred to the server
Cons:
  1. plaintext, hence not secure by design
  2. limited to string data, hence need to be serialized
  3. can only be read on client-side
Session storage
  1. Stores data only for a session, meaning that the data is stored until the browser (or tab) is closed
  2. data is never transferred to the server
  3. can only be read on client-side
  4. storage limit is about 5-10MB
  5. opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window
sessionStorage.setItem('key''value');
var data = sessionStorage.getItem('key');

Cookie
  1. Stores data that has to be sent back to the server with subsequent XHR requests. Its expiration varies based on the type and the expiration duration can be set from either server-side or client-side .
  2. Cookies are primarily for server-side reading (can also be read on client-side), localStorage and sessionStorage can only be read on client-side.
  3. Size must be less than 4KB.
  4. Cookies can be made secure by setting the httpOnly flag as true for that cookie. This prevents client-side access to that cookie.
Cookies can be updated , set using document.cookie object from browser window object.
document.cookie = "yummy_cookie=choco"
document.cookie = "tasty_cookie=strawberry"
console.log(document.cookie); 
// logs "yummy_cookie=choco; tasty_cookie=strawberry"



Reference: https://medium.com
Continue Reading →

call() , apply() and bind() in JavaScript

In this post, we will be discussing the difference between call(), apply(), and bind() methods of JavaScript functions with simple examples. As functions are also Objects in JavaScript, these 3 methods are used to control the invocation of the function. call() and apply() were introduced in ECMAScript 3 while bind() was added as part of ECMAScript 5.

  Bind( ) 
The bind method creates a new function and sets the this keyword to the specified object.
For example: Let’s suppose we have two person objects.
const john = {
    name: 'John',
    age: 24,
  };
  const jane = {
    name: 'Jane',
    age: 22,
  };

Let’s add a greeting function:
function greeting() {
    console.log(`Hi, I am ${this.name} and I am ${this.age} years old`);
  }

We can use the bind method on the greeting function to bind the this keyword to john and jane objects.
For example:
const greetingJohn = greeting.bind(john);
// Hi, I am John and I am 24 years old
greetingJohn();
const greetingJane = greeting.bind(jane);
// Hi, I am Jane and I am 22 years old
greetingJane();

Here greeting.bind(john) creates a new function with this set to john object, which we then assign to greetingJohn variable. Similarly for greetingJane.

Bind() can also accept arguments: We can also pass extra arguments to the bind method. 
function greeting(lang) {
    console.log(`${lang}: I am ${this.name}`);
  }
  const john = {
    name: 'John'
  };
  const jane = {
    name: 'Jane'
  };
  const greetingJohn = greeting.bind(john'en');
  greetingJohn();
  const greetingJane = greeting.bind(jane'es');
  greetingJane();

In the above example, the bind method creates a new function with certain parameters predefined (lang in this case) and this keyword set to the john and jane objects.

 Call ( ) 
The call method sets the this inside the function and immediately executes that function.

The difference between call() and bind() is that the call() sets the this keyword and executes the function immediately and it does not create a new copy of the function, while the bind() creates a copy of that function and sets the this keyword.

function greeting() {
    console.log(`Hi, I am ${this.name} and I am ${this.age} years old`);
  }
  const john = {
    name: 'John',
    age: 24,
  };
  const jane = {
    name: 'Jane',
    age: 22,
  };
  // Hi, I am John and I am 24 years old
  greeting.call(john);
  // Hi, I am Jane and I am 22 years old
  greeting.call(jane);


Above example is similar to the bind() example except that call() does not create a new function. We are directly setting the this keyword using call().

Call () can also accept arguments: Call() also accepts a comma-separated list of arguments. 

function greet(greeting) {
    console.log(`${greeting}, I am ${this.name} and I am ${this.age} years old`);
  }
  const john = {
    name: 'John',
    age: 24,
  };
  const jane = {
    name: 'Jane',
    age: 22,
  };
  // Hi, I am John and I am 24 years old
  greet.call(john'Hi');
  // Hi, I am Jane and I am 22 years old
  greet.call(jane'Hello');


 Apply ( ) 
The apply() method is similar to call(). The difference is that the apply() method accepts an array of arguments instead of comma separated values.

function greet(greetinglang) {
    console.log(lang);
    console.log(`${greeting}, I am ${this.name} and I am ${this.age} years old`);
  }
  const john = {
    name: 'John',
    age: 24,
  };
  const jane = {
    name: 'Jane',
    age: 22,
  };
  // Hi, I am John and I am 24 years old
  greet.apply(john, ['Hi''en']);
  // Hi, I am Jane and I am 22 years old
  greet.apply(jane, ['Hola''es']);

  1. bind: It binds the function with provided value and context but it does not executes the function. To execute function you need to call the function.
  2. call: It executes the function with provided context and parameter.
  3. apply: It executes the function with provided context and parameter as array.
Conclusion
We have learned that how this keyword behaves differently in JavaScript than in other object-oriented languages. The call, bind and apply methods can be used to set the this keyword independent of how a function is called.
 The bind method creates a copy of the function and sets the this keyword, while the call and apply methods sets the this keyword and calls the function immediately.
Reference: https://blog.bitsrc.io/https://www.codementor.io


Continue Reading →

Sunday, 11 October 2020

Typescript: Iterators (for..in and for..of)

 for..of statements

for..of loops over an iterable object. Here is a simple for..of loop on an array:

let someArray = [1"string"false];

for (let entry of someArray) {
  console.log(entry); // 1, "string", false
}


for..of vs. for..in statements

Both for..of and for..in statements iterate over lists; the values iterated on are different though, for..in returns a list of keys on the object being iterated, whereas for..of returns a list of values of the numeric properties of the object being iterated.

Here is an example that demonstrates this distinction:

let list = [456];

for (let i in list) {
  console.log(i); // "0", "1", "2",
}

for (let i of list) {
  console.log(i); // "4", "5", "6"
}


Another distinction is that for..in operates on any object; it serves as a way to inspect properties on this object. for..of on the other hand, is mainly interested in values of iterable objects. Built-in objects like Map and Set implement Symbol.iterator property allowing access to stored values.

let pets = new Set(["Cat""Dog""Hamster"]);
pets["species"] = "mammals";

for (let pet in pets) {
  console.log(pet); // "species"
}

for (let pet of pets) {
  console.log(pet); // "Cat", "Dog", "Hamster"
}


Continue Reading →

Saturday, 10 October 2020

Javascript: Map and Set

Now we’ve learned about the following complex data structures:

  • Objects for storing keyed collections.
  • Arrays for storing ordered collections.

But that’s not enough for real life. That’s why Map and Set also exist.

 Map 

Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

Methods and properties are:

  1. new Map() – creates the map.
  2. map.set(key, value) – stores the value by the key.
  3. map.get(key) – returns the value by the key, undefined if key doesn’t exist in map.
  4. map.has(key) – returns true if the key exists, false otherwise.
  5. map.delete(key) – removes the value by the key.
  6. map.clear() – removes everything from the map.
  7. map.size – returns the current element count.

For instance:

let map = new Map();

map.set('1''str1');   // a string key
map.set(1'num1');     // a numeric key
map.set(true'bool1'); // a boolean key


Map can also use objects as keys.

let john = { name: "John" };
let map = new Map();

map.set(john'str1');   // a string key


Every map.set call returns the map itself, so we can “chain” the calls:

map.set('1''str1')
  .set(1'num1')
  .set(true'bool1');


Iteration over Map

For looping over a map, there are 3 methods:

  • map.keys() – returns an iterable for keys,
  • map.values() – returns an iterable for values,
  • map.entries() – returns an iterable for entries [key, value],

let recipeMap = new Map([
    ['cucumber'500],
    ['tomatoes'350],
    ['onion',    50]
  ]);
  
  // iterate over keys (vegetables)
  for (let vegetable of recipeMap.keys()) {
    alert(vegetable); // cucumber, tomatoes, onion
  }
  
  // iterate over values (amounts)
  for (let amount of recipeMap.values()) {
    alert(amount); // 500, 350, 50
  }
  
  // iterate over [key, value] entries
  for (let entry of recipeMap) { // the same as of recipeMap.entries()
    alert(entry); // cucumber,500 (and so on)
  }

// iterate with foreach
recipeMap.forEach(function(valuekey) {
    console.log(key + ' -> ' + value);
  });


Set 

A Set is a special type collection – “set of values” (without keys), where each value may occur only once.

Its main methods are:

  1. new Set(iterable) – creates the set, and if an iterable object is provided (usually an array), copies values from it into the set.
  2. set.add(value) – adds a value, returns the set itself.
  3. set.delete(value) – removes the value, returns true if value existed at the moment of the call, otherwise false.
  4. set.has(value) – returns true if the value exists in the set, otherwise false.
  5. set.clear() – removes everything from the set.
  6. set.size – is the elements count.

The main feature is that repeated calls of set.add(value) with the same value don’t do anything. That’s the reason each value appears in a Set only once.

For example, we have visitors coming, and we’d like to remember everyone. But repeated visits should not lead to duplicates. A visitor must be “counted” only once.

Set is just the right thing for that:

let set = new Set();

let john = { name: "John" };
let pete = { name: "Pete" };
let mary = { name: "Mary" };

// visits, some users come multiple times
set.add(john);
set.add(pete);
set.add(mary);
set.add(john);
set.add(mary);

// set keeps only unique values
alertset.size ); // 3

for (let user of set) {
  alert(user.name); // John (then Pete and Mary)
}

The alternative to Set could be an array of users, and the code to check for duplicates on every insertion using arr.find. But the performance would be much worse, because this method walks through the whole array checking every element. Set is much better optimized internally for uniqueness checks.








Continue Reading →

Thursday, 1 October 2020

map(), filter(), and reduce() in JavaScript

map → Executes a function on each element of an array

Every element of the array is passed to the callback function and returns a new array with the same length.

When to use map: If we want to perform the same operation/transformation on each element of the array and get back a new array of the same length with the transformed values.

var numbers= [1,2,3,4,5];
var doubled  = numbers.map(n => n * 2);
doubled// [2,4,6,8,10]


filter → Remove items which don’t satisfy a condition

Every element of the array is passed to the callback function. On each iteration, if the callback returns true, then that element will be added to the new array, otherwise, it is not added to the new array.

Use it when: You want to remove unwanted elements based on a condition.

var numbers = [1,2,3,4,5];
var greaterThan2 = numbers.filter(n => n > 2);
greaterThan2// [3,4,5]


Reduce → Creates a single value from elements of Array

While using reduce, we need to declare the initial value of accumulator(final result). On each iteration, inside the callback we perform some operation and that will be added to the accumulator.

Use it when: You want to find a cumulative or concatenated value based on elements across the array.

Example: Sum of numbers

var numbers = [1,2,3,4,5];
var initialVal = 0;
let result=numbers.reduce((accuval=> val + accu , initialVal);
console.log(result// 15
Continue Reading →

Tuesday, 23 October 2018

UI Framework Questions

What is React JS?
ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications. It’s used for handling view layer for web and mobile apps. React also allows us to create reusable UI components.

React allows developers to create large web applications which can change data, without reloading the page. The main purpose of React is to be fast, scalable, and simple. It works only on user interfaces in application. This corresponds to view in the MVC template. It can be used with a combination of other JavaScript libraries or frameworks, such as Angular JS in MVC.

What is Redux
Redux is a predictable state container for JavaScript apps.
Redux makes it easy to manage the state of your application. Another way of looking at this – it helps you manage the data you display and how you respond to user actions.

What is Webpack
Webpack is an open-source JavaScript module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset. Webpack takes modules with dependencies and generates static assets representing those modules.

What is Babel
Babel is a JavaScript compiler.

Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Here are the main things Babel can do for you:

What is the difference between CSS and SASS?
Sass is a preprocessor for CSS, which makes it essentially the same thing as CSS. Being a preprocessor, you code in Sass and later the code is compiled into CSS. It functions as a (amazing) power-up for CSS, enabling features that are yet to exist in CSS. Sass’ main goal is to improve maintainability as your stylesheets getting larger and more complex. Some handy features Sass provided are:
  1. Variables, you can store reusable values with variables, this can be handy to store values like color hex code or a font stack.
  2. Nesting, you can write hierarchical CSS selectors simpler with Sass, just write it in nests just like what we do with HTML elements.
  3. Partials, you can write your stylesheet in a modular way using partials and import statements, improving your code maintainability and readability.
  4.  Mixins, they are like functions which you can define and reuse throughout your stylesheets. For example, sometimes we have to write one declaration for each rendering engine, like border-radius that should be accompanied by -webkit-border-radius, -moz-border-radius and so on. You can group all those border-radius statements into one mixin and just use the mixin whenever you need to define the border-radius for your element. Neat, isn’t it?
  5. Extension and Inheritance, which lets you share a set of CSS properties across your stylesheets.
  6. Mathematical Operators, like +, -, *, /, and % to aid you in determining various numbers throughout your stylesheets.


Continue Reading →

Tuesday, 9 October 2018

JavaScript Inheritance

JavaScript does not have classes unlike other languages. It uses the concept of prototypes and prototype chaining for inheritance.

Let’s implement prototype chaining

//SuperType constructor function
function SuperType(){
    this.name = "Virat"
   }
   
   //SuperType prototype
   SuperType.prototype.getSuperName = function(){
    return this.name
   }
   
   //SubType prototype function
   function SubType(){
    this.age = 26
   }
   
   //Inherit the properties from SuperType
   SubType.prototype = new SuperType();
   
   //Add new property to SubType prototype
   SubType.prototype.getSubAge = function(){
    return this.age;
   }
   
   //Create a SubType object
   var subTypeObj = new SubType();
   console.log(subTypeObj.name); //Output: Virat
   console.log(subTypeObj.age); //Output: 26
   console.log(subTypeObj.getSuperName()); //Output: Virat
   console.log(subTypeObj.getSubAge()); //Output: 26

Above code defines two consructor functions, SuperType and SubType. By default, SubType.prototype has a constructorfunction which points to the constructor function itself and proto property which inherits the default object properties.

//Inherit the properties from SuperType
SubType.prototype = new SuperType();

Now, SubType function has access to all the SuperType properties and methods.

Continue Reading →

Wednesday, 6 April 2016

HTML5 Local and Session Storage

HTML5 Local Storage

Local Storage is a web storage feature that allows you to store key-value pairs in a web browser. It’s part of the Web Storage API and provides a way to persist data across sessions without an expiration date, meaning the data will remain until explicitly deleted.

Key Features of Local Storage:

  1. Capacity: Generally allows around 5-10 MB of data per origin.
  2. Synchronous API: Access to data is synchronous, meaning it can block the main thread, so it's best for smaller amounts of data.
  3. Data Type: Only stores strings. You can use JSON to store objects or arrays.
  4. Persistence: Data persists even after the browser is closed and reopened.
  5. Scope: Data is scoped to the origin (protocol, host, and port), so different domains cannot access each other’s Local Storage.

Common Methods:

  • localStorage.setItem(key, value): Stores a value with the specified key.
  • localStorage.getItem(key): Retrieves the value associated with the specified key.
  • localStorage.removeItem(key): Removes the specified key and its value.
  • localStorage.clear(): Removes all key-value pairs from Local Storage.

Example Usage:

// Storing data
localStorage.setItem('username', 'JohnDoe');

// Retrieving data
const username = localStorage.getItem('username');
console.log(username); // Outputs: JohnDoe

// Removing data
localStorage.removeItem('username');

// Clearing all data
localStorage.clear();

Use Cases:

  • Storing user preferences.
  • Caching data for offline access.
  • Managing user sessions.

Keep in mind that sensitive information should not be stored in Local Storage due to security concerns, as it's accessible via JavaScript.

                                                            HTML5 Session Storage

Session storage is a type of web storage that allows you to store data for the duration of a page session. This means that the data persists as long as the browser tab is open. Once the tab is closed, the data is cleared.

Here are some key points about session storage:

  1. Scope: Data is limited to the window or tab where it was created. Different tabs or windows will not share the same session storage.

  2. Storage Limit: Typically, session storage can hold around 5-10MB of data, though this can vary by browser.

  3. Data Types: You can only store data as strings. To store objects, you'll need to convert them to strings using JSON.stringify() and parse them back using JSON.parse().

  4. API: You can access session storage using the window.sessionStorage object. Common methods include:

    • setItem(key, value): Store a value by key.
    • getItem(key): Retrieve a value by key.
    • removeItem(key): Remove a specific item by key.
    • clear(): Clear all session storage data.
  5. Use Cases: It's commonly used for temporary data, such as user preferences, form inputs during a session, or any data that should not persist beyond the tab being open.

Continue Reading →

Monday, 9 February 2015

The difference between == and === in jQuery/JavaScript

In this post I would like to explain the difference between double (==) and triple (===) equals in JavaScript/jQuery. A quick and short explanation is that == does type coercion (conversion) before checking for equality; and === does strict equation which requires values to have the same type as well.
Here is what it means:
0 == false     // true
0 === false    // false, because they have different types (int, bool)
1 == "1"       // true
1 === "1"      // false, because they have different types (int, string)
null == undefined // true
null === undefined // false
Detailed (longer) explanation
When you use == the javascript interpreter will convert one side of the comparison according to these rules:
  • When comparing a number and a string, the string is converted to a number value.
  • When comparing a boolean, the boolean is converted to 1 if it is true and +0 if it is false.
  • When object is compared with a number or a string, the object is converted to its’ default value (.valueOf().toString()). If these methods are missing a runtime error is thrown.
  • When comparing an object and another object, no type conversion is made. They are equal only if they refer the same object.
When you use === the javascript interpreter will not convert values to primitive types and make sure that the operands have the same value as well as the same type.
"foo" === "foo"  // true, both operands are of type String
new String("foo") === new String("foo")  // false, 2 Objects refer diff object instances
Detailed comparison information can be found on Mozilla Developer Network page. Here is the summary:
  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another
  • Two Boolean operands are strictly equal if both are true or both are false
  • Two distinct objects are never equal for either strictly or abstract comparisons
  • An expression comparing Objects is only true if the operands reference the same Object
  • Null and Undefined Types are == (but not ===)
Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives