Is there a way in javascript to both assign and check for undefined (or null or whatever) in one line like this:
if (let myVar = DoSomethingAndReturnValue()) {
// DoSomethingAndReturnValue() returned a falsy value and so myVar is falsy
return
}
// myVar is now assigned with some value we can do something with it.
This creates a global variable but does it.
if (!(myVar = DoSomethingAndReturnValue())) {
console.log(2);
}
Related
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");
}
I want to assign a value to a variable when a condition is verified like this
if (k<12){
var Case=4;
}
The problem when i call this variable to be printed in the body of the page i get undefined
document.write(Case);
Basically your var statement gets hoisted and assigned with undefined.
Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.
Order of execution:
var Case; // hoisted, value: undefined
if (k < 12) {
Case = 4;
}
You are getting undefined because you have not actually defined it. You are defining it when the condition is true. You should write the code like this.
var Case = null;
var k = 0;
if(k > 14) {
Case = 3;
}
document.write(Case);
I hope it was helpful.
var Case = 0;
if(k<12){
Case = 4;
}
document.write(Case);
You need to define it first so if k<12 == False it wont be undefined.
Here is one of the similar example
var global=0;
function somefunction()
{
global++;
}
var temp=global;
function somefunctiontwo()
{
var x=temp;
}
here I am getting x=0
I want x=1
how can I assign newly assigned value of global variable to x
Use an object as global variable; that will be assigned by reference instead of 'by value' as for the simple (number) type:
var global = { value: 0 };
var temp = global;
in function:
global.value++;
now is:
temp.value == 1
temp and global refer to two different variables. Assigning to global will not change the value in temp.
Simply change var x=temp to var x=global. It's not clear why you need an intermediate variable.
var global=0;
var temp;
function somefunction(){
global++;
}
function somefunctiontwo() {
var x=temp;
console.log(x);
}
somefunction();
temp=global;
somefunctiontwo();
This will give what you expect. Pay attention on how/where you call the functions.
Your structure seems a little off, not sure if this is for a reason we can't see... Will presume it is. Can have a function that resyncs the temp value to global.
function syncGlob(){
return temp = global;
}
Returns temp as well so you can call it when creating x.
var x = syncGlob();
You're setting the value of temp to global PRIOR to the on ready firing - at this point global is 0. If you increment global at on ready, temp already has a value of 0.
When you click somefunction2 and assign x the value of temp, temp has a value of 0, because at the time of temp initiation, global had a value of 0 NOT 1
I have a function with 2 parameters, it should work whether a the 2nd parameter is assigned or not in the bracket. Basically, if it's assigned then do something if not do something else or just don't bother about it.
vf.showHide = function (trigger, target) {
var $trigger = $(trigger),
trigParent = $trigger.parent(),
trigDataView = $trigger.data('view'),
numShown = $trigger.data('showalways'),
basketSubtotalElem = $('.subtotal .monthlyCost span.price, .subtotal .oneOffCost span.price, .subtotal label h3, .vat *');
target = target || null; // This is the 2nd parameter but I don't know if this right...
trigParent.delegate(trigger, 'click', function (e) {
var elem = $(this);
target = $(elem.attr('href'));
e.preventDefault();
if (trigDataView === 'showhide') {
if($('.filterBlock')){
if (target.is(':visible')) {
target.hide();
elem.find('span').removeClass('minus').addClass('plus');
} else {
target.show();
elem.find('span').removeClass('plus').addClass('minus');
}
}
}
});
}
So if the function is called like this: vf.showHide('a', 'div') it works and if it's called with 1 parameter like this: vf.showHide('a') it's should still works and error is thrown.
Many thanks
When you invoke a function, if you pass fewer parameters than expected, the parameters you omit are given the undefined value. So in your case:
vf.showHide = function(trigger, target) {
if (target === undefined) {
//target parameter is not passed any value or passed undefined value
//add code to process here, e.g. assign target a default value
}
}
target = target || null: if target is evaluated to false, it's assigned to null. Take notice that empty string, zero number (0), NaN, undefined, null, false are evaluated to false. So please be careful to write code like that.
target = target || null will work.
What you are doing here is declare an local variable within the function's scope.
Within each function, a local variable corresponding to the the name of the parameters are created to hold the passed in value.
If the parameters are not passed in, it will remain as 'undefined' local variable.
function (a, b) {
//a, b are declared.
}
what target = target || null does is just assign a value to an declared local variable it use the || expression:
The value of of || expression is determined by the first operands return true.
true || 2 will be valued as true
false || 2 will be valued as 2
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 })