javascript scope : retain global variable value after a function - javascript

When the 'hypotenuse' function is called the value of 'x' changes from 1. Fix it so that 'x' is still 1 in the gobal scope.
var x = 1;
var y = 1;
function hypotenuse(a , b) {
var cSquared = a * a + b * b;
x = Math.sqrt(cSquared);
return x;
}
hypotenuse(x, y);

All you need to do to make this happen is redeclare the x variable using var within the function. This is will declare the x variable within the scope of the function, leaving the original, globally scoped x variable untouched:
var x = 1;
var y = 1;
function hypotenuse(a , b) {
var cSquared = a * a + b * b,
x = Math.sqrt(cSquared);
return x;
}
hypotenuse(x, y);
Or, using the code style which you originally adopted (splitting out var declarations):
var x = 1;
var y = 1;
function hypotenuse(a , b) {
var cSquared = a * a + b * b;
var x = Math.sqrt(cSquared);
return x;
}
hypotenuse(x, y);
For more detailed info on what is happening here, read up on javascript scope

Try this:
var x = 1;
var y = 1;
function hypotenuse(a, b) {
var cSquared = a * a + b * b;
var x = Math.sqrt(cSquared);
return x;
}
//console.log(hypotenuse(x, y));
//console.log('x = ' + x);

Related

Trying to call a hasChildNodes method but getting cannot read property of Null

I'm attempting to make a simple turn-based two player game (like FE) as practice for an upcoming project. In trying to ensure that no characters overlap on the same grid tile, I tried to make a validator function that I can call for each character on generation (randomly generated locations), so that I wouldn't have the same script with minor changes in each character gen section. My original code (without the function) is above, the most recent attempt (with some context) is below:
function bTeamCharGen() {
var a = 10;
var b = 15;
var c = 0;
var d = 5;
var bTeamLead = document.createElement("img");
bTeamLead.src = "images/transp_img.gif";
bTeamLead.height = "38";
bTeamLead.width = "38";
bTeamLead.className = "lead";
bTeamLead.id = "bLead";
genStartPos();
var curr = document.getElementById("gridBlock_" + i + "_" + j);
if (curr.hasChildNodes()) {
while (curr.hasChildNodes()) {
genStartPos(a, b, c, d);
}
}
document.getElementById("gridBlock_" + i + "_" + j).appendChild(bTeamLead);
document.getElementById("bLead").style.background = "url('images/eirika_1_1.gif') 0 0";
document.getElementById("bLead").style.backgroundRepeat = "no-repeat";
//commented out basic structure for further characters here
}
This is the original code for one of the characters. The following is what I've currently arrived at (and still with the Uncaught TypeError):
var i, j;
//functions to generate grid and background
function genStartPos(minX, maxX, minY, maxY) {
i = Math.floor(Math.random() * (maxX - minX + 1) + minX);
j = Math.floor(Math.random() * (maxY - minY + 1) + minY);
}
function validStartPos() {
genStartPos();
var curr = document.getElementById("gridBlock_" + i + "_" + j);
if (curr.hasChildNodes()) {
while (curr.hasChildNodes()) {
genStartPos(a, b, c, d);
}
}
}
function bTeamCharGen() {
var a = 10;
var b = 15;
var c = 0;
var d = 5;
var bTeamLead = document.createElement("img");
bTeamLead.src = "images/transp_img.gif";
bTeamLead.height = "38";
bTeamLead.width = "38";
bTeamLead.className = "lead";
bTeamLead.id = "bLead";
validStartPos();
document.getElementById("gridBlock_" + i + "_" + j).appendChild(bTeamLead);
document.getElementById("bLead").style.background = "url('images/eirika_1_1.gif') 0 0";
document.getElementById("bLead").style.backgroundRepeat = "no-repeat";
//commented out basic structure for further characters here
}
function initialise() {
makeGrid();
setBackground();
bTeamCharGen();
rTeamCharGen();
}
It's a bit long and unwieldy, as I'm still trying to neaten it up quite a bit, but everything else worked until I did this. I'm calling the initialise function as an onload for the body, and the <script> is within the <head>, since I had problems earlier on when having it within <body>.
I'm not sure, but... I think you trying get element when "gridBlock_" + i + "_" + j is undefined
You calling genStartPos() without any parameter. So your i and j are undefined, so you string with element id.
If you cant pass variables to genStartPos(), you need to make some default value for maxX, maxY...
PS you also calling genStartPos(a, b, c, d) when a, b, c, d are undefined. Or maybe this just not all code you show

What's the best way to allocate the variables with multiple combinations

