Way to differentiate between declared variable vs undeclared-2 [duplicate] - javascript

This question already has answers here:
Way to differentiate between declared variable vs undeclared [closed]
(11 answers)
Closed 9 years ago.
Possible Duplicate
Way to differentiate between declared variable vs undeclared
I want to explain clearly my problem here.
I have this condition.
if(//condition1)
var x1 = 1;
else if(//condition2)
var x2 = 2;
else if(//condition3)
var x3 = 3;
This way I can have only one variable declared.
Now I want to print the variable which is declared.
How can I do that?
This is a more realistic example of what I am trying to do:
var d_pattern=/d{1}/;
var dd_pattern=/d{2}/;
var ddd_pattern=/d{3}/;
var dddd_pattern=/d{4}/;
if(dddd_pattern.test(formatString))
var dddd=this.getDayName();
else if(ddd_pattern.test(formatString))
var ddd=this.getDayNameAbbr();
else if(dd_pattern.test(formatString))
var dd=this.getDateFormatted();
else if(d_pattern.test(formatString))
var d=this.getDate();

Use another variable to hold the information:
var which;
if (condition1) {
var x1 = 1;
which = 'x1';
} else if (condition2) {
var x2 = 2;
which = 'x2';
} else if (condition3) {
var x3 = 3;
which = 'x3';
}
console.log('Declared variable is: ' + which);
But remember, as explained in several answers in your earlier question, hoisting causes all the variables to be declared.
If you want to be able to use which to show the value of the variable, it would be better to use an object, with the name as the property:
var obj = {}, which;
var which;
if (condition1) {
obj.x1 = 1;
which = 'x1';
} else if (condition2) {
obj.x2 = 2;
which = 'x2';
} else if (condition3) {
obj.x3 = 3;
which = 'x3';
}
console.log('Declared variable is: ' + which + ' value is: ' + obj[which]);

Why not use an Object?
var obj = {};
if(//conditon){
obj.x1 = 1;
}
else if(//condition){
obj.x2 = 2;
}
console.log(Object.keys(obj))
Note: this is the same logic that was given on the last v1 if this question

You can use typeof
if(typeof x1 !== "undefined"){
// ...
}
// other checks

You can iterate the context object by name. In global context its window, so you can iterate window and check
if(window[var_name] === undefined)
Regarding your question, there`s one more way to cehck if variable was defined for any context - memoize all variables, then on every change to the context write new list of variables were defined. But it will require to keep list of variables defined for the context you need to track

Related

How can I find out if an ES6 value is var / const / let after it is declared? [duplicate]

This question already has answers here:
How to check that ES6 "variable" is constant?
(4 answers)
Closed 3 years ago.
I know I can find out if a value is var const or let by looking at where it is declared. However I am wondering - mainly for debugging, developing JS compilers, and academic interest - if it is possible to find out the immutability / scope of a variable (var / const / let-ness) after it has been created.
ie
doThing(something)
Would return
let
Or equivalent. Like we can determine types with typeof or something.constructor.name for constructors.
You can distinguish let and const from var with direct eval in the same function as the variable:
let a;
try {
eval('var a');
// it was undeclared or declared using var
} catch (error) {
// it was let/const
}
As #JonasWilms had written earlier, you can distinguish let from const by attempting assignment:
{
let x = 5;
const original = x;
let isConst = false;
try {
x = 'anything';
x = original;
} catch (err) {
isConst = true;
}
console.log(isConst ? 'const x' : 'let x');
}
{
const x = 5;
const original = x;
let isConst = false;
try {
x = 'anything';
x = original;
} catch (err) {
isConst = true;
}
console.log(isConst ? 'const x' : 'let x');
}
let and var are only about the scope, so it's not possible. Because JavaScript does not pass by reference, if you were to pass a variable to a function you would lose the " constness" and also the scope - on that function the variable would just be a locally scoped one. So my thoughts are: it's not possible.
You can't directly access the environment record chain in any way, and therefore you can't tell were a variable was declared. The with statement might enable you to narrow down the scope were a variable was declared as it allows you to add a Proxy as an environment record, but that only gives some insight and it is generally a very dangerous thing to do.
I used to do this but its a little hacky...
I create a variable and try to change it and if it throws an error then it's a const variable,.
I create a variable and try to change it on the {} braces, if the value is different then it was initially created then it's a var, if not then it's a let variable.

How to change a variable that was called in parameters JavaScript [duplicate]

This question already has answers here:
Does JavaScript pass by reference? [duplicate]
(13 answers)
Closed 6 years ago.
Im working on a project, and in an attempt to shorten the amount of code I wrote a function to call all of them at once. It looks something like this function Function(peram1) {peram1 = peram1 += 5}; And I call it like so Function(someVariable) My issue is that I need to change the variable someVariable from inside the function, even though the value of peram1 is simply just the value of someVariable, but cant directly change it. I call multiple of these functions, so I cant simply just call the actual variable name from within.
var someVariable = 5;
var someSeperateVariable = 8;
function Function(peram1) {
peram1 = peram1 += 5;
};
Function(someVariable);
Function(someSeperateVariable);
console.log(someVariable, someSeperateVariable);
You can use an object to store variables, pass property name and object to function
var obj = {someVariable:5, someSeparateVariable:8};
function fn(prop, obj) {
obj[prop] += 5;
};
fn("someVariable", obj);
fn("someSeparateVariable", obj);
console.log(obj.someVariable, obj.someSeparateVariable);
Consider returning a value from Function
var peram1 = Function(Peram1);
Another option in case peram1 is not an object - is to wrap peram1 with an object:
var objContainPeram1 = { peram1: peram1 }
Function (objContainPeram1) {
objContainPeram1.peram1 = objContainPeram1.peram1 + 5
}
Another solution would be to wrap your code in a function to create a closure:
function closure() {
var someVariable = 5;
var someSeperateVariable = 8;
function foo() {
someVariable += 5;
};
console.log(someVariable)
foo()
console.log(someVariable)
}
closure()

Difference between let and var in JavaScript [duplicate]

This question already has answers here:
What is the difference between "let" and "var"?
(39 answers)
Closed 6 years ago.
I was going through the javascript style guide by Airbnb (https://github.com/airbnb/javascript).
In section 2.2 it is explained that
let is block-scoped rather than function-scoped like var.
// bad
var count = 1;
if (true) {
count += 1;
}
// good, use the let.
let count = 1;
if (true) {
count += 1;
}
I didn't get why the first one is bad practise and second is bad and if both let and var are block scoped then what difference does it make, if I use either of them?
Also what is the difference between function scoped and block scoped?
When something is block scoped it means that you can control the lifetime better and more intutive ways
for example
function a() {
if (true) {
var a = 7;
let b = 42;
}
}
The var a is pulled out in the scope of the function, rather than stying isolated in the block for the if, so like this;
function a() {
var a; // The JS compiler pulls the var out to this level
if (true) {
a = 7;
let b = 42; // but keeps the let in this block.
}
}
.. and that is counter intuitive and sometimes lead to problems -- the let does not have that problem.

How to check dynamic global variables without using `window` in JavaScript? [duplicate]

This question already has answers here:
Why isn't my JavaScript working in JSFiddle?
(7 answers)
Closed 7 years ago.
I need to pass a list of variable names in JavaScript and check if those variables exist. I tried the following but it doesn't seem to be doing the trick (JSFiddle here):
var test1 = 'test1';
var test2 = 'test2';
function checkVariable(variableNameList) {
for (var iterator = 0; iterator < variableNameList.length; iterator++) {
var variableName = variableNameList[iterator];
if (typeof window[variableName] === 'undefined') {
alert('Variable ' + variableName + ' is not defined');
} else {
alert('Variable ' + variableName + ' is defined');
}
}
}
checkVariable(['test1', 'test2', 'test3']);
I'm trying to get the resulting alerts:
Variable test1 is defined.
Variable test2 is defined.
Variable test3 is not defined.
It seems easy to fix using the trick below but is there any other way to achieve this? Is declaring global variables under window the only way to track them?`
window.test1 = 'test1';
window.test2 = 'test2';
Are there better ways to do this or is this the right approach?
Vanilla JS only answers please.
It does not work because the variables are not in global scope, they are in scope of the window.onload function scope.
Your code is actually running like this:
window.addEventListener("load", function () {
var test1 = 'test1'; /* these are not global because of */
var test2 = 'test2'; /* running inside of window.onload */
function checkVariable(variableNameList) {
}
checkVariable(['test1', 'test2', 'test3']);
});
Change your code to run either in the head or at the end of the body. I forked your code to run in the head: https://jsfiddle.net/phrhxyzL/1/ and you get the results you expect.

Correct way of initializing vars on this cases?

I am aware that most common practice would be to put var a,b; on the top, but I want to extract every possible character (after running on JS Uglify), and it seems they don't delete unnecessary var initializing
I want to know if any of the following will cause problems and which is recommended
Case 1:
if(condition){
var a=-1;
var b="++";
}else{
var a=1;
var b="--";
}
Case 2:
if(condition){
var a=-1;
var b="++";
}else{
a=1;
b="--";
}
Case 3:
if(condition){
a=-1;
b="++";
}else{
var a=1;
var b="--";
}
This is the way it should be:
var a,b;
if(condition)
{
a = -1;
b = "++";
}
else
{
a = 1;
b = "--"
}
Variables should always be declared at the top of the function with the var keyword. Variable scope is at the function level, and not using var makes it a global variable. Declaring it at the top always ensures that you know the scope is for the entire function (and it is anyway), so when another programmer looks at it and doesn't know that scope is at the function level, he/she wont get confused and think the scope is only in the conditional.
It doesn't matter, since JavaScript has function scope, not lexical scope.
You can think of it as every var ...; statement being shunted up to the top of the function they're in. (That's what I do, at least.)
I'd write the code as
var a, b;
if(condition) {
a = -1;
b = "++";
} else {
a = 1;
b = "--";
}

Categories

Resources