Javascript How to define multiple variables on a single line? - javascript

Reading documentation online, I'm getting confused how to properly define multiple JavaScript variables on a single line.
If I want to condense the following code, what's the proper JavaScript "strict" way to define multiple javascript variables on a single line?
var a = 0;
var b = 0;
Is it:
var a = b = 0;
or
var a = var b = 0;
etc...

Using Javascript's es6 or node, you can do the following:
var [a,b,c,d] = [0,1,2,3]
And if you want to easily print multiple variables in a single line, just do this:
console.log(a, b, c, d)
0 1 2 3
This is similar to #alex gray 's answer here, but this example is in Javascript instead of CoffeeScript.
Note that this uses Javascript's array destructuring assignment

You want to rely on commas because if you rely on the multiple assignment construct, you'll shoot yourself in the foot at one point or another.
An example would be:
>>> var a = b = c = [];
>>> c.push(1)
[1]
>>> a
[1]
They all refer to the same object in memory, they are not "unique" since anytime you make a reference to an object ( array, object literal, function ) it's passed by reference and not value. So if you change just one of those variables, and wanted them to act individually you will not get what you want because they are not individual objects.
There is also a downside in multiple assignment, in that the secondary variables become globals, and you don't want to leak into the global namespace.
(function() { var a = global = 5 })();
alert(window.global) // 5
It's best to just use commas and preferably with lots of whitespace so it's readable:
var a = 5
, b = 2
, c = 3
, d = {}
, e = [];

There is no way to do it in one line with assignment as value.
var a = b = 0;
makes b global. A correct way (without leaking variables) is the slightly longer:
var a = 0, b = a;
which is useful in the case:
var a = <someLargeExpressionHere>, b = a, c = a, d = a;

Why not doing it in two lines?
var a, b, c, d; // All in the same scope
a = b = c = d = 1; // Set value to all.
The reason why, is to preserve the local scope on variable declarations, as this:
var a = b = c = d = 1;
will lead to the implicit declarations of b, c and d on the window scope.

Here is the new ES6 method of declaration multiple variables in one line:
const person = { name: 'Prince', age: 22, id: 1 };
let {name, age, id} = person;
console.log(name);
console.log(age);
console.log(id);
* Your variable name and object index need be same

Specifically to what the OP has asked, if you want to initialize N variables with the same value (e.g. 0), you can use array destructuring and Array.fill to assign to the variables an array of N 0s:
let [a, b, c, d] = Array(4).fill(0);
console.log(a, b, c, d);

note you can only do this with Numbers and Strings
you could do...
var a, b, c; a = b = c = 0; //but why?
c++;
// c = 1, b = 0, a = 0;

do this if they have same value
let x = y = z = 0
otherwise
let [x, y, z] = [10, 30, 50]
console.log(x, y, z) // 10 30 50

The compressed type of that is here:
var a, b = a = "Hi";
& for 3 variables:
var x, y, z = x = y = "Hello";
Hope to be helpful!

This is completely correct:
var str1 = str2 = str3 = "value";
And if change one of their value, the value of other variables won't change:
var str1 = str2 = str3 = "value";
/* Changing value of str2 */
str2 = "Hi Web!";
document.write("str1 = " + str1 + " - str2 = " + str2 + " - str3 = " + str3);

Related

New to JS, Can't Fix Errors With School Project

I'm working on a project for a computers class, and am new to JavaScript. I keep getting NaN for output, and have looked for answers and haven't found any. (Project is a compound interest calculator and UI design is done.)
I'm not really sure what to try, cause I'm a JS newbie.
var i = getNumber("amountInput");
var c = getNumber("compoundedInput");
var l = getNumber("lengthInput");
var r = getNumber("rateInput");
var rc = r / c;
var cl = c * l;
onEvent("calculateButton", "click", function() {
var rca = 1 + rc;
var p = Math.pow(rca, cl);
var f = i * p;
setText("outputArea", f);
});
Output should be a number, but I am getting NaN.
You need to set all the variables inside the onEvent function, so that you get the values of the inputs after the user clicks the button. You're setting them when the page is first loaded, and the inputs will be empty at that time.
onEvent("calculateButton", "click", function() {
var i = getNumber("amountInput");
var c = getNumber("compoundedInput");
var l = getNumber("lengthInput");
var r = getNumber("rateInput");
var rc = r / c;
var cl = c * l;
var rca = 1 + rc;
var p = Math.pow(rca, cl);
var f = i * p;
setText("outputArea", f);
});
NaN in JS means 'not a number'. (mdn reference)
Usually, you would see NaN when you're trying to convert a non-numeric string to a number, either explicitly (e.g. parseFloat('3')), or implicitly (e.g. the expression 3 * 'a' will implicitly try to convert 'a' to a number). Worth noting, dividing by zero does not give NaN in JS (it gives infinity or -infinity); however, 0/0 also gives NaN.
For your use case, you're expecting getNumber to return a numeric, but it seems like it isn't. Look at your getNumber code (or copy it in your question).
if you want to get number from input in html you cant use getNumber()
<input type="text" id="number" >
<button id="submit">Submit</button>
and for geting the number:
const number = documnet.getElementById('number');
const submitBtn = document.getElementById('submit');
submitBtn.addEventListener('click', () => {
const plusOne = 1 + Number(number.value);
console.log(plusOne)
});

