Why am I able to write:
var x = 5;
console.log(x);
5
but when I write:
var n = a;
console.log(n);
Uncaught ReferenceError: a is not defined
Well, you don't have a variable a. Set it beforehand, like this:
var a = 10;
var n = a; // n is now also 10
If you want a character string, enclose the characters in quotes:
var n = "a"; // n is now a character string, not a number
When you write
var n = a;
then it means to set n's value the same value as variable a. But you haven't defined a yet, so you get an error message.
I think you mean the string "a", so use that:
var n = "a";
console.log(n);
Because a is not a defined variable as the error clearly states.
If you want to set n to the character 'a', then you need to put it in either single or double quotes.
n = 'a';
or
n = "a";
to print a in console,
var n = "a";
console.log(n);
print some other variable
var a = 10;
var n = a;
console.log(n);
Because you are trying to print out put of n which reference value of a which is undefined variable.
You are getting error instead of undefined because javascript does not allow you assignment of undeclared variable
Related
If I do
x = document.getElementsByClassName("something")[0]
I get the expected result.
But if I do
var x = document.getElementsByClassName("something")[0]
or
let x = document.getElementsByClassName("something")[0]
I get undefined.
Why is that?
Declaring a variable doesn't return anything (ie, undefined), however assigning a variable does return the value. For example:
let x, y
x = y = 7 // this sets both x & y to seven
The line above works because y = 7 returns the value of y which is then assigned to x. However you can't do anything with a variable declaration:
let x = 7
x = let y = 3 // syntax error
The point is that declaring a variable does not return a value, which is why you see undefined after it in console (also in node REPL), but assignments or other values that do return a value will display that value.
Note that you can do this:
var x = document.getElementsByClassName("something")[0]
x // this line will return the value of x
The document.getElementsByClassName will return the array named as HTMLCollection
Please have a look in this code,
var testElements = document.getElementsByClassName('test');
var testDivs = Array.prototype.filter.call(testElements, function(testElement){
return testElement.nodeName === 'DIV';
});
Also you can check the details here
I'm a total newbie, trying to survive my JS assignments. Any help is welcome.
When I run the following code, I get an error message saying "a is not defined." But a is defined.
function name(a, n) {
let a = b;
let b = x;
let c = n;
let b = c;
return c + a;
}
console.log(name(a, n));
a is only defined inside the function.
You are trying to read a (and n) outside the function and pass the resulting values to the function.
The problem is the way you call the function name instead of this console.log(name(a, n)); use this: console.log(name(5, 10));
As #Quentin said, when you pass the variables a and b to the function console log, it has to be defined outside of your function, but you can pass just the values and don't need to define the a and b variable outside the function.
So many problems here...
function name(a, n) {
let a = b; // a is already declared in function's declaration
let b = x; // x has never been declared
let c = n;
let b = c; // b is already declared in Line 3, additionally this line will make b = n
return n + a;
// this would finally become return b + b
// because Line 4: c = n
// and Line 5: b = c
// and Line 2: a = b
}
document.write(name(a,n)); // a and n should contain any value
In nodeJS terminal, I can enter this expression and have as a return 'true':
> var x = true; x;
true
How can I capture this return value in a variable, without changing the expression?
The following is not working:
> var y = (var x = true; x)
SyntaxError: Unexpected token var
In node REPL, you can just use _ :
> var x = true; x;
true
> var y = _
undefined
> y
true
You can't use a statement as an expression.
x = true is an expression, and x is also an expression. var x = true is not an expression, it's a statement.
To use the expression you would declare the variable x first. The value of an assignment expression is the value that was assigned, so you don't need to put x; after the assignment (which helps as that makes it a statement):
var x; var y = (x = true);
Javascript Code
var a = {};
a.test += 1; //NaN
++a.test; //NaN
Instead
var a = {};
a.test = 0;
++a.test; //1
a.test += 1; //2
I wonder if there could be anyway that can make first code sample work the same as second, i.e without an explicit assignment to 0. As in assigning default value for any property of an object to 0 instead undefined. I'm trying to do this in node.js. So, no problem of cross browser things and old ECMA Specs.
var i;
for(i = 0; i<10; i++) {
if(a.test) {
++a.test;
} else {
a.test = 0;
++a.test;
}
//a.test = a.test || 0; (1)
//++a.test;
}
If it is possible then the inner if/else or the assignment statement(1) in the above code can be eliminated.
Javascript by default defines all new variables as undefined ( if not explicitly defined ) , which is different from Number object, which you are trying to define. So you should use smth like :
for (i=0; i<10; i++) {
a.test = a.test || 0;
++a.test
}
There's no way to do this for any arbitrary undefined property.
For a known property name, there is a way, but DO NOT USE IT !! 1
Object.prototype.test = 0;
This will give every object an implicit .test property with that value in it, and the first time you attempt to modify it the result will be stored in your own object:
> Object.prototype.test = 0
> a = {}
> a.test++
> a.test
1
1 Adding stuff to Object.prototype will break stuff, including for (key in obj)
This is where prototypes come in useful in javascript:
function Demo() {
}
Demo.prototype.x = 0;
> a = new Demo();
> a.x += 1
> a.x
1
> b = new Demo()
> b.x
0
In the first code, you can't. Any number added to a non-number or NaN value will always result in NaN
var a = {};
a.test += 1; // undefined + 1 = NaN
++a.test; // ++(undefined) = NaN
as for the inner if
for(i = 0; i<10; i++) {
a.test = a.test || 0; //use existing value, or if undefined, 0
++a.test; //increment
}
I think this would do:
var a = {"test":0};
a.test += 1;
Using standard JS it's not possible to do what you're asking. Unless you prototype I guess? But I'm not experienced with Prototype.And I don't think prototyping works with Node.js
The reason for this is because js is not a typed language (i.e. we only use var to declare a variable, not int a or string b), so in order to use the ++ operator, the variable needs to be given a type through assignment.
hope that helps
How can I use the value of the variable a as a key to lookup a property? I want to be able to say: b["whatever"] and have this return 20:
var a = "whatever";
var b = {a : 20}; // Want this to assign b.whatever
alert(b["whatever"]); // so that this shows 20, not `undefined`
I am asking if it's possible during the creation of b, to have it contain "whatever":20 instead of a:20 where "whatever" is itself in a variable. Maybe an eval could be used?
This works in Firefox 39 and Chrome 44. Don't know about other browsers. Also it doesn't work in nodejs v0.12.7.
var a = "whatever";
var b = { [a]: 20 };
console.log(b["whatever"]); // shows 20
That is, to interpolate a variable, enclose it in brackets.
I'm not sure if this is a part of any standard. Originally, I saw such syntax here: https://hacks.mozilla.org/2015/07/es6-in-depth-classes/ where the author defined:
[functionThatReturnsPropertyName()] (args) { ... }
I'm also not sure if you should use that syntax. It's not widely known. Other members on your team might not understand the code.
var a = "whatever";
var b = {};
b[a] = 20;
alert(b["whatever"]); // shows 20
var a = "whatever";
var b = {a : 20};
b[a] = 37;
alert(b["whatever"]); // 37
'a' is a string with the value 'a'. a is a variable with the value 'whatever'.
Great question. I had a time trying to figure this out with underscore but the answer couldn't be more simple:
var a = "whatever";
var b = {a : 20};
var array = [a, b]
var answer = _.object([[array]])// {whatever: {a:20}}//NOTICE THE DOUBLE SET OF BRACKETS AROUND [[array]]
I hope this helps!
Try this:
var a = "whatever";
var c = "something";
var b = {whatever : 20, something: 37};
alert(b[a]); // Shows 20
alert(b[c]); // Shows 37
Here is the fiddle.
Or if I understand from the below comments correctly, try this:
var a = "whatever";
var b = {a : 20};
alert(b.a); // Shows 20
To show all options, I want mention the CoffeeScript way of doing this, which is:
var a = "whatever";
var b = (
obj = {},
obj["" + a] = 20,
obj
);
alert(b.whatever); // 20
Although I prefer:
var a = "whatever";
var b = {};
b[a] = 20;
alert(b.whatever); // 20