I want to reduce the initialization of multiple combination variables.
My aim is to create a function and pass a function with variable.
If I pass a variable x into function value(x); I should get output as "123". Similarly, if I pass a variable xy into function value(xy), then I should get output as "123456". Basically, I want to concatenate variables
Here is the javascript code as
var x = "123";
var y = "456";
var z = "789";
var a = "0-+";
var xy = x + y;
var yz = y + z;
var zx = z + x;
var xa = x + a;
var ya = y + a;
var za = z + a;
var ax = a + x;
var ay = a + y;
var az = a + z;
var xz = x + z;
var yx = y + x;
var zx = z + x;
var zy = z + y;
var xyz = x + y + z;
var xyza = x + y + z + a;
function value(input) {
console.log(input);
}
Sample execution as follows:
value(x); //output: 123
value(y); //output: 456
value(xy); //output: 123456
value(za); //output: 7890-+
In this case, there are lots of combination for the above variables i have defined to meet all possible combinations. I want to validate the user input from the above combination and also i dont want to write so many variables. Is there any possible easy solution ?
Please suggest. Thanks
I would declare a global object to store the variables as keys:
var globals = {
"x": "123",
"y": "456",
"z": "789"
};
Note that you can refer to your "variables" by globals.x, or globals.y (you can replace globals with a shorter keywork to reduce code of course).
It is a little extra effort to define the "variable names" with quotes.
However, now you get to use:
alert(Combinate("xz"));
// output: 123789
With a function like:
function Combinate(phrase) {
result = "";
for (var i = 0, len = phrase.length; i < len; i++) {
result += globals[phrase[i]];
}
return result;
}
Here's a JSFiddle.
You'll want to use some form of iterating over an array or object. As an example:
var x = "dave";
var y = "bill";
var z = "john";
var a = "suzan";
var people = [x,y,z,a];
for(i=0; i<people.length; i++) {
for(x=0; x<people.length; x++) {
value(people[i] + people[x]);
for(y=0; y<people.length; y++) {
value(people[i] + people[x] + people[y]);
for(z=0; z<people.length; z++) {
value(people[i] + people[x] + people[y] + people[z]);
}
}
}
}
// not sure why you'd have a function to wrap console.log(), but...
function value(input) {
console.log(input);
}
See in action on jsFiddle.
There are more elegant paths, but this should get you on the road to learning about JavaScript.

How to take plus sign in variable

