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)
Related
consider the following code:
let logged = 1;
let x = {logged} //{logged: 1}
x['logged']; // 1
x['logged']['index']; //undefined
x['logged']['index'] = 0;
x; // {logged: 1}
x['logged']['index']; //undefined
So, my questions are:
isn't
x[logged]['index'] doing something like 1['index']. Shouldn't
which give something like cannot index a numeric literal kind of
error?
x[logged]['index'] = 0;, this doesn't throw any error, as if the
element is stored somewhere, but, where is this value being stored?
As shown in line 6, the value of x is still {logged: 1}. And why does it not throw error?
and why is x[logged]['index'] is still undefined?
I tested this on a nodejs terminal, with node version 14.16.0
Not sure if my comments above actually fully illuminated the issue for you.
I have written a small program that may be helpfull to visualize what happens. Note I'm doing a method lookup on a primitive value rather than a regular property lookup - but this is all just the same and allows to illustrate what happens better.
function captureThis() {
return this
}
(function setUpObjectPrototype() {
if (Object.prototype.captureThis !== undefined) throw new Error("Couldn't set up Object prototype properly.")
Object.prototype.captureThis = captureThis
process.nextTick(() => delete Object.prototype.captureThis)
})()
var number = 1
var thisObject = number.captureThis()
console.log("Is thisObject an object? " + (typeof thisObject == "object"))
console.log("Is number still just a number? " + (typeof number == "number"))
console.log("Is thisObject an instance of Number? " + (thisObject instanceof Number))
// Output
// Is thisObject an object? true
// Is number still just a number? true
// Is thisObject an instance of Number? true
Note that at no point is the number variable actually coerced to an object - a temporary object is created that wraps the value contained in the number variable. This object is never actually assigned to a variable - unless it is captured like it is in this little program.
Hopefully that helps.
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();
I am creating variable and using it in for statement
for(var i = 0; i < 10; i++) {
console.log(i)
}
It is working properly and resulting from 1-10;
When I write same in the if condition
if(var value = 10) {
console.log("Evaluate");
}
It is resulting Unexpected token var.
When I declare a variable (var a = 10), resulting the same error. Is there any issue.
An if statement only accepts an expression inside (something that evaluates to a value). Something like var value = ... is a statement - rather than evaluating to a value, it does something (namely, creates a local variable bound to the name value). So, since var value = ... cannot be evaluated as an expression, an error is thrown.
Some things can be evaluated both as statements and expressions (such as functions), but variable creation is not one of them.
Note that variable assignment is possible inside an if, because assignment does evaluate to the value assigned:
var value;
if(value = 10) {
console.log('value now has the value 10');
}
But that's really confusing to read - a reader of the code will likely immediately worry whether that's a typo or not. Better to assign variables outside of an if condition, whenever possible.
Only use var when you want to create a new variable. If you simply want to check a variable (for example, check whether the variable named value is 10), then just print that variable name, and use a comparison operator (===, not =):
if (value === 10) {
// do stuff
}
When you write
var value = 10
actually evaluated as the following statements:
var value;
value = 10
You can not write statement in if as condition, as the condition must be only expression:
An expression that is considered to be either truthy or falsy.
Declare and initialize the variable outside. Use proper operators.
var value = 10;
if(value == 10) {
console.log("Evaluate");
}
else {
console.log("Hello");
}
You need to declare the variable like this:
var value = 10;
if(value == 10) {
console.log("Evaluate");
}
This question already has answers here:
Boolean variable returns as string from javascript function [duplicate]
(2 answers)
Closed 6 years ago.
I don't know if this is a bug, but it feels kind of strange. Can you store a boolean returned by a function in a variable using javascript? Whenever I try to store a boolean value in a variable which is returned by a function, it gets changed to string.
I have the following function which converts a string to a boolean
function str2bool(strvalue){
console.log("Value is - " + strvalue);
console.log("Type is - " + typeof strvalue);
return (strvalue && typeof strvalue == 'string') ? (strvalue.toLowerCase() == 'true') : (strvalue == true);
}
I've found this function somewhere here on StackOverflow, but I do not remember it's author, so if you are reading this, sorry about me not giving proper credits:)
I have another javascript line, which looks as follows:
target.prop('disabled',str2bool(booleanInStringFormat));
console.log("Typeof str2bool return is - " + typeof str2bool(booleanInStringFormat));
If I use it this way, everyting works fine, the str2bool function returns the following lines to the console:
Value is - false
Type is - string
And the line after the main function returns:
Typeof of str2bool function is - boolean
But if I try to store the return value of str2bool in a variable, and use it afterwards, the prop function won't work, because apparently the variable that I use to store the return value of str2bool becomes a string. If I run this code I get the following results:
status = str2bool(booleanInStringFormat);
console.log("Typeof status is - " + typeof status);
target.prop('disabled',status);
The results are the following:
Value is - false
Type is - string
Typeof status is - string
End result is that target remains disabled
So, why is the typeof the variable in which I store the return of the function is changed back to string?
Because you use global variable status, which appeared to be a property of the global object window, this property could only be string.
The window.status.
You could just change to an other variable name, but much better, avoid using global variable.
(function(){
var status = str2bool('false');
console.log(typeof status);
}());
Tried the below snippet, it seems we can return a boolean and save it
function booleanReturnCheck(){
return false;
}
var isBool = booleanReturnCheck();
console.log(isBool);
console.log(typeof (isBool));
JSFIDDLE
The accepted answer on this link discusses boolean variables. Maybe something there might help: Declaring a boolean in JavaScript using just var
The section to pay attention to is
var IsLoggedIn1 = "true"; //string
var IsLoggedIn2 = 1; //integer
var IsLoggedIn3 = true; //bool
It seems that your values are strings because they are being set as strings.
you can parse bool using !!
var bool = !!'true';
You can parse a Boolean Variable using :
var myVar = Boolean("false");
var myVar = !!"false";
Note that any string which isn't the empty string or "false" will evaluate to "true".
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 })