'Why var keyword is used here?
Here in the below function, we are converting a data url to blob.
Actually I am writing a component that can crop an image...if I use const..then the screen freezes ... and nothing happens...only after using var it seems to be working.
const dataURLtoBlob = (dataurl) => {
var arr = dataurl.split(",");
var mime = arr[0].match(/:(.*?);/)[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
n--;
while (n) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
};
Why var is used here? Is it because var can be reassigned and modified?
Solution 1:[1]
In javascript there are 3 ways to declare a variable, var, let, const.
var is global scoped, which means it can be read on the whole function if you declare it inside it, so even if you declared a variable inside the while you wrote you could read it outside it.
let is block scoped, which means it can only be read from the block you declared it in. So if you declared a variable on the while you wrote you could only read it inside the while block.
And const is just like let but it can't be reassigned.
In your case all your variables are declared on the same block and are never reassigned, so let, var and const would work the same way. The most correct way to declare them would be const though, as they are never reassigned, but all would work.
Here's more info: https://www.geeksforgeeks.org/difference-between-var-let-and-const-keywords-in-javascript/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Layer891203 |
