I am bit unclear in understanding why this below piece of code is not showing the message box,
http://jsfiddle.net/KendoDev/p8Mk2/
function findMax(var x, var y) {
//alert("x is:" + x + " y is: " +y);
var max = 0;
if(x>y)
max = x;
else
max = y;
alert("max is: " + max);
return max;
}
var c=4,d=9;
var m = findMax(c,d);
http://jsfiddle.net/p8Mk2/1/
function findMax(x,y) {
}
No var statement as explained here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
Your javascript isn't syntactically correct - function findMax(var x, var y) should just be function findMax(x, y).
In general, if you write some javascript and nothing happens when you run it, it probably means something went wrong syntactically, and you should check your browser's Error Console. (In this case, it tells you that the function definition is where the error occurred, right on the first "var".)
Your function syntax is wrong: you don't need var in the parameter list.
function findMax(x, y) {
you do not need to put a var
see updated fiddle
http://jsfiddle.net/p8Mk2/2/
Remove var from arguments. Like this:
function findMax(x, y) {
//alert("x is:" + x + " y is: " +y);
var max = 0;
if(x>y)
max = x;
else
max = y;
alert("max is: " + max);
return max;
}
var c=4,d=9;
var m = findMax(c,d);
Related
I am looking for a way to replace a variable in a function with its actual value. I am going to convert this function into a string and send via a HTTP request and thus need to convert the variables inside the function with their values.
let x = Math.random();
let funcString = function () {
let y = x + 10;
return y;
}.toString();
// Send funcString as a parameter
For eg. in the above code if I send funcString as it is, whoever receiving it will have no idea what is the value of x.
Since I am ultimately sending a string I would like to send
"function () {let y = 0.53 + 10; return y;}" (assuming
Math.random() produced 0.53 at runtime).
Is there any way to do this?
I am doing this in a nodejs project so a npm module would be fine by me too.
Well if you are returning this function as a string, just use String#replace() method to replace x occurrence with its value.
This is how you should use it:
funcString.replace('x', x)
Demo:
let x = Math.random();
let funcString = function () {
let y = x + 10;
return y;
}.toString();
console.log(funcString.replace('x', x));
Edit:
If your variable has many occurrences and can be part of other variables just use a regex with replace method.
funcString.replace(/\bx\b/g, x)
Demo:
let x = Math.random();
let funcString = function () {
let y = x + 10;
let fix ='true';
let z = x * 2;
return y;
}.toString();
console.log(funcString.replace(/\bx\b/g, x));
use replace with regex, g will search all x-es
let x = Math.random();
let funcString = function () {
let y = x + 10;
let a = x + 10;
let b = x + 10;
return y;
}.toString().replace(/x/g, x);
console.log(funcString);
New to JS here, so I apologize if I'm missing something obvious. Trying to build a random number generator (it works in a nested manner, so something like a list of tuples of random number), but I get a OOM error with this code. (Say, if i try to do something like generateList(6))
function generateList(num){
var arr = [];
for(i=0;i<num;i++){
arr.push(generateTuple());
}
return arr;
}
function generateTuple(){
var tuple = [];
for(i=0;i<3;i++){
tuple.push(Math.floor(Math.random() * 300));
}
return '(' + tuple[0] + ',' + tuple[1] + ',' + tuple[2] + ')';
}
OTOH, if I just generate the random numbers individually and return them (instead of using a list), it works without errors. Can anyone enlighten me as to what is going on here?
function generateTuple(){
var a = Math.floor(Math.random() * 300);
var b = Math.floor(Math.random() * 300);
var c = Math.floor(Math.random() * 300);
return '(' + a + ',' + b + ',' + c + ')';
}
EDIT: So basically if you run the code, it gets stuck in some loop, and after a period of time in the console it returns the OOM error. So I assume it's some memory overflow or something somewhere.
You are creating global i by declaring it without var or let, then you loop with it. That creates unprecedented values for i, leading to the loop will never complete. Declare your variables correctly.
for(var i=0;i<num;i++) // better: let i = 0; ...
and
for(var i=0;i<3;i++) // better: let i = 0; ...
Your is are global variables. Always declare variables with const or let (or var) to avoid global pollution and unexpected behavior (like what's happening here).
Each time generateTuple is run, i gets set to 3 at the end of the for loop in generateTuple. So, the i referenced by generateList - which references the same global variable - never has a chance to get any higher than 4. So if you call generateList with higher numbers, you'll get an infinite loop.
Just declare your variables properly:
function generateList(num){
var arr = [];
for(let i=0;i<num;i++){
arr.push(generateTuple());
}
return arr;
}
function generateTuple(){
var tuple = [];
for(let i=0;i<3;i++){
tuple.push(Math.floor(Math.random() * 300));
}
return '(' + tuple[0] + ',' + tuple[1] + ',' + tuple[2] + ')';
}
console.log(generateList(10));
I'm trying to make an increment method. This seemingly easy task has stumped me.
An example of what I want:
var x=5;
x.increment();
console.log(x); //6
What I tried to do:
Number.prototype.increment=function(){
this++; //gave me a parser error
};
Numbers are immutable in javascript. when you do console.log(this) you will see it will point to Number whose primitive value is 5(in our case), so you can not change it's value.
What you can do is return incremental value(by doing this + 1) from incremnt and assign it to x like x=x.increment();
Number.prototype.increment = function(){
return this + 1;
}
var x = 5;
x=x.increment();
console.log(x);
this cannot be changed directly. Try this way
Number.prototype.increment = function(){
return this + 1;
}
var x = 5;
x = x.increment(); // x will be 6 here
Hope this helps.
This question already has answers here:
Surprised that global variable has undefined value in JavaScript
(6 answers)
Closed 7 years ago.
Hi I have a snippet of code. I am confused about change of value x1 when I remove non-related part of same code. I searched about it and I came to know that it has to do with hoisting. But the value x1 is still unclear even with hoisting concept for me. Can someone please make me clear on this?
var x = 10;
function main() {
document.write("<br>x1 is " + x);
x = 20;
if (x > 0) {
var x = 30;
document.write("<br>x2 is " + x);
}
var x = 40;
var f = function(x) {
document.write("<br>x3 is " + x);
}
f(50);
}
main();
The output of this code is:
x1 is undefined
x2 is 30
x3 is 50
If I change this code to:
var x = 10;
function main() {
document.write("<br>x1 is " + x);
}
main();
The output is:
x1 is 10
So what is happening here is a common pitfall.
The simplest way to put this is. When you set var x = 30 inside your main function, you are actually redefining the scope that var x = 10 had for use inside this function. This has to do with how Javascript executes and scope.
By defining x inside the function, your scope for x has changed. Below is an example of what I mean and a version of your code that works
Example:
var test = 'test';
function run(){
console.log(test);
var test=1;
}
Your Code Updated:
var x = 10;
function main() {
console.log("<br>x1 is " + x);
x = 20;
if (x > 0) {
x = 30;
console.log("<br>x2 is " + x);
}
x = 40;
var f = function(x) { console.log("<br>x3 is " + x); }
f(50);
}
main();
Good question btw.
Since this is somewhat of a very interesting scope of how Javascript executes, consider the following code and its outputs to get the full idea
var test = 'test';
function run(){
console.log(test);
test=1;
console.log(test);
var test=2;
console.log(test);
}
console.log(test);
run();
console.log(test);
Very interesting to see how this reacts.
All variable and function declarations get "hoisted" or moved to the top of their scope. The undefined value for x is caused because the var x statement gets moved up to the top of main however the assignment = 30 does not.
So, your code will read more like this:
var x = 10; // x is 10
function main() {
var x; // x declaration is "hoisted"
document.write("<br>x1 is" + x); // x1 is undefined
x = 20; // x is 20
if (x > 0) {
x = 30; // x is 30
document.write("<br>x2 is" + x);// x2 is 30
}
x = 40; // x is 40
var f = function(x) { // x is 50
document.write("<br>x3 is" + x);// x3 is 50
}
f(50);
}
main();
You can read more about Hoisting here: JavaScript Scoping and Hoisting
I am pretty new in JavaScript and I have a litle doubt.
I have created this JSFiddle: https://jsfiddle.net/AndreaNobili/1up938xf/
I have defined only the JavaScript function that perform a simple sum (no HTML) and that show the result into a popup by an alert
var add = function(x, y) {
z = z + y;
return z;
}
var sum = add(2, 3);
alert(sum);
The problem is that when I try to run this test application I can't see anything. Why? What am I missing?
This is pretty easy to fix, actually.
One: your adding function doesn't actually add correctly. It should be, x + y not z + y
function(x, y) {
z = x + y;
return z;
}
It was causing an error because you were trying to use a variable you never declared or assigned (z + y)
That is probably because you are calling z instead of x and tbe first time, z is no defined yet
ReferenceError: z is not defined
and your missing a var. Define z first or (more likely) use x instead:
var add = function(x, y) {
var z = x + y;
return z;
}
var sum = add(2, 3);
alert(sum);
And here is a Fiddle: https://jsfiddle.net/1up938xf/1/
You are using "z = z + y;" but you want "z = x + y;"
First one causes a JS error and the alert is not shown