JS do ... while

It seems to me that i misunderstand the behavior of the do ... while loop in JS.
Let's say we have a code like:
var a = [1,2,3,4,5];
var b = [];
var c;
do {c = a[Math.floor(Math.random()*a.length)];
b.push(c);}
while(c===4);
console.log(b);
Which is intended to roll out random item from array a if that item is not 4.
But if we roll several times we'll see that it doesn't actually prevent 4 from getting to array b. Why? I thought that it would work like this:
Roll random item from array a, store it to c and push c to b;
Check if (c===4) is true;
If it is — go to paragraph 1;
If it's not — log b to console.
Where am I mistaking and why does this code work in such a way? What are others way to 'ban' some item from array from being rolled randomly (except filtering the array) if this approach can't help me?
Do while runs and THEN checks. So it will get a random number from A, store that in C and push that to B, and THEN if C is 4, it will do another loop.
So if C is 4, it will still push it to B, it just won't continue after that.
You could do it like this:
var a = [1,2,3,4,5];
var b = [];
var c = a[Math.floor(Math.random()*a.length)];
while (c !== 4) {
b.push(c);
c = a[Math.floor(Math.random()*a.length)];
}
console.log(b);
I think this is what you're trying to do? Continuously push a random item from A into B unless you get the result 4, in which case, quit and go to console.log?
As explained by the commenters, you're still pushing 4. You can avoid it by make it very explicit what happens when.
var a = [1,2,3,4,5];
var b = [];
var c;
var keep_going = true;
while (keep_going) {
c = a[Math.floor(Math.random()*a.length)];
if (c === 4) {
keep_going = false;
} else {
b.push(c);
}
}
console.log(b);
So the way your code is written, you are not "bannning" 4 from being added to b. The code you have written will add a value from a to b and, if the value added equals 4, continue to add values from a to b until the last value added does not equal 4. So you will get results like:
b == [1];
b == [5];
b == [4,1];
b == [4,4,4,4,4,4,3];
Since do-while is a looping mechanism, I'm assuming you want to keep trying to add a value from a to b until you find one that is not 4. That would be
var a = [1,2,3,4,5],
b = [],
c;
do {
c = a[Math.floor(Math.random()*a.length)];
if(c!==4) { b.push(c); }
} while(c===4);
console.log(b);
This will produce the following values for b
b == [1];
b == [2];
b == [3];
b == [5];

How to write a loop with JavaScript

