Re-declaring arrow function [duplicate] - javascript

This question already has answers here:
Why let and const keyword variables are not allowed to redeclaration in JavaScript, where var keyword variable is allowed?
(1 answer)
delete or override const variables in javascript Harmony / ECMAScript 6
(2 answers)
Why reassigning const producing error in console only if we do that in code editor? [duplicate]
(1 answer)
Closed 10 hours ago.
tried to re-declare an arrow function-- (Check code)
Why is it giving error when var can be redeclared.
I made an arrow function using var then tried re-declaring it using let as var can be redeclared. But why is it giving error?

If you declare a variable with var, you can redeclare a variable with var as many times as you like, but it will error if you redeclare with let or const. With let and const, you can only declare a variable one.
What you probably meant to do is reassign the variable, which you can do as many times as you want with var or let, just don't add var or let again.
Redeclaring
// valid, but not advised
var cube = (num) => num * num * num;
var cube = (num) => num * num * num;
// invalid
var cube = (num) => num * num * num;
let cube = (num) => num * num * num;
// invalid
var cube = (num) => num * num * num;
const cube = (num) => num * num * num;
Reassigning
// valid
var cube = (num) => num * num * num;
cube = (num) => num * num * num;
// valid
let cube = (num) => num * num * num;
cube = (num) => num * num * num;
// invalid - can't change a const
const cube = (num) => num * num * num;
cube = (num) => num * num * num;

Related

I've created a variable which is supposed to generate random number between 0 and 4 but it is only showing the output as 1

var randomNumber = Math.floor(Math.random() *3);
Output
randomNumber should be a function which returns a number. Right now it is just a variable that has been assigned a value once and you are logging the same value.
var randomNumber = () => Math.floor(Math.random() *3);
console.log(randomNumber());
console.log(randomNumber());
console.log(randomNumber());
console.log(randomNumber());
Though in the question there's a misunderstanding of how variables in JS work, it's possible to do very near to something similar with JS by using objects.
All objects have a method named valueOf, which returns the primitive value of the object when it's needed. This method is often called internally when JS makes implicit type conversions. This method can also be overridden, you can write your own valueOf method, and JS will use that method instead of the built-in method. Like this:
// RandomNumberGenratorFactory
function randomNumber(min, max, dec) {
// min: The lower limit of the rnd <Number>
// max: The upper limit of the rnd <Number>
// dec: The count of decimals of the rnd <Integer>
// dec > 0, if int <= 0 or omitted, an integer rnd will be returned
// Swap min/max if needed
if (max < min) {
[max, min] = [min, max];
}
// Prepare to create an integer rnd
let fn = Math.floor,
fix = 1;
if (dec > 0) {
// Prepare to create a decimal rnd
fn = x => +x.toFixed(dec);
fix = 0;
}
return {
// Shadows the original valueOf method
valueOf: () => fn(Math.random() * (max - min + fix) + min)
};
}
// Create random number generators
const rnd = randomNumber(-4, 4),
rnD = randomNumber(1, 5, 3);
// The generator variable itself refers to an object
console.log(rnd);
for (let n = 0; n < 10; n++) {
// Getting numeric value of the generators by unary plus operator
const r = +rnd;
console.log(r, +rnD);
}
// Generator evaluates to a number when used with operators
console.log(rnD + rnd - rnD * rnd);
The reason why your code didn't work, is that Math.floor(Math.random() *3); returns a primitive (a number in this case), and primitives are just values, they're not linked to the expression or function which originally created the value.

Create a random number multiple times in JS

I want to generate a random number in Javascript 6 times. I've got the random variable declared and properly functioning. I just need to replicate it six times without logging it six separate times.
const randRoll = Math.floor(Math.random() * 10) + 10;
How would I go about this?
The proper way of doing this is using for loop
let randomNumbers = [];
for(let i = 0; i < 6; i++) {
randomNumbers.push(Math.floor(Math.random() * 10) + 10);
}
You can also do something like this
let randomNumbers = new Array(6).fill(0).map((v) => Math.floor(Math.random() * 10) + 10);
To create a random number in Javascript, the math.random() function is used. JavaScript math.random() generates a random decimal value between 0 and 1.
const random_num = Math.floor(Math.random() * 10); console.log(random_num);
As you can see,In the above example, I used the Math.floor() function to round our random number up to become a random integer, used “* 10” to generate a number between “1” and “10”.
If you need generate a number ( 1 to 100 ) you can multiply generated number by 100 and so on “* maxNumberHer”.
Random Number Between Two Values
Math.floor(Math.random() * (max - min) + min)
Between 900 to 1000
const generateRandomNum = (min, max) => Math.floor(Math.random() * (max - min) + min) console.log(generateRandomNum(900, 1000))
about Repeat 6 times
You can use for loop
for (let i = 0; i < 6; i++) { console.log(generateRandomNum(900, 1000)); }

Implementing Binomial DIstribution in JavaScript error?

