Converting Ternary Operator to if / else statements - javascript

I found a fix for my application, but I copied and pasted the code, which doesn't match with the rest of the code, I want to turn these ternary operators into if/else statements.
const name = persona ? persona.player_name : steamID.getSteamID64();
I tried to do:
const name = persona;
if (name = persona) {
persona.player_name;
} else {
steamID.getSteamID64;
}
But it didn't work, any help will be appreciate it thanks!

Just do:
let name = '';
if (persona) {
name = persona.player_name;
} else {
name = steamID.getSteamID64();
}

The mistake is, that the ternary operator doesn't check for equality in this example but for undefined, that means that you example will translate to the following:
let name = undefined;
if (persona !== undefined) {
name = persona.player_name;
} else {
name = steamID.getSteamID64();
}
It would be written in human language like this: If persona is defined, assign property player_name to the variable named name. If persona is not defined, assign the result of steamID.getSteamID64() to name.
This is possible because just checking if(foo) is a shorthand for if (foo !== undefined). And the ternary operator is an inline if-condition, so if(foo) can be translated to foo ? then : else.

You could take a var statement for declaring the value and assign later.
const needs a value and be careful by taking name as variable, becaus this is a short form of the window's name window.name.
var name;
if (persona) name = persona.player_name;
else name = steamID.getSteamID64();

Related

What does this JS object declaration syntax mean?

I am working through a node.js beginners tutorial and came across this piece of code:
const respondEcho = (req, res) => {
const { input = '' } = querystring.parse(
req.url.split('?').slice(1).join('')
)
}
The syntax of this line const { input = '' } = querystring.parse() is a little confusing to me.
It seems like a declaration of a constant object set equal to a method which returns key value pairs. What I don't understand however is the assignment inside the curly braces - if this was an object declaration then it would be like this rather:
const {input: ''}
The input='' seems like it would be a default value on the object. Could someone explain the meaning of this syntax?
const { foo = '' } = bar
means that you are destructuring the foo property from bar and you are assigning a default value to it incase it is falsy.
It is practically the same as doing:
let foo = bar.foo;
if (foo === undefined) {
foo = '';
}
It is a destructuring assignment with a default value in the case that the value unpacked from the object is undefined.

Typescript - correct way to set a string based on string comparison