I try to make code like this:
var code1 = a, code2 = b, code3 = c;
var x = 3;
for (y = 1; y <= x; y++) {
//this part where i dont know about
alert ();
}
So how to make it alert code1, code2, and code3? I mean this alerts the values a, b, and c.
I tried with alert("code"+y); and alert(code+y); but it wont do.
So how to make it alert code1, code2, and code3? i mean this alert the value a, b, and c?
The best way is to use an array instead of discrete code1, code2, and code3 variables:
// (I assume a, b, and c have already been declared somewhere, or that your real
// code has literals?)
var codes = [a, b, c];
var y;
for (y = 0; y < codes.length; y++) {
alert(codes[y]);
}
(Note that I started y in a different place.)
While it's possible to do the code1, code2, code3 thing with global variables, global variables should be avoided whenever possible, and it's nearly always possible. (It's also possible with local variables, but you have to use eval or its cousin the Function constructor, and avoiding eval is also something you should avoid whenever possible, and is nearly always possible. :-) )
Alternately, if you find yourself wanting to do this where an array doesn't quite make sense, you can use an object instead:
var codes = {
code1: a,
code2: b,
code3: c
};
var y;
for (y = 1; y <= 3; ++y) {
alert(codes["code" + y]);
}
That works because in JavaScript, you can access an object property using either dot notation and a literal (obj.foo), or brackets notation and a string (obj["foo"]), and in the latter case the string can be the result of any expression. Since "code" + y is code1 when y is 1, codes["code" + y] looks up the property "code1" on codes (when y is 1).
Use Bracket notation
alert(window["code"+y]);
I would rather recommend you to use an array like
var code = [1, 2, 3];
for (y = 0; y < code.length; y++) {
alert(code[y]);
}

Manipulate replace string in javascript

I have three variables in javascript like
var a = document.getElementById("txtOrderNumberRelease1").value;
var b = document.getElementById("txtOrderNumberRelease2").value
var c = document.getElementById("ddlOrderNumberRelease3");
and
var mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY"
In mainString, the value "789" is coming from variable "a",
value "456" is coming from variable b and value "LLX" is coming from variable "c".
Variables "a" and "b" will always be Integers, whereas variable "c" will always be one the three values ie. "LLI,LLA,LLX".
Before value "789", there can be any number of words splitted by hypen "-". like ROAM-LCD-Synergy-SSI etc...
But after the value of variable "c" i.e "LLX" in mainString, there can be only one word for eg. "WARRANTY".
Now my issue is, I have to replace these three values of "a","b" and "c" ie. "789-456-LLX" with my newly entered values lets say 987-654-LLA, then my desired final string would be
old string: mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY"
desired string: mainString ="ROAM-LCD-Synergy-987-654-LLA WARRANTY"
Please suggest some wayout.
Thanks
var a = 123;
var b = 456;
var c = "ABC";
var mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY";
var updatedString = mainString .replace(/\d{3}-\d{3}-[A-Z]{3}\s([^\s]*)$/,a+"-"+b+"-"+c+" $1");
console.log(updatedString);
Something like this should work:
mainString.replace(/[\d]{3}\-[\d]{3}\-[\w]{3}\s([\w]+)$/, a + "-" + b + "-" + c + " $1");
Here's an option that uses string.split.
function replaceLastThreeDashedFields(original,a,b,c) {
var spaceSplit = original.split(' ');
var dashSplit = spaceSplit[0].split('-');
dashSplit[dashSplit.length - 3] = a;
dashSplit[dashSplit.length - 2] = b;
dashSplit[dashSplit.length - 1] = c;
var newDashed = dashSplit.join('-');
spaceSplit[0] = newDashed;
var newSpaced = spaceSplit.join(' ');
return newSpaced;
}
Just change the values before they are assigned? Place this before your variables are declared.
document.getElementById("txtOrderNumberRelease1").value = '987';
document.getElementById("txtOrderNumberRelease2").value = '654';
document.getElementById("txtOrderNumberRelease3").value = 'LLA';
The following code should update based on the values of a, b, and c...
var mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY";
var a = document.getElementById("txtOrderNumberRelease1").value;
var b = document.getElementById("txtOrderNumberRelease2").value;
var c = document.getElementById("ddlOrderNumberRelease3");
mainString = mainString.replace("789",a);
mainString = mainString.replace("456",b);
mainString = mainString.replace("LLX",c);

Defining numerous variables in a single step?

Is there a solution I can use that allows me to define more than one var with the same value in a single step at the start of my funcion?
function myFunction () {
var a,b = 0;
document.write(a) // undefined
document.write(b) // 0
}
Is there an improved way to write a,b = 0; ?
Something like this, however I don't like it.
var var1 = "hello",
var2 = "world",
var3 = 666;
Better
var var1 = "hello";
var var2 = "world";
var var3 = 666;
Please take a look at http://javascript.crockford.com/code.html
You can't do two things at once. You can't declare multiple local variables and assign a single value to all of them at the same time. You can do either of the following
var a = 1,
b = 1;
or
var a,b;
a = b = 1;
What you don't want to do is
var a = b = 1;
because you'll end up with b being a global, and that's no good.
var a = 0, b = 0;
var a = 0, b = a;
An alternate way
var a = b = 0;

Categories