Inside the console, you can simply declare variables and use them.
var x = 'thing';
undefined
x + 3;
'thing3'
I want set that variable from a Javascript file, and use it in the console. That does not seem possible, so I hope somebody knows a solution for it.
In a javascript file, typing console.log(var x = 'thing') gives compilation errors in Gulp. I know I can just type console.log(x), but I want to use the variable and play with it in the console.
How can I declare variables that I can use in the console?
You are looking for a simple
var x = {thing: 'thing'};
console.log(x);
The undefined in the console comes from evaluating a statement that doesn't return anything. If you don't evaluate it in the console, but put it into your js files, there won't be any log.
I'm trying to debug my webpage using console.log
Don't. Use a debugger. You can statically insert breakpoints in your code with a debugger; statement.
How can I interact with logged variables from a JS file in the console?
The best thing of breakpoints in a debugger is: you can interact with any variables in the scope of the breakpoint without even needing to log them.
Maybe use console.debug(myTest.test)
I will suggest you to use the debugger rather than using global variables as it's not secure if you are able to access those variables in console. Use chrome while debugging. Open console and select the js file which you want to debug and put breakpoints.
Related
I have a website which uses Google Analytics and Google Tag Manager. It has been live for a couple of days but today the GTM script (gtm.js) started giving me errors in the console: "Uncaught TypeError: Assignment to constant variable". This, in turn, is causing some of my custom JS to not work as intended.
The GTM script is included as the second tag in as well as a immediately after the opening body tag, as instructed here : [https://developers.google.com/tag-platform/tag-manager/web][1]
This is the error that I get in the console:
Uncaught TypeError: Assignment to constant variable.
at <anonymous>:1:157
at <anonymous>:1:260
at gtm.js?id=GTM-XXX:271:414
at gtm.js?id=GTM-XXX:272:118
at b (gtm.js?id=GTM-XXX:272:337)
at dc (gtm.js?id=GTM-XXX:47:276)
at e (gtm.js?id=GTM-XXX:132:34)
at gtm.js?id=GTM-XXX:31:130
at Array.<anonymous> (gtm.js?id=GTM-XXX:133:454)
at Object.execute (gtm.js?id=GTM-XXX:133:194)
Does anyone recognize this issue? This error occurs in Chrome (Mac and Windows), Edge but not in Firefox (neither Mac nor Windows). Safari gives me a similar error "TypeError: Attempted to assign to readonly property."
First of all, you typically don't need a GA script if you have GTM. GTM is perfectly capable of managing GA.
Now to debug it properly, open the drawer in your devtools and go to the Network Request Blocker tool. Add a new blocking rule to block gtm. Reload the page, see if the error disappears. If it doesn't, then the issue is not in gtm. If it does disappear then we switch to gtm debugging.
Go to GTM, open site preview, get the error in the preview window, see what tags fired right before the error happened and try pausing the tags. See if by pausing them you can indicate which one causes the issue.
Or you could use a redirector extension (or a similar one) to replace your gtm container with a completely empty (but published) container and see if that error occurs. If it still occurs with an empty container, and you didn't make any trivial mistakes like rewriting a const in your CHTML tags/CJS vars/templates, it's likely your front-end interfering with GTM through some globals or overriding native functions, or, well, debug it further so we would know where to dig.
If you remove your custom JS tags, I suspect you'll see the error is resolved.
The error given is quite specific - there's an attempted assignment to a constant. I suspect this is happening within your own code as executed by GTM per the bottom of the stack trace you provided.
Put simply, somewhere in your code, I suspect you have something like the following:
const myVar = 123;
myVar = 456; //Error thrown here because you're illegally trying to change the assigned value
This fails because the const keyword indicates that the variable both cannot be redeclared nor reassigned in the same block scope.
It should instead read either of the following:
Using a 'var' statement
Var declares a variable named 'myVar' and assigns the value 'hello' to it. Other assignments can be made to the variable in the same scope.
var myVar = 'hello';
Using a 'let' statement
Let also declares a variable named 'myVar' and assigns a value of 'hello' to it. Other assignments can be made to this variable in the same block scope, but the variable itself cannot be redeclared.
//Simple example
let myVar = 0;
//Using this in a loop
for (let i = 0; i < 5; i++) { //Legal because you declare the variable once and can assign new values each iteration
//...
}
Swapping out the use of 'const' with any variable where you're assigning a new value to a variable and initially using the let keyword instead should resolve your error.
I am trying to access a variable from another file in JavaScript, and I'm not able to. When I try to print that variable out, for example, Intellisense suggests the variable. However, when I actually run it, I get the error Uncaught ReferenceError: myVariable is not defined
The variable is definitely declared in my file ('homePage.js').
I thought that all variables in Javascript were global, so I'm not sure why this is happening. All my files are in the same folder. Do I need to import something or am I just doing something completely wrong?
Thank you!
Maybe you are trying to access the variable value when your file still not loaded in the browser. You can check this using window.onload
window.onload = function() {
console.log('myVariable', myVariable);
// or execute some function that use the variable
}
https://developer.mozilla.org/es/docs/Web/API/GlobalEventHandlers/onload
You can also move variables into session state / cookie and pull it back into the other script from there.
The object {'1':'test'} gives an error in Firefox, but seems to be fine in Chrome. Does anyone know how to get around this error and make this work? The keys and values are from an external source so I can't just change them. (Run the code snippet below in Firefox and you will see the error.)
{'1':'test'}
You have to save the object in a variable or use it in any way. Just writing in inside a script block does nothing.
The following works fine:
var obj = {'1':'test'};
alert(obj['1']);
I tried in chrome console and firefox console.
Indeed, that doesn't work in Firefox, but, it's normal.
In javascript you can't type JSON without variable declaration before.
So, Firefox doesn't understand it because javascript doesn't understand it.
In fact, I think that Chrome overrides the javascript interpretor to allow declaration without attributions.
Like in python shell when you type 5, it will write 5. So with that Chrome allow you to see the structure of an array or object whatever, just by typings them without declare it into a variable.
You can see an example here :
https://jsfiddle.net/3yqdj599/
let yes = {'1':'test'};
console.log(yes)
// {'1':'test'} => that doesn't work
Finally, don't worry, since a browser is able to execute javascript, if you assign your object in a variable, it will interpret it.
I hope this is clear and helped you ! :)
Cya !
Rails will not let me run JS code, I have these errors
1)
2)
whenever you add JS code, the errors appear.
Some idea why this happening?
Just because you're getting error highlights in your IDE, doesn't necessarily mean your code is wrong. Try running your server, navigate to your site from your browser, and check the developer console. Do you still see javascript errors?
This warning (it is not an error) is being displayed because your IDE thinks that the variable $ is not defined in your code. However, it is not able to find out that $ is a global variable defined in the jQuery library, imported a few lines before.
The IDE is just saying that the presence of that variable is not guaranteed unless you properly import the needed libraries to make it exist (jQuery in this case). Your code should work properly. In order to identify errors in your javascript code, I would recommend you to use the built in console in the web browser.
I've seen some of the console wrappers that stop errors in browser with a console and more advanced ones that enable logging in older browsers. But none that I've seen help switch on and off the debug code.
At the moment I do a find and replace to comment out debug code. There must be a better way?
I'm using Combres which uses YUI to minify the JavaScript. I've seen some posts that mention using double semi colons to mark lines to be removed in the minification process. Is this a hack or good practice?
Probably you should have your own wrapper around console.log() and log your debug info via that wrapper. That way you can replace that single function with an empty function once you deploy to production so the console won't flood with debugging info. You can also replace the actual console.log function with an empty function, but that would prevent any Javascript from outputting to console, not just yours.
If you look at how the YUI Framework does it, they actually use a regex and generate 3 files from source. One that has the logging -debug, one that has the logging stripped out, just the file name, and a minified version with no logging. Then you can set a global config to say which version you want. I've worked that way in the past and works nicely.
Define your own debugging function that'd be wrapper around console.log or anything else you want and make sure that minifier can easily deduce that it is no-op if you make it empty. After that, once you comment function body out, most minifiers should detect that there's nothing to call or inline and remove references to your function completely.
Here's the example:
(function() {
function debug() {
console.log(arguments)
}
function main() {
debug(123)
alert("This is production code!")
debug(456)
}
main()
})()
I've put it into anonymous function to restrict scope of debug and don't let it be assigned to window - that allows minifier to easily decide if it is necessary or not. When I paste this code to online GCC, I get:
(function(){function a(){console.log(arguments)}a(123);alert("This is production code!");a(456)})();
But once I add // before console.log to make debug empty, GCC compiles it to:
(function(){alert("This is production code!")})();
...removing all traces of debug code completely!
Use Y.log() instead, and then you can use gallery-log-filter to filter the log messages that you want to see printed.