Concatenating a declared but not defined variable - javascript

Out of curiosity I did this simple concatenation:
let a;
a+="hello"
console.log(a)
It returns "undefinedhello"
I get that a was basically the string "undefined", or is it converted to a string when concatenating? Is there something to learn here?

let a="";
a+="hello"
console.log(a)
since you are creating a variable here so the default value becomes undefined . You need to assign a value over there.
check here

Related

Javascript, what happens when we assign value to read-only data property such as string length?

Suppose we have a string, length is read-only data property of string. What happen if we unintentionally assign value to length property of string? Why javaScript return those value as a result?
for example if we run this part of code:
var str="test";
console.log(str.length)
console.log(str.length=3)
output should be like this:
4
3
the third line of code returns 3, My question is why assignment in javaScript returns right side of operand not left side of it?
The assignment operator always returns the right-hand value. Hence, passing the expression inside the console.log function returns the right-hand value, in your case 3.
Assigning any value to the length property of a string has no effect.
let myString = "Hello,World!";
myString.length = 4;
console.log(myString);
// expected output: "Hello,World!"
console.log(myString.length);
// expected output: 12

Javascript variable is undefined outside if condition

I have defined a javascript variable but it returns undefined.
variable = "";
if(somecondition){
variable=myString.length;
}
alert(variable);
here variable returns undefined. If I keep the alert inside the if condition, I am able to get the value but its not working if I keep the alert outside the if condition.
Your myString does not have an property called length and hence you are getting undefined.
Usually, String, array has length property while objects don't have it.
Either you are invoking a wrong property or invoking it on a wrong data type or you have to define one yourself :P
Using var will do it:
var variable;
You need to declare and define your variable.
var variable = "";
if(somecondition) {
variable = myString.length;
}
alert(variable);
Are you missing the initialization of mystring?
Look at the following
var variable = '';
if (true) {
variable = 'Yes'
}
alert(variable);
This will show alert as Yes.
So in your case myString.length; is probably undefined
If variable isn't undefined in the function, it's because it is still equal to the initial value, "" (Empty String).
What I bet is happening, is myString is actually a number and not a string. Try the following and see if you are still having a problem:
variable = "";
if(somecondition){
variable=myString.toString().length;
}
alert(variable);

What does ||{} mean in javascript?

I'm working on a project using Easel JS. Opened up the Easel file and the very first line of code confused me:
this.createjs = this.createjs||{};
I know that createjs is invoked when you're setting up your canvas or, for example, creating a bitmap to add to the canvas. But I don't understand the syntax of this line - assign this.createjs or (what I guess is) a blank object to this.createjs?
this.createjs = this.createjs||{};
If this.createjs is not available/ any falsy value then you are assigning {} empty object to this.createjs.
It's more like,
var a,
b;
b = a || 5;
Since a is not having any value currently, 5 will be assigned to b.
Correct. This ensures that if this.createjs doesn't already exist, an empty object is assigned to it. The || is an or operator - if this.createjs on the left-hand-side evaluates to falsy, it will assign the right-hand-side instead.
this.createjs = this.createjs||{};
If this.createjs is falsy, this.createjs will be a new empty object
You could have replace it by
if (!this.createjs){
this.createjs = {};
}
|| means or.
In that context means this.createjs equals if exists/not null/defined this.createjs other way {}

why does a variable in javascript seem to hold the value "undefined" even when it was defined

if I run the following javascript code, the browser alerts "undefinedabc".
var x;
x += "abc";
alert(x);
To me it looked like I did define the variable x, so why does it seem to be undefined?
undefined is the default value of any variable with no value assigned. So, var x; means that a = undefined. When you add "abc" to it, you're actually doing undefined + "abc". Finally, undefined is stringifiend to "undefined" and then concatenated to "abc" and turns to "undefinedabc".
In order to concat initialize the var x, you should assign an empty string to it (remember that JavaScript dinamically-typed):
var x = '';
x += "abc";
alert(x); // "abc"
This MDN article describes this behaviour.
var x = "";
x += "abc";
alert(x);
Try this. You are trying to add 'abc' and undefined which will result to undefinedabc.
First examine the behaviour of a Variable Statement, Specifically:
"Variables are initialised to undefined when created."
Then examine the behaviour of the addition operator (compound assignment applies the behaviour of the operator corresponding to what precedes =).
Specifically, point 7:
"If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)"
So, since "abc" is a string, x is to be translated to a String, according to ToString. x, as we know from above, is undefined.
Finally, examine the behaviour of the abstract operation ToString, specifically, that an undefined argument results in the string "undefined".

For...In with custom object in javascript

function doIt()
{
var person={firstname:"John", lastname:"Smith", age:"25"};
var x;
var txt="";
for (x in person)
{
txt=txt+person[x] +"<br>";
}
document.getElementById("showtext").innerHTML=txt;
}
My question is: Why when I replace
txt=txt+person[x]+"<br>";
with:
txt=txt+person.x+"<br>";
the value of person.x is returned as undefined?
In the first iteration of the loop, x should be 'firstname'. So person.x should be equal to person.firstname, and thus return the value John. I would love to understand why it returns 'undefined' instead.
In the first case you're using 'bracket notation', where the value of the variable x is used to determine the property name.
In the second case you're using 'dot notation', where the property looked for is literally called x.
The Answer is:
Since x ist not the property name and the object doesnt have a property with the name/key x.
person.x
is undefined.
This would be equivalent to
person["x"] (the subtle difference lies in the double quotes)
what is also undefined.
For it to work with the dot-notation, you would have to write :
eval("person." + x); // but this is evil
// Tested on win7 with chrome 45+
so expression eval("person." + x) would expand in the first run to eval("person.firstname" ) which returns "John"
...
What I don't recommend, because eval can introduce may security issues.
Update 1
Disclaimer:
With this answer i only answered the initial question, and tried to explain the problem. With "// but this is evil " i am suggesting not to use this approche.
When you write person[x], it means "look up the value of x, and then find that element in person". When you write person.x it means "look up the value of x inside of person".
person doesn't have an x element, so you're getting undefined. You really do just want person[x].
x will be a string. eg "person" so you have to use [] brackets
You can't use dot notation with a variable key. It will look up the property "x" which is undefined. person[x] is the right way.
Javascript will allow you to access an object's property using a variable if you use the square brackets syntax. Thus, person[x] will do what you are trying to do as long as x contains a string representing the property name. The syntax construction person.x is equivalent to person["x"].

Categories