I'm just hoping someone could double check my implementations to make sure everything is correct on the math and JS sides. I'm wondering where my implementation went wrong b/c the formulas do not compute the same probabilities, specifically probability_three seems to have a computation error I cannot find.
Here's the JSFiddle: https://jsfiddle.net/s73Lh1fk/5/
There are 3 functions I'm hoping to get reviewed.
probability_one
probability_two
probability_three
The formulas are as follows.
P(d, n) = 1 - (d - 1 / d)^n
P(d, n, o) = 1 - (d - (d - o + 1) / d)^n
P(d, n, o, k) = nCk * (p * k) * q^(n−k)
for nCk, I implemented https://www.calculatorsoup.com/calculators/discretemathematics/combinations.php
function factorialize(num) {
// Step 1. Create a variable result to store num
var result = num;
// If num = 0 OR num = 1, the factorial will return 1
if (num === 0 || num === 1)
return 1;
// Instatiate the while loop
while (num > 1) {
// Decrement by 1
num--
// Update the result
result *= num
}
// Return
return result;
}
function nCr(n, r){
// Compute n factorial
var nFact = factorialize(n)
// Compute r factorial
var rFact = factorialize(r)
// Compute n - r factorial
var nrFact = factorialize(n - r)
// Compute nCr
var result = (nFact / (rFact * nrFact))
// Return
return result
}
If you need any more information, please don't hesitate to ask. I'll do my best to provide it.
For example:
The result here is 9.75%
function probability_one() {
// Get number of dice
var n = document.getElementById("n1").value
// Get sides on each die
var d = document.getElementById("d1").value
// Calculate
var prob = 1 - ((d - 1) / d)**n
prob = parseFloat(prob*100).toFixed(2)+"%"
prob = `<B>${prob}</B>`
// Print the probability
var p = document.createElement('p')
p.innerHTML = prob
document.getElementById("output1").appendChild(p)
}
The result here is 9.75%
function probability_two() {
// Get number of dice
var n = document.getElementById("n2").value
// Get sides on each die
var d = document.getElementById("d2").value
// Get the specific outcome
var o = document.getElementById("o2").value
// Calculate
var prob = 1 - ((d - (d - o + 1)) / d)**n
prob = parseFloat(prob*100).toFixed(2)+"%"
prob = `<B>${prob}</B>`
// Print the probability
var p = document.createElement('p')
p.innerHTML = prob
document.getElementById("output2").appendChild(p)
}
The result here is 18.00%, not 9.75%
function probability_three(){
// USER INPUTS
// Get number of dice
var n = document.getElementById("n3").value
// Get sides on each die
var d = document.getElementById("d3").value
// Get the value that defines a success
var o = document.getElementById("o3").value
// Get the number of success needed
var k = document.getElementById("k3").value
// CALCULATIONS
// p
var p = ((d - o) + 1)/10
console.log(`p: ${p}`)
// q
var q = (1 - p)
console.log(`q: ${q}`)
// nCr
var vnCr = nCr(n, k)
console.log(`nCr: ${vnCr}`)
// p**k
var pk = p**k
console.log(`p**k: ${pk}`)
// q**n-k
var pnk = q**(n-k)
console.log(`q**n-k: ${pnk}`)
// Probability
var prob = (vnCr * pk * pnk) / (p + q)**n
console.log(`Prob.: ${prob}`)
prob = parseFloat(prob*100).toFixed(2)+"%"
prob = `<B>${prob}</B>`
// Print the probability
var p = document.createElement('p')
p.innerHTML = prob
document.getElementById("output3").appendChild(p)
}

Storing random generated number in a variable, why does the value not change?

The first time I type the random variable in the console I get a number between 1 and 10 which is expected. Then every time I retype the random variable it gives me the same number. Why is this?
var random = Math.floor(Math.random() * 10) + 1;
Instead of using a variable, you should create a function to generate a random number.
const random = () => Math.floor(Math.random() * 10) + 1;
const number1 = random();
const number2 = random();
const number3 = random();
console.log(number1, number2, number3);
Also this is useful,
const randomVariable = function () {
return Math.floor(Math.random() * 4);
};
randomVariable();

JS: Return a number to a specified power of 10

I'm working on a problem that requires me to return a number rounded to a specified power of 10. For example:
1234, specified power = 2 => 1200
1234, specified power = 3 => 1000
I did find a solution to the problem with this function:
const roundToPower = (num, pow) => {
return Math.round(num / Math.pow(10, pow)) * Math.pow(10,pow)
};
However, I am not exactly sure how and why it works.
Is someone able to break it down for me? Thanks!
Lets divide the upper function into three parts
num / Math.pow(10, pow) will divide the given number by the power of 10 which is given. e.g for pow = 3 num will be divided by 1000
It then uses use Math.round() on that decimal.
Then again to equalize the division we did in first step it multiples again with power of ten Math.pow(10,pow)
Example
For pow = 3 and num = 1230
=> Math.round(1230 / Math.pow(10, 3)) * Math.pow(10, 3)
=> Math.round(1230 / 1000 )) * 1000
=> Math.round( 1.230 )) * 1000
=> 1 * 1000
=> 1000
I know that question is not about how to convert numbers to a specified power of 10. I know a better and simple way to do this. Maybe it can help.
let a = 1234;
a = convert(a,2);
console.log(a); // 1200
let b = 123456;
b = convert(b,5);
console.log(b); //123460
function convert(num, power){
if(power < String(num).length){
num = num.toPrecision(power);
num = Number(num).toFixed();
return num;
}
else{
console.log("Invalid power for number: " + num);
}
}

Categories

Resources