I want to calculate two numbers and its pretty simple.
But Is there any way to take operator in variable and then do the calculation?
var x = 5;
var y = 5;
var p = '+';
var z = x + p + y;
$(".button").click(function() {
alert(z);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click ME !</div>
Avoid eval whenever possible. For this example, a simple switch...case statement will be sufficient:
var x = 5;
var y = 5;
var z;
var p = "+";
switch (p) {
case "+":
z = x + y;
break;
case "-":
z = x - y;
break;
}
You can also use a map of functions:
var fnlist = {
"+": function(a, b) { return a + b; },
"-": function(a, b) { return a - b; }
}
var x = 5;
var y = 5;
var p = "+";
var z = fnlist[p](x, y);
Or use parseInt on the string which you will be adding the variable to:
var x = 5;
var y = 5;
var p = '-';
var z = x + parseInt(p + y);
$(".button").click(function(){
alert(z);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click ME !</div>
You are looking for eval function:
var x = 5;
var y = 5;
var p = '+';
var z = x + p + y;
$(".button").click(function(){
alert(eval(z));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click ME !</div>
However, you have to remember that using eval function is potentially risky. For example, if used in the wrong way it can allow one to make injection attacks. Debugging can be also more difficult. I suggest to read this question.
you can use the eval function:
var x = 5;
var y = 5;
var p = '+';
var z = eval(x + p + y);
alert(z);

var x, y = 'foo'; Can this be accomplished?

Since it is possible to do:
var x = 'foo', y = 'foo';
Would this also be possible?
var x, y = 'foo';
I tried it, however x becomes undefined.
I know this may seem like a silly or redundant question, but if I'm curious about something, why not ask? Also you will probably wonder why I would need two variables equal to the same thing in scope. That is not the point of the question. I'm just curious.
Not sure if this is what you're asking, but if you mean "Can I assign two variables to the same literal in one line without typing the literal twice?" then the answer is yes:
var x = 10, y = x;
You need two separate statements to get the exact same semantics.
var x, y; x = y = 'foo';
// or
var x = 'foo'; var y = x;
// or
var y; var x = y = 'foo';
The solution other users are suggesting is not equivalent as it does not apply the var to y. If there is a global variable y then it will be overwritten.
// Overwrites global y
var x = y = 'foo';
It is a good practice to correctly apply var to local variables and not omit it for the sake of brevity.
You can do
var x = y = 'test'; // Edit: No, don't do this
EDIT
I just realized that this creates/overwrites y as a global variable, since y isn't immediately preceded by the var keyword. So basically, if it's in a function, you'd be saying "local variable x equals global variable y equals …". So you'll either pollute the global scope, or assign a new value to an existing global y variable. Not good.
Unfortunately, you can't do
var x = var y = 'test'; // Syntax error
So, instead, if you don't want to pollute the global scope (and you don't!), you can do
var x, y;
x = y = 'test';
In order for that to work, you will either need to initialize them separately (like your first example) or you will need to set them in a separate statement.
// This causes bugs:
var x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x = y = 'test'; }
doSomething();
console.log( y ); // test !?
On the other hand:
// this does not
var x,y; x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x,y; x = y = 'test'; }
doSomething();
console.log( y ); // 3 -- all is right with the world.
Below is my test function. The currently uncommented line in the pollute function does what you were looking for. You can try it and the other options in jsfiddle here.
var originalXValue = 'ekis';
var originalYValue = 'igriega';
var x = 'ekis';
var y = 'igriega';
function pollute()
{
// Uncomment one of the following lines to see any pollution.
// x = 'ex'; y = 'why'; // both polluted
// var x = 'ex'; y = 'why'; // y was polluted
// var x = y = 'shared-ex'; // y was polluted
var x = 'oneline', y = x; // No pollution
// var x = 'ex', y = 'ex'; // No pollution
document.write('Pollution function running with variables<br/>' +
'x: ' + x + '<br/>y: ' + y + '<br/><br/>');
}
pollute();
if (x !== originalXValue && y !== originalYValue)
{
document.write('both polluted');
}
else if (x !== originalXValue)
{
document.write('x was polluted');
}
else if (y !== originalYValue)
{
document.write('y was polluted');
}
else
{
document.write('No pollution');
}
Note that although
var x = y = 'test';
is legal javascript
In a strict context (such as this example):
function asdf() {
'use strict';
var x = y = 5;
return x * y;
}
asdf();
You will get:
ReferenceError: assignment to undeclared variable y
to have it work without error you'd need
var x, y;
x = y = 5;
You'd use var x, y = 'foo' when you want to explicitly initialize x to undefined and want to restrict the scope of x.
function foo() {
var x, y = 'value';
// ...
x = 5;
// ...
}
// Neither x nor y is visible here.
On the other hand, if you said:
function foo() {
var y = 'value';
// ...
x = 5;
// ...
}
// y is not visible here, but x is.
Hope this helps.
Source: http://www.mredkj.com/tutorials/reference_js_intro_ex.html
I would avoid being tricky. Since I only use one variable per var (and one statement per line) it's really easy to keep it simple:
var x = "hello"
var y = x
Nice, simple and no silly issues -- as discussed in the other answers and comments.
Happy coding.
I am wondering why nobody posted that yet, but you can do this
var x, y = (x = 'foo');
You can't do
var a = b = "abc";
because in that case, b will become a global variable.
You must be aware that declaring a variable without var makes it global. So, its good if you follow one by one
var a = "abc";
var b = a;

Returning multiple values in javascript?

Is there a way to use a sort of the C#-like out or ref parameter modifiers with Javascript to do something like this:
function myManyReturnFunction(number1, number2, out x, out y) {
x = number1 * number2;
y = number1 / number2;
return true;
}
var height1, height2 = 0;
var check = myManyReturnFunction(1,1, out height1, out hight2);
I would like to change the variable's reference as well. So yes, passing an argument by reference.
function myManyReturnFunction(number1, number2) {
return {
x: number1 * number2,
y: number1 / number2
}
}
And you don't need x and y parameters, simply call:
var result = myManyReturnFunction(6, 9);
var x = result.x;
var y = result.y;
You can create an "object"...
function getObj(){
var objOut = new Object();
objOut.name = "Smith";
objOut.State = "Arkansas";
return objOut;
}
If you define the 'out' variables in the global scope outside if your function they can be reassigned inside the function with something like this:
var height1 = 0, height2 = 0;
function myManyReturnFunction(number1, number2) {
height1 = number1 * number2;
height2 = number1 / number2;
return true;
}
var check = myManyReturnFunction(1,1);
You can also create an object, which you can then pass to your function, which can be modified within the function like so:
var myValues = {}
function setValues(num1, num2, vals) {
vals.x = num1 * num2;
vals.y = num1 / num2;
return True;
}
setValues(1, 1, myValues);
There are several ways to return multiple values in JavaScript. You've always been able to return multiple values in an array:
function f() {
return [1, 2];
}
And access them like this:
var ret = f();
document.write(ret[0]); // first return value
But the syntax is much nicer in JavaScript 1.7 with the addition of destructuring assignment (if you're lucky enough to be targeting an environment guaranteed to support it (e.g. a Firefox extension)):
var a, b;
[a, b] = f();
document.write("a is " + a + " b is " + b + "<br>\n");
Another option is to return an object literal containing your values:
function f() {
return { one: 1, two: 2 };
}
Which can then be accessed by name:
var ret = f();
document.write(ret.one + ", " + ret.two);
And of course you could do something really horrible like modify global scope or even set properties on the function itself:
function f() {
f.one = 1;
f.two = 2;
}
f();
document.write(f.one + ", " + f.two);
More reading (and the source of some of these examples):
https://developer.mozilla.org/en/New_in_JavaScript_1.7#Destructuring_assignment_(Merge_into_own_page.2fsection)
You can return non-primitive types:
function blah() {
return { name: 'john', age: 23 };
};
var x = blah();

Categories

Resources