I've installed brackets and currently playing around with variables and functions. All the outputs work fine in the console, however I keep getting this error in the editor.
How do I go about fixing this?
The no-undef rule looks out for undefined variable, without any initial assumption on the environment and the global variables (console for instance).
You can specify that you are in an environment where console indeed exists, by adding browser and/or node envs in your .eslintrc:
env: {
browser: true,
node: true,
},
More info in the rule doc
just to have comment:
/*global console*/
as the first line of your .js file, and then have:
// eslint-disable-line no-console
at the line of the console.log("");
this will make the error go away!
Since you have it as a Capitol C, I would guess that the editor thinks you're looking for a function or class. Try lowering it from Console.log() to console.log("john won...") and see if that works.
I assume it's coming from no-console rule, which disallows calls to methods of the console object.
In JavaScript that is designed to be executed in the browser, it’s
considered a best practice to avoid using methods on console. Such
messages are considered to be for debugging purposes and therefore not
suitable to ship to the client. In general, calls using console should
be stripped before being pushed to production.
Examples of correct code for this rule:
/*eslint no-console: "error"*/
// custom console Console.log("Hello world!");
As a solution, you can add this to your set of rules in .eslintrc
rules: {
'no-console': 'off'
}
This one was driving me crazy as well. You can edit Brackets' config JSON. It will remove the error icon from the left gutter:
{
"brackets-eslint.gutterMarks": false
}
Reference: https://github.com/brackets-userland/brackets-eslint/blob/master/README.md
add 'no-console' in rules object is inactive
I think you should write "console.log" instead of "Console.log". It should be lowecase.
This might seem like a special case, but deleting and recreating the .eslintrc file fixed this issue for me.
Related
I am writing a web app using AngularJS (v1.5) so I have some controllers, and in those controllers I am often declaring something like :
function myController($someDirectives, ...){
var ctrl = this;
// My code
}
The thing is when I JSHint my code, I get this warning message for all of my 'this' declared in controllers :
If a strict mode function is executed using function invocation, its 'this' value will be undefined.
I must precise that in my .jshintrc file, I set "strict":false.
Does anyone know how to disable this message in particular?
Thanks in advance.
set the configuration in .jshintrc file
{
"validthis": true // Tolerate using this in a non-constructor
}
You can always override jshint options in the code-block ie.
/* jshint validthis: true */
I had the same issue, with a very similar environment angular 1.5.5 always getting the same lint warning:
If a strict mode function is executed using function invocation, its 'this' value will be undefined.
I've changed the name of my component's main function starting with upper-case and the warning disappeared
function MyController($someDirectives, ...){
I'm having the same issue. I'm doing "indirect invocation" with the function in question, not "function invocation", and 'this' is referenced many times in the function body.
In my case, I was having so many of these "errors" that jsHint quit before scanning my whole script.
To get around this I put this at the top of my script-file:
/*jshint maxerr: 10000 */
It did not suppress the errors, but at least it allowed me to scroll down to see jsHint's analysis of the entire script.
I don't know why but some words that I use as function names get a lint error of being defined but never used.
For instance, the code below returns error:
// I am using AngularJS
$scope.close = close;
function close() {
/* Code here */
}
But this does not:
// I am using AngularJS
$scope.close2 = close2;
function close2() {
/* Code here */
}
The error is on the line function close(). Why is this such a special name? How can I mute this error?
(Note: Answer has been heavily edited)
Summary
John Papa says to use latedef in JSHint and, at least implicitly, to ignore JSLint issues. (latedef defined here.)
I believe there's a plays-nicely solution (see below), however, that includes the advantages of Papa's suggested style with code that lints in JSHint and JSLint.
JSHint is "wrong" not to complain about close2. JSLint catches it exactly like you'd expect.
close but not close2 is a JSHint problem
For what it's worth, if you paste your code (jslint formatted Pasteee with both close & close2 here) into JSLint.com, both close and close2 cause errors. If you're not seeing an error for close2, I'm guessing it's JSHint's problem, but it'd be more useful to see exactly what you're linting through JSHint (in context) to know for sure.
So close is not a special name to JSLint. I would like to see your "actual" code in context to see if JSLint would say something similar
Just to be clear, this breaks on JSLint.com:
/*jslint sloppy:true, white:true */
/*global $scope */
$scope.close2 = close2;
function close2() {
return "something";
}
That will produce 'close2' was used before it was defined. $scope.close2 = close2;
If you want to know why JSHint is, I believe, breaking, we can go JSHint code spelunking, but to answer your JSLint tag (at least) the behavior you're seeing isn't happening.
How to fix
See this SO answer on exactly what you're discussing here, where John Papa says to use latedef in JSHint. One way around the linting issue is to ignore Papa and define the function first, but, as you mention in your comment, below, that's not ideal.
So here's the best compromise I could come up with...
Declare, but don't define, variables that will hold functions.
Insert your Angular directive
Define your functions from 1.
That definitely mutes the JSHint error, since the code that caused it isn't there any more. If I was doing Angular and needed to follow Papa-style, that's what I'd do to keep Crockford's blessing.
Example:
(function () {
'use strict';
// 1. Declare your function names. Minimally spammy!
var theController;
// 2. Directive
angular
.module('myApp')
.controller('myAppCtrl', theController);
// 3. *Define* the functions. No `latedef` needed, and JSLint compliant.
// Keeps "the list of calls at the top of the page" and allows you to
// "jump to each definition if you need more details". QED? ;^)
theController = function () {
return "so jslint doesn't complain about empty blocks";
};
}());
In Karma tests, there are a lot of global variables and functions, which JSHint complains about (it is integrated into my editor).
How can I tell JSHint to ignore all undefined variables in this one specific file? I would expect /* jshint undef: false */ to turn off these warning, but it doesn't.
The correct way to tell JSHint about globals is to use the globals directive. For example:
/*globals globalFunction, anotherGlobal, oneMore */
This will prevent "{a} is not defined" warnings when JSHint encounters any of the listed identifiers.
Alternatively, if you really want to ignore all "not defined" warnings in that file, and you're using JSHint 1.0.0 or above, you can simply turn off that specific warning:
/*jshint -W117 */
Just add this rule in your .jshintrc file.
"-W117": true
This will ignore all the warnings which say, '* is not defined.'
Ran into this problem using jshint this afternoon.
This following fix worked for me.
Instead of using "globals", try using "predef".
For example:
{
/*
* RELAXING OPTIONS
* =================
*/
// Suppress warnings about == null comparisons.
"eqnull": true,
"predef" : ["describe", "expect", "it", "inject", "beforeEach", "angular"]
}
I've found myself using jshint ignore:line as a way of addressing this need:
var unusedVar; // jshint ignore:line
This allows jshint to continue its useful checking for this condition but where there are explicit reasons to ignore a specific declaration than adding this both addresses the issue and does it in a way that is immediately apparent to anyone looking at the code.
A good example (at least for me), is when using ES6's destructuring to illicit a set of shortcuts that you may or may not use all the time. In Ember, I often use many of the methods that hang off of it such as typeOf and computed. Rather than always referring to Ember.computed it's far nicer to just refer to computed and have something like the following at the top of all my Ember objects:
const { computed, $, A, run, on, typeOf, debug, get, set } = Ember; // jshint ignore:line
I'm building a normal webpage which requires me to load about five CSS files and ten Javascript files.
When loading them separately in the HTML page, my webpage loads fine.
Now for production, I concatenated all the Javascript into a single file, in the order needed, and all the CSS into another file. But when I try to run the web page with the concatenated files it throws an error saying:
Uncaught TypeError: undefined is not a function
On the line where jquery.min.js is being loaded in the concatenated Javascript file.
What can I do to mitigate this? I want to concatenate all files and minify them for production. Please help.
EDIT: I merged the Javascript and CSS in the order they were when they were being loaded individually and were working fine.
Assuming this problem still has not be resolved, a lot of individual files don't end their code with a semicolon. Most jQuery scripts end with (jQuery) and you need to have (jQuery);.
As separate files the script will load just fine but as one individual file you need the semicolons.
You might have to re-check the order in which you are merging the files,
it should be something like:
jquery.min.js
jquery-ui.js
any third party plugins you loading
your custom JS
This solution worked for me
;(function($){
// your code
})(jQuery);
Move your code inside the closure and use $ instead of jQuery
I found the above solution in https://magento.stackexchange.com/questions/33348/uncaught-typeerror-undefined-is-not-a-function-when-using-a-jquery-plugin-in-ma
after seraching too much
I got the same error from having two references to different versions of jQuery.
In my master page:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
And also on the page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
I had this problem recently with the jQuery Validation plug-in, using Squishit, also getting the js error:
"undefined is not a function"
I fixed it by changing the reference to the unminified jquery.validate.js file, rather than jquery.validate.min.js.
#MvcHtmlString.Create(
#SquishIt.Framework.Bundle.JavaScript()
.Add("~/Scripts/Libraries/jquery-1.8.2.min.js")
.Add("~/Scripts/Libraries/jquery-ui-1.9.1.custom.min.js")
.Add("~/Scripts/Libraries/jquery.unobtrusive-ajax.min.js")
.Add("~/Scripts/Libraries/jquery.validate.js")
.Add("~/Scripts/Libraries/jquery.validate.unobtrusive.js")
... more files
I think that the minified version of certain files, when further compressed using Squishit, for example, might in some cases not deal with missing semi-colons and the like, as #Dustin suggests, so you might have to experiment with which files you can doubly compress, and which you just leave to Squishit or whatever you're bundling with.
For those out there who still couldn't fix this, I did so by changing my 'this' to '$(this)' when using jQuery.
E.G:
$('.icon').click(function() {
this.fadeOut();
});
Fixed:
$('.icon').click(function() {
$(this).fadeOut();
});
I've run into the very same issue, when mistakenly named variable with the very same name, as function.
So this:
isLive = isLive(data);
failed, generating OP's mentioned error message.
Fix to this was as simple as changing above line to:
isItALive = isLive(data);
I don't know, how much does it helps in this situation, but I decided to put this answer for others looking for a solution for similar problems.
Yes, i also I fixed it changing in the js libraries to the unminified.
For example, in the tag, change:
<script type="text/javascript" src="js/jquery.ui.core.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.rcarousel.min.js"></script>
For:
<script type="text/javascript" src="js/jquery.ui.core.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="js/jquery.ui.rcarousel.js"></script>
Quiting the 'min' as unminified.
Thanks for the idea.
Remember: Javascript functions are CASE SENSITIVE.
I had a case where I'm pretty sure that my code would run smoothly. But still, got an error and I checked the Javascript console of Google Chrome to check what it is.
My error line is
opt.SetAttribute("value",values[a]);
And got the same error message:
Uncaught TypeError: undefined is not a function
Nothing seems wrong with the code above but it was not running. I troubleshoot for almost an hour and then compared it with my other running code. My error is that it was set to SetAttribute, which should be setAttribute.
In case there are any morons out there like me, I had this frustrating problem because I forgot a simple
new
keyword before instantiating a new object.
I just had the same message with the following code (in IcedCoffeeScript):
f = (err,cb) ->
cb null, true
await f defer err, res
console.log err if err
This seemed to me like regular ICS code. I unfolded the await-defer construct to regular CoffeeScript:
f (err,res) ->
console.log err if err
What really happend was that I tried to pass 1 callback function( with 2 parameters ) to function f expecting two parameters, effectively not setting cb inside f, which the compiler correctly reported as undefined is not a function.
The mistake happened because I blindly pasted callback-style boilerplate code. f doesn't need an err parameter passed into it, thus should simply be:
f = (cb) ->
cb null, true
f (err,res) ->
console.log err if err
In the general case, I'd recommend to double-check function signatures and invocations for matching arities. The call-stack in the error message should be able to provide helpful hints.
In your special case, I recommend looking for function definitions appearing twice in the merged file, with different signatures, or assignments to global variables holding functions.
Make sure you have commented out any commentaries. Sometimes when copying and pasting you will leave out the "/*!"
Also when you go into the console they will list your errors and you should take it one at a time. If you see "Uncaught SyntaxError: Unexpected token * " That might mean it is reading your js file and it isn't getting past the first line.
/*!
* jquery.tools 1.1.2 - The missing UI library for the Web
*
* [tools.tabs-1.0.4, tools.tooltip-1.1.2, tools.scrollable-1.1.2, tools.overlay-1.1.2, tools.expose-1.0.5]
*
* Copyright (c) 2009 Tero Piirainen
* http://flowplayer.org/tools/
* File generated: Wed Oct 07 09:40:16 GMT 2009
*/
I got this when I accidentally passed too many parameters into a jquery function that only expected one callback parameter.
For others troubleshooting: make sure you check all your jquery function calls for extra parameters.
I have a bunch of console.log() calls in my JavaScript.
Should I comment them out before I deploy to production?
I'd like to just leave them there, so I don't have to go to the trouble of re-adding the comments later on if I need to do any more debugging. Is this a bad idea?
It will cause Javascript errors, terminating the execution of the block of Javascript containing the error.
You could, however, define a dummy function that's a no-op when Firebug is not active:
if(typeof console === "undefined") {
console = { log: function() { } };
}
If you use any methods other than log, you would need to stub out those as well.
As others have already pointed it, leaving it in will cause errors in some browsers, but those errors can be worked around by putting in some stubs.
However, I would not only comment them out, but outright remove those lines. It just seems sloppy to do otherwise. Perhaps I'm being pedantic, but I don't think that "production" code should include "debug" code at all, even in commented form. If you leave comments in at all, those comments should describe what the code is doing, or the reasoning behind it--not blocks of disabled code. (Although, most comments should be removed automatically by your minification process. You are minimizing, right?)
Also, in several years of working with JavaScript, I can't recall ever coming back to a function and saying "Gee, I wish I'd left those console.logs in place here!" In general, when I am "done" with working on a function, and later have to come back to it, I'm coming back to fix some other problem. Whatever that new problem is, if the console.logs from a previous round of work could have been helpful, then I'd have spotted the problem the first time. In other words, if I come back to something, I'm not likely to need exactly the same debug information as I needed on previous occasions.
Just my two cents... Good luck!
Update after 13 years
I've changed my mind, and now agree with the comments that have accumulated on this answer over the years.
Some log messages provide long-term value to an application, even a client-side JavaScript application, and should be left in.
Other log messages are low-value noise and should be removed, or else they will drown out the high-value messages.
If you have a deployment script, you can use it to strip out the calls to console.log (and minify the file).
While you're at it, you can throw your JS through JSLint and log the violations for inspection (or prevent the deployment).
This is a great example of why you want to automate your deployment. If your process allows you to publish a js file with console.logs in it, at some point you will do it.
To my knowledge there is no shorter method of stubbing out console.log than the following 45 characters:
window.console||(console={log:function(){}});
That's the first of 3 different versions depending on which console methods you want to stub out all of them are tiny and all have been tested in IE6+ and modern browsers.
The other two versions cover varying other console methods. One covers the four basics and the other covers all known console methods for firebug and webkit. Again, in the tiniest file sizes possible.
That project is on github: https://github.com/andyet/ConsoleDummy.js
If you can think of any way to minimize the code further, contributions are welcomed.
-- EDIT -- May 16, 2012
I've since improved on this code. It's still tiny but adds the ability to turn the console output on and off: https://github.com/HenrikJoreteg/andlog
It was featured on The Changelog Show
You should at least create a dummy console.log if the object doesn't exist so your code won't throw errors on users' machines without firebug installed.
Another possibility would be to trigger logging only in 'debug mode', ie if a certain flag is set:
if(_debug) console.log('foo');
_debug && console.log('foo');
Hope it helps someone--I wrote a wrapper for it a while back, its slightly more flexible than the accepted solution.
Obviously, if you use other methods such as console.info etc, you can replicate the effect. when done with your staging environment, simply change the default C.debug to false for production and you won't have to change any other code / take lines out etc. Very easy to come back to and debug later on.
var C = {
// console wrapper
debug: true, // global debug on|off
quietDismiss: false, // may want to just drop, or alert instead
log: function() {
if (!C.debug) return false;
if (typeof console == 'object' && typeof console.log != "undefined") {
console.log.apply(this, arguments);
}
else {
if (!C.quietDismiss) {
var result = "";
for (var i = 0, l = arguments.length; i < l; i++)
result += arguments[i] + " ("+typeof arguments[i]+") ";
alert(result);
}
}
}
}; // end console wrapper.
// example data and object
var foo = "foo", bar = document.getElementById("divImage");
C.log(foo, bar);
// to surpress alerts on IE w/o a console:
C.quietDismiss = true;
C.log("this won't show if no console");
// to disable console completely everywhere:
C.debug = false;
C.log("this won't show ever");
this seems to work for me...
if (!window.console) {
window.console = {
log: function () {},
group: function () {},
error: function () {},
warn: function () {},
groupEnd: function () {}
};
}
Figured I would share a different perspective. Leaving this type of output visible to the outside world in a PCI application makes you non-compliant.
I agree that the console stub is a good approach. I've tried various console plugins, code snippets, including some fairly complex ones. They all had some problem in at least one browser, so I ended up going with something simple like below, which is an amalgamation of other snippets I've seen and some suggestions from the YUI team. It appears to function in IE8+, Firefox, Chrome and Safari (for Windows).
// To disable logging when posting a production release, just change this to false.
var debugMode = false;
// Support logging to console in all browsers even if the console is disabled.
var log = function (msg) {
debugMode && window.console && console.log ? console.log(msg) : null;
};
Note: It supports disabling logging to the console via a flag. Perhaps you could automate this via build scripts too. Alternatively, you could expose UI or some other mechanism to flip this flag at run time. You can get much more sophisticated of course, with logging levels, ajax submission of logs based on log threshold (e.g. all Error level statements are transmitted to the server for storage there etc.).
Many of these threads/questions around logging seem to think of log statements as debug code and not code instrumentation. Hence the desire to remove the log statements. Instrumentation is extremely useful when an application is in the wild and it's no longer as easy to attach a debugger or information is fed to you from a user or via support. You should never log anything sensitive, regardless of where it's been logged to so privacy/security should not be compromised. Once you think of the logging as instrumentation it now becomes production code and should be written to the same standard.
With applications using ever more complex javascript I think instrumentation is critical.
As other have mentions it will thrown an error in most browsers. In Firefox 4 it won't throw an error, the message is logged in the web developer console (new in Firefox 4).
One workaround to such mistakes that I really liked was de&&bug:
var de = true;
var bug = function() { console.log.apply(this, arguments); }
// within code
de&&bug(someObject);
A nice one-liner:
(!console) ? console.log=function(){} : console.log('Logging is supported.');
Yes, it's bad idea to let them running always in production.
What you can do is you can use console.debug which will console ONLY when the debugger is opened.
https://developer.mozilla.org/en-US/docs/Web/API/console/debug