I want to check if a string is equal to another string and set a new string based on this condition.
private myFunction( myString: string ) {
if (myString != "someString") {
let path:string = "/*/POST/A";
}
else{
let path:string = "/*/POST/note/B";
}
(do something with path here)
Not sure the above is correct actually finding it pretty hard to find a decent example of this and completely new to typescript/ javascript.
let variables are block-scoped - they only exist within the block you declare them. So declaring let path inside of the if block or the else block won't allow you to use it later outside of the if/else.
All you need to do is declare it in the scope you want to use it and assign it in the if/else.
let path: string;
if (myString != "someString") {
path = "/*/POST/A";
} else {
path = "/*/POST/note/B";
}
//use path here
Consider using a ternary expression so you’re not declaring the variable inside the conditional:
const path:string = myString === “someString” ? “option a” : “option b”

Call variable using another variable whos string content is the other variables' name [duplicate]

This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 4 years ago.
So I have a bunch of variables such as:
var HelloBob = '123';
var HelloSally = 'abc';
var HelloTim = 'pie';
I need to reference these variables by constructing their names and so having their names in another variable.
So in which this would output '123' instead of 'Hellobob'
var name = 'bob';
console.log('Hello'+bob)
I've done this previously using Window[] (I think), but I attempt using it and it doesn't work. Such as...
var HelloBob = '123';
var name = 'bob';
if(typeof window['Hello'+name] !== undefined){
console.log('Variable Exists')
}
Which should only be true if a variable with the name 'Hellobob' exists, but it is always true when I run it.
I'll need to be able to reference the variables fully, so able to do .toLowerCase()
There are a couple issues with your snippet:
typeof returns a string - you’re comparing the result to undefined (a property of the global scope) instead of 'undefined' (the type string)
You’re forming the variable name Hellobob which doesn’t exist. Setting name to Bob (instead of bob) should fix this.
var HelloBob = '123';
var name = 'Bob';
if (typeof window['Hello' + name] !== 'undefined') {
console.log('Variable exists:', window['Hello' + name]);
}
However...
As mentioned in the comments, this is usually not a good pattern to follow. Instead, consider creating an object to contain these variables:
var hello = {
Bob: '123',
Sally: 'abc',
Tim: 'pie',
};
var name = 'Bob';
if (hello.hasOwnProperty(name)) {
console.log('Variable exists:', hello[name]);
}
The best way I know is to use eval:
var HelloBob = '123';
var HelloSally = 'abc';
var HelloTim = 'pie';
function getGreeting(name) {
var greetingVar = 'Hello'+name;
var greeting = null;
try {
greeting = eval(greetingVar);
} catch (err) {
console.error("Tried to get greeting for a person that doesn't exist.");
}
return greeting;
}
console.log(getGreeting('Bob'));
console.log(getGreeting('Scott'));
See also: Use dynamic variable names in JavaScript
Edit: I agree with other comments though, this seems like a terrible idea that is probably best implemented another way.

Javascript passing variable in function

I am new to javascript. I am creating a text adventure. I am trying to write a function to take a given parameter, and use the .toLowerCase and return it as the same variable. I think I have the general idea to do it, but I just can not get it to work. Thanks!
function lowercase(a){
return a.toLowerCase();
}
var alive = 1;
while(alive == 1){
var name = prompt("What is your name?");
lowercase(name);
document.write("Hello " + name + "!\n");
break;
}
You need to assign the result of the function:
name = lowercase(name);
Are you new to programming in general? Because Javascript is similar to most other language in this regard.
name = lowercase(name);
Since you are returning the value in your function, you must reinitialize the value of the variable. Javascript as far as I know is not a "pass by reference" language. It has always been a "pass by value". Read more about it here.
What's the difference between passing by reference vs. passing by value?
use name = lowercase(name);
the function returns a result, but you have to assign this result to a variable in order to use it after, or you can simply say
document.write('Hello' + lowercase(name) + 'something');
The value of the name variable isn't being changed at the moment, you need to assign it to the result of the function.
function lowercase(a){
return a.toLowerCase();
}
var alive = 1;
while(alive == 1){
var name = prompt("What is your name?");
name = lowercase(name);
document.write("Hello " + name + "!\n");
break;
}
name = lowercase(name);
Note, you should almost always use "===" instead of "==". "===" tests whether something's value and data type (number, string, boolean, object, etc.) matches another, whereas "==" only tests whether the values match (after performing a type conversion). For example:
if ("42" == 42) { // true (string 42 equals number 42)
if ("42" === 42) { // false (string does not equal number, what you want)

Determine original name of variable after its passed to a function

I've got a feeling this might not be possible, but I would like to determine the original variable name of a variable which has been passed to a function in javascript. I don't know how to explain it any better than that, so see if this example makes sense.
function getVariableName(unknownVariable){
return unknownVariable.originalName;
}
getVariableName(foo); //returns string "foo";
getVariableName(bar); //returns string "bar";
This is for a jquery plugin i'm working on, and i would like to be able to display the name of the variable which is passed to a "debug" function.
You're right, this is very much impossible in any sane way, since only the value gets passed into the function.
This is now somehow possible thanks to ES6:
function getVariableName(unknownVariableInAHash){
return Object.keys(unknownVariableInAHash)[0]
}
const foo = 42
const bar = 'baz'
console.log(getVariableName({foo})) //returns string "foo"
console.log(getVariableName({bar})) //returns string "bar"
The only (small) catch is that you have to wrap your unknown variable between {}, which is no big deal.
As you want debugging (show name of var and value of var),
I've been looking for it too, and just want to share my finding.
It is not by retrieving the name of the var from the var but the other way around : retrieve the value of the var from the name (as string) of the var.
It is possible to do it without eval, and with very simple code, at the condition you pass your var into the function with quotes around it, and you declare the variable globally :
foo = 'bar';
debug('foo');
function debug(Variable) {
var Value = this[Variable]; // in that occurrence, it is equivalent to
// this['foo'] which is the syntax to call the global variable foo
console.log(Variable + " is " + Value); // print "foo is bar"
}
Well, all the global variables are properties of global object (this or window), aren't they?
So when I wanted to find out the name of my variables, I made following function:
var getName = function(variable) {
for (var prop in window) {
if (variable === window[prop]) {
return prop;
}
}
}
var helloWorld = "Hello World!";
console.log(getName(helloWorld)); // "helloWorld"
Sometimes doesn't work, for example, if 2 strings are created without new operator and have the same value.
Global w/string method
Here is a technique that you can use to keep the name and the value of the variable.
// Set up a global variable called g
var g = {};
// All other variables should be defined as properties of this global object
g.foo = 'hello';
g.bar = 'world';
// Setup function
function doStuff(str) {
if (str in g) {
var name = str;
var value = g[str];
// Do stuff with the variable name and the variable value here
// For this example, simply print to console
console.log(name, value);
} else {
console.error('Oh snap! That variable does not exist!');
}
}
// Call the function
doStuff('foo'); // log: foo hello
doStuff('bar'); // log: bar world
doStuff('fakeVariable'); // error: Oh snap! That variable does not exist!
This is effectively creating a dictionary that maps variable names to their value. This probably won't work for your existing code without refactoring every variable. But using this style, you can achieve a solution for this type of problem.
ES6 object method
In ES6/ES2015, you are able to initialize an object with name and value which can almost achieve what you are trying to do.
function getVariableName(unknownVariable) {
return Object.keys(unknownVariable)[0];
}
var foo = 'hello';
var output = getVariableName({ foo }); // Note the curly brackets
console.log(output);
This works because you created a new object with key foo and value the same as the variable foo, in this case hello. Then our helper method gets the first key as a string.
Credit goes to this tweet.
Converting a set of unique variable into one JSON object for which I wrote this function
function makeJSON(){ //Pass the variable names as string parameters [not by reference]
ret={};
for(i=0; i<arguments.length; i++){
eval("ret."+arguments[i]+"="+arguments[i]);
}
return ret;
}
Example:
a=b=c=3;
console.log(makeJSON('a','b','c'));
Perhaps this is the reason for this query
I think you can use
getVariableName({foo});
Use a 2D reference array with .filter()
Note: I now feel that #Offermo's answer above is the best one to use. Leaving up my answer for reference, though I mostly wouldn't recommend using it.
Here is what I came up with independently, which requires explicit declaration of variable names and only works with unique values. (But will work if those two conditions are met.)
// Initialize some variables
let var1 = "stick"
let var2 = "goo"
let var3 = "hello"
let var4 = "asdf"
// Create a 2D array of variable names
const varNames = [
[var1, "var1"],
[var2, "var2"],
[var3, "var3"]
]
// Return either name of variable or `undefined` if no match
const getName = v => varNames.filter(name => name[0] === v).length
? varNames.filter(name => name[0] === v)[0][1]
: undefined
// Use `getName` with OP's original function
function getVariableName(unknownVariable){
return getName(unknownVariable)
}
This is my take for logging the name of an input and its value at the same time:
function logVariableAndName(unknownVariable) {
const variableName = Object.keys(unknownVariable)[0];
const value = unknownVariable[variableName];
console.log(variableName);
console.log(value);
}
Then you can use it like logVariableAndName({ someVariable })

Categories