Why I can't perform this simple JavaScript test program into a JSFiddle?

158 Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

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)

0
On

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/

0
On

That is probably because you are calling z instead of x and tbe first time, z is no defined yet

0
On

You are using "z = z + y;" but you want "z = x + y;"

First one causes a JS error and the alert is not shown