whats wrong in this code why i am getting push is not a function?
var name = ['Brinth','Green','Yellow'];
var newname = name;
newname.push('Black');
console.log(name);
whats wrong in this code why i am getting push is not a function?
var name = ['Brinth','Green','Yellow'];
var newname = name;
newname.push('Black');
console.log(name);
This is because if you declare variables in the global scope with var
, they are implicitly set as properties on the window
object; and window
already has a name
property, and any assignment of which will get coerced to a string (which doesn’t have a .push()
method):
var name = ['Brinth', 'Green', 'Yellow']
console.log(window.name) // String "Brinth,Green,Yellow"
This is indeed rather unfortunate, but then again it is also the reason why you can directly call say console.log()
, where it should technically be window.console.log()
(or window.setTimeout()
etc.). Now there are ways around this; you can create a dedicated scope in an IIFE:
(function () {
var name = ['Brinth', 'Green', 'Yellow']
var newname = name
newname.push('Black')
console.log(name)
}())
or you can use const
insteed of var
, which does not assign to the global object:
const name = ['Brinth', 'Green', 'Yellow']
const newname = name
newname.push('Black')
console.log(name)
wow thats really unfortunate…
A better name for that array is names
anyhow, or colors
, instead of name.
Have you any problem with renaming the variables so that they work and make better sense? That’s a standard code improvement technique too.
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.