I have a simple array loop, runs perfect in jsFiddle showing all items, see https://jsfiddle.net/8odoros/b27ocs4d/1/
What's strange is that putting the same script here as a snippet runs by letter, showing the first string letter by letter. I feel stupid, am I missing something? Check it out:
var name = ['Helen','Jim','Thomas','Luke','Theodore'];
var div = document.getElementById('cards');
for(var i=0;i<5;i++){
var newHtml = name[i]+' '+i+'</br>';
div.innerHTML = div.innerHTML + newHtml;
}
<div id="cards"></div>
Word name is a reserved word (as #prasad answered) in javascript that why your code was not working as expected.
See below code, after changing name with names. Its seems working as was working in jsfiddle.
var names = ['Helen','Jim','Thomas','Luke','Theodore'];
var div = document.getElementById('cards');
for(var i=0;i<5;i++){
var newHtml = names[i]+' '+i+'</br>';
div.innerHTML = div.innerHTML + newHtml;
}
<div id="cards"></div>
Note: name can only be used as local variable inside a function or iife and can not used as global varibale.
Try any one of the function its working. name is reserved word of javascript.But applied with in function .Its not act as a reserved word.This is one of the way preventing the action.
(function () {
var name = ["Helen","Jim","Thomas","Luke","Theodore"];
var div = document.getElementById('cards');
for(var i=0;i<5;i++){
var newHtml = name[i]+' '+i+'</br>';
div.innerHTML = div.innerHTML + newHtml;
}
})()
<div id="cards"></div>
Apparently name is a property of window and it has a setter which converts the input value to a string. Your code is trying to assign an array to that property which is magically converted to a string:
var name = ["foo", "bar"];
console.log(name); // array converted to "foo,bar"
So why does it work on jsFiddle? The answer is that, by default, jsFiddle wraps your code inside a function, something like this:
<script>
window.onload = function() {
var name = ["foo", "bar"];
console.log(name); // ["foo", "bar"]
}
</script>
This creates a closure where var name creates a new variable instead of referring to window.name. If you change your jsFiddle settings (JavaScript tab > Load type > No wrap - in body) then you get the same result as the StackSnippet like this:
<script>
var name = ["foo", "bar"];
console.log(name); // "foo,bar"
</script>
The solution is not to pollute the global namespace in the first place. That way you do not have to lookup the list of "words not to use as JavaScript variables".
name AKA window.name
Well name is most definitely not a reserved word in javascript.
name AKA window.name is the name of the window. Its value is set by a setter function and as the window name should be a string. So when you set it with name=["foo","bar"] it is converted to a string.
It is unfortunate that Javascript must share the global name space with every man and his dog and this illustrates another reason to avoid the global scope whenever possible.
Related
I am trying to change the entire word into capital letters. What is wrong with my approach, for individual letters toUpperCase is working fine
var name = "gates";
for (var i=0; i< name.length; i++){
name[i] = name[i].toUpperCase();
}
name;
So the thing is "hello world".toUpperCase() is working fine as expected. Why the looping individual characters in array does not work as expected!.
Is this some property in arrays/strings especially in JS?
As RGraham mentioned the string letters cannot be modified, I don't understand the negative feedback of the community. Even the question seems to be valid.
The reason this doesn't work, is that accessing a string using the array syntax is read-only. As per the MDN docs:
For character access using bracket notation, attempting to delete or
assign a value to these properties will not succeed. The properties
involved are neither writable nor configurable. (See
Object.defineProperty() for more information.)
So, console.log(name[0]) will work, but name[0] = "G"; will not update the name variable.
You don't need to loop through the letters, just do:
var name = "gates";
name = name.toUpperCase();
A string is immutable in most languages, meaning, you can't change individual characters, or add something, without ending up with a new one.
name = name.toUpperCase();
Will give you what you need, but a new, all-caps string is put in the variable 'name'.
Accoring to http://www.w3schools.com/jsref/jsref_touppercase.asp
var str = "Hello World!";
var res = str.toUpperCase();
http://www.w3schools.com/jsref/jsref_touppercase.asp
var str = "Hello World!";
var res = str.toUpperCase();
Result:
HELLO WORLD!
So for example I am trying to do a for loop in JS
for (var i=0;i<result.length;i++){
var btn[i] = document.createElement("BUTTON");
var t[i] = document.createTextNode("CLICK ME");
btn.appendChild(t[i]);
}
the i being the delimiter, is it possible to append it to another variable name like above when I try to create an element? Just to make the variable name unique. Right now I am trying with the square brackets and it's giving me an error saying unexpected []. Any help is appreciated thanks!
In browsers (I've never done any node.js stuff) the global scope lives in the window object.
bla = 'test';
window['bla'] == 'test';
This means that you can create a variable say test1 like this:
window[bla + 1] = 'foo';
I tried to convert snippet 1 to snippet 2 but this did not work (the text fields did not clear). f3aa and f3bb are each text fields that I need to clear after a sumbit.
Snippet 1
var target=document.getElementById('f3aa');
target.value='';
var target=document.getElementById('f3bb');
target.value='';
Snippet 2
o1('f3aa')=o1('f3bb')='';
Snippet 3
function o1(a)
{
document.getElementById(a);
}
Assuming I've understood your question correctly, you were nearly there:
document.getElementById('f3aa').value = '';
document.getElementById('f3bb').value = '';
In your snippet 2, you are trying to assign an empty string to a DOM element, rather than the value property of that element.
In snippet 1, you assign a DOM element to the target variable, and then assign an empty string to the value property of the target variable. As target contains a DOM element, you assign that string to the value property of that element, which is equivalent to the code I have shown above.
You forgot to include the attribute names from your first snippet in your second:
document.getElementById('f3aa').value='';
document.getElementById('f3bb').value='';
(Note that this isn't really an "optimization" - there will be no noticeable difference in how quickly the two snippets run. Use whichever is more readable.)
X('f3aa').value = X('f3bb').value = '';
where X is your query-by-ID implementation.
Live demo: http://jsfiddle.net/zmr29/
(I wrote a X function in my demo, but I assume that you either use a library or have some other shorthand for DOM queries.)
I think it's illegal to use var to declare a variable more than once in the same scope.
This code is bad:
var test = true;
var test = false;
This code is good:
var test = true;
test = false; // <-- no "var" keyword here
If I do this,
var element = {};
alert(element);
element[name] = "stephen";
alert(element.name);
Why doesn't element.name work?
When using bracket notation, (unless it's a variable) it needs to be in qoutes, like this:
var element = {};
alert(element);
element["name"] = "stephen";
alert(element.name);
You cant test it out here. To explain what I mean by "unless it's a variable", this would also work:
var myVariable = "name";
element[myVariable] = "stephen";
Because name should be in quotes.
This works:
var element = {};
alert(element);
element['name'] = "stephen";
alert(element.name);
Try it.
This is the reason why you may want to get an object's property dynamically. For example:
You have a variable, but you can't be sure of its value. The server send you the variable value so you should write like this.
obj[name].age // Here the name is a variable, and it can be changed in every page refresh, for example.
But if you want to set obj['name'] = 'Lorenzo' you have to use quotes.
Think like obj[name] is used for set, obj['name'] is used for get.
Here's the problem - I know function by name (and that function has already been loaded form an external script), but I don't have an actual function object avail for me to call. Normally I would call eval(function_name + "(arg1, arg2)"), but in my case I need to pass an object to it, not a string.
Simple example:
var div = document.getElementById('myDiv')
var func = "function_name" -- this function expects a DOM element passed, not id
How do I execute this function?
Thanks!
Andrey
Never use eval, it´s evil (see only one letter difference)
You can simply do:
var div = document.getElementById('myDiv');
var result = window[function_name](div);
This is possible because functions are first class objects in javascript, so you can acces them as you could with anyother variable. Note that this will also work for functions that want strings or anything as paramter:
var result = window[another_function_name]("string1", [1, "an array"]);
You should be able to get the function object from the top-level window. E.g.
var name = "function_name";
var func = window[name];
func( blah );