Advice for experienced developer trying Javascript for the first time - javascript

I'm very experienced in C/C++/Objective-C and over the last few days have been trying my hand at html/css/JS and am finding it very frustrating.
Time and time and time again I've been caught out as I've a syntax error or undeclared variable due to copying / pasting etc. with the consequence being that the code suddenly stops working then I have to scratch my head and figure out why.
The most painful thing is resorting to sprinkling alerts in the code everything something fails in order to track down the reason. I know there is the new console object for logging but it doesn't seem to work with Komodoedit or jsFiddle? Which is what I've been using.
Is there a way of using these tool, or alternative tools where I can step through the code line by line in a debugger like I can with other languages? Or any tricks for easy detection of problems with the code before executing it in addition to jslint?
[I don't want to use any libraries that might have built-in support for logging etc. as I'm finding they (well JQuery/JQuery mobile is) are drastically slowing down loading times on an iPhone so want to concentrate on pure JS.]
[My target browser is just iOS, but am using Komodoedit with Chrome most of the time and every few hours try it on an iPhone]
Thanks

You need several tools.
First, get yourself a real debugger. I use the one built into Chrome. There's a similar one built into Safari and Firebug available as an add-on for Firefox. This will allow you to set breakpoints and step through your code and see exactly what is happening.
Second, get very used to running your code through jsLint. This will show you many obvious typos and encourage you to write robust code from day one.
Third, start writing in strict mode. This will again prevent some obvious typos and force you to start some good habits.
Fourth, use console.log() when needed. Once you have a debugger, it's output will show in the debug console of the debugger for any page in your browser, including jsFiddle pages. You will have to invoke the debugger on the right frame in jsFiddle and then it will work fine. I use both a regular debugger and console.log() all the time with jsFiddle. It takes a little figuring in jsFiddle and the debugger to find where your own code is to set breakpoints, but once you find it, it's easy to use.
Fifth, javascript is simply not C++. While the syntax will seem quite familiar, the way you do things with anonymous functions and closures and objects and prototypes is very different. As one who programmed in C++ for many, many years before learning javascript, I very much appreciate what I can do now in javascript that was a lot more work in C++, but it took awhile to get my brain into a new mode of thinking. I spent too much time in my first years of javascript development trying to emulate C++ techniques rather than just learning the better way to accomplish the goal in javascript.
Sixth, you will have to change how you write and test code because of the lack of a compiler that finds errors for you. I remember in the days of C++, when I needed to refactor something, I could make a bunch of changes and then let the compiler find all the other places I need to fix the syntax. You can't do that with javascript. When you make mass changes, you can run through jsLint to find some issues and then you literally need to execute every path to make sure everything works. It is a bit of a pain.
Seventh, find a strategy/tools for unit testing. Once a project gets more than a few functions long, you will benefit greatly from building unit tests that you can run anytime you make significant changes. They will both find issues for you in a lot less time than without the unit tests and they will give you the courage to refactor and clean up your code when you see the need for that because you know the unit tests will tell you if everything is working again. It's extra work up front that pays dividends many times over down the road.

Firefox has an add-on called FireBug that is very helpful for debugging CSS/javascript, and yes, it does have the ability to step through a script as well as a command line where you can try out various javascript expressions. I'm pretty sure Chrome has a similar feature.

Here is the article in which you get a list of tools to debug the javascript
advance-javascript-debugging-techniques

Since you're using Chrome, you just need to open the developer console (spanner -> tools -> javascript console, or Ctrl+Alt+J (at a guess)). Instead of sprinkling your code with alerts, use console.log, console.error, and console.info to print to it. All of those are variadic, so you can pass as much to one call as you need.
In addition to this, you can use the console to test and modify parts of your code on the fly, or to just try out a few snippets to see if they work. It's a fully functional REPL that also works with the current document.
In the sources tab of the developer console, you are able to set breakpoints and step through your code, analysing state at each point. This page goes into some detail about it: http://chromedevtools.googlecode.com/svn-history/r421/trunk/tutorials/breapoints/index.html
In the elements tab, you are able to set breakpoints on changes to elements in the DOM, including changes to attributes and child nodes. Right click a node and select the option you want. This will come in handy when debugging code that is asynchronous and plays with the document (eg. AJAX calls inserting new content).
In addition to this, you can scroll to the bottom of the styles pane to the right, and open the event listeners section. Here, you can inspect all the events bound to the selected DOM node.
You can enter debugger (without a semicolon) into your code, and it will open the sources tab at that point so you can inspect the code further. I think this may be Chrome specific.
Finally, tools like JSlint will help you spot undeclared variables as you code, as well as cases where the formatting of your code creates unexpected errors, and some might even go as far as using syntax highlighting to make you notice variables that are undefined.
This is also just scraping the surface. Your editor and JSlint can make your code look right and parse without error, but the browser and its console is where you will spend most of your time.

Related

VS Code Node.js macOS debugging not working - I don't even know how to state the problem

Newbie question here, it seems... I'm losing my mind. Why is this so hard? I've been programming other languages for years, but I'm relatively new to node and JS. I've read and watched as much as I can find official and unofficial on the web about this and it's either years old or significantly different from my situation, so not very helpful.
I'd really, really appreciate anyone who can understand my (pretty simple, I would have thought!?) specific case and help me get this set up to just work. Possible?
macOS 10.15.6 Catalina.
As I understand it, node comes with the OS. It's Node.js 12.8.1
VS Code 1.48.2
I create a new file, name it abcd.js. VS Code figures out it's javascript. I add some code - read a file of JSON from the disk, make some changes, console.log some stuff (appears under the Output tab). I run it.* All good and works.
Now... Run menu > "Start Debugging". Or, There's a Run/Debug icon in the sidebar that shows a "Run and Debug" button which I click on. Both of those ask me for an environment - I choose Node.js, and the Debug console outputs this:
/usr/local/bin/node path/to/my/file.js
Debugger listening on ws://127.0.0.1:56430/30b0c2aa-278b-4540-94c4-825d30b94f57
For help see https://nodejs.org/en/docs/inspector
And that's it. I have breakpoints, but it doesn't stop on them. Something happens (too quick to see what it is). I don't think it's actually running my code because nothing new shows up under the Output tab.
There's also a note in that sidebar saying "To customize Run and Debug create a launch.json file." I've experimented with that as much as I can, but nothing I do seems to help.
I've been programming for years. I'm used to other languages and IDEs (eg. C, Java, AppleScript, Swift, others), where you open the IDE, write some code, hit run (or debug), it may or may not build a target (depending on the language and environment), but then it runs the code (opens the target app, or runs in the IDE, and allows you to step through the code, breakpoints, etc. in the IDE if debugging). Is JS/node programming radically different from this somehow?
*One theory:
I'm not doing this through any terminal or any browser. Maybe that's the problem...? At some point I installed a "Code Runner" plugin that I believe is what is running my code. It was a while ago, but if I recall correctly maybe I turned to that because I was looking for the experience I've described above, and this plugin gave me that where the "normal" node setup process didn't? Perhaps my problem is that that plugin simplifies RUNNING js scripts so much that my issues with DEBUGGING exist because that plugin allows me to bypass other usual complications with running JS/Node scripts (but doesn't have any debugging functionality of its own)?
My thanks to #ippi for his/her comment with a gif video. Not sure if the following really answers my question, but I'm posting it in case it helps anyone else.
I took some time to clean up my Mac a little, and I completely uninstall VSCode, all its extensions and supporting files and started again.
I re-installed Code from scratch, didn't add any extensions, and then tried what #ippi's video showed.
It still didn't work - I got more or less the same output as in my post, and I'm not sure if it was running the code or not.
I had an urgent deadline to meet so didn't come back to it till now - two days later - and now, it's working.
A couple of things changed in that time though I really don't know what fixed this, if it was either of those or anything else. The two changes I can remember that I've done the last two days are:
Despite my post saying my node was 12.8.1, sometime in the last couple of days it turned into 8.something. I updated it to the latest v12.8.3, and
to meet that deadline I used node inspect myfile.js in Terminal for a bit.
The inspect (mostly) worked to meet my deadline, but still a hassle compared to what's shown in #ippi's video. I definitely wanted to get it working that way.
So… updating node fixed it? Running it in the terminal for a bit fixed it? Something else? I'm at a loss to know what did it. But it's working now.
Thanks again to #ippi for that. It pointed me in a good direction at least - to clean up my install a bit, if nothing else.
Maybe this will help someone else sometime in the future.
It seems the ultimate answer is:
It should just work out of the box (possibly subject to updating node to its latest). If it doesn't then:
The issue most likely isn't that you have to do any fancy configuring or whatnot to make it work.
Instead, most likely something is wrong with your installation and/or OS and you should explore that.
#ippi's video attached in case his/her link ever breaks:

Dojo mysteriously, persistently blanked on page

We use the dojo framework on our websites. A client has called in a panic saying their sales from users of Microsoft Edge have completely dropped off. I've found that in that browser, intermittently, the dojo variable is null after page load. So of course no interaction works for those users, so of course no sales.
But in the course of testing I found this astonishing thing in devtools:
I don't even know how I would do that if I wanted to do it. So I want to track this down but I have no clue what to look for. I might've suspected some weird, recurring setInterval code, but I would not have thought that could get between the two statements on that last console line.
There's a script line just before the </body> tag where I'm able to put a breakpoint. At that point, dojo is set as the framework as expected. So some code that loads after page load is doing it.
(EDIT: I'd be willing to do iterative, brute force breakpoints if I could. But I only have access to Edge via BrowserStack, and trying to set useful breakpoints in minified code is very difficult in Edge's dev tools.)
Does anyone have a suggestion what sort of thing I should look for?
How to debug for this? Is there a client-exposed variable where you can see the functions set to the document's onload, or a way I can put breakpoints in them?
I attempted using a watch() shim in console to watch for the dojo object being changed, but didn't have much luck with that. (but might have done it incorrectly, so if this is an idea, I might need help with proper implementation).
EDIT: There's also this, if this helps make any sense of it. After I delete dojo, setting it works as expected.
Well, I don't know what the specific problem is, but someone has at least given me a way in which this is possible:
window.__defineGetter__('dojo', function(){ return null })
This doesn't exist in the original code, but at least now I see how it's possible at all. The person who gave me this suggests that the code might be trying to get and protect its own copy of dojo, but something about it goes wrong in Edge.

Is it possible to follow JavaScript in real-time?

I would like to see what the JavaScript interpreter is doing in real-time, which line it is reading and which function it is running, because I would like to make a full debug on every little piece of the JavaScript to make it faster. For this I need some tool to tell me what the interpreter is doing exactly, if it is defining a variable, if it's running a function, if it's in a loop, check the current intervals (defined in setInterval).
As far as I know Firebug can't do that.
Check out the javascript tab in Firebug, it's a full debugger. Set a break point and when your code hits that line you will have full debugging access to variables etc. Chrome has similar functionality in the developer tools which are included in a standard install.
If you're looking to do automated monitoring/analysis of your program, check out Chrome's Debugger Protocol. It provides a programatic API. I believe (but could be wrong) that this is what tools like Web Inspector and node-inspector are built on.
If you want something more than what the standard Firebug/Web Inspector interfaces are built on, you're going to have to either use something like this or start hacking on the internals of the V8 and Gecko JS interpreters.
As the other answer says,if you want to go step by step, setting a debug point is the way to go.
But since you seem interested in improving performance you might want to consider optimizing only the true bottlenecks in your application. To see which functions take the most to run, and other statistics you might want to take a look at console.profile() (available both in firebug and chrome).
Here is an example:
console.profile('myProfile');
//some code you want to know more about
console.profileEnd();
You can also start it manually by clicking the Profile button in the Console panel(in firebug)/ Profile panel (chrome)
In Chrome you might want to also take a look at Heap Snapshots (they tell you about memory usage).

Debugging JavaScript (FBJS) in Facebook

I am developing an application on Facebook. I am running into some vague situation that I want to debug. The problem is that Facebook adds MUCH wrapping code and changes the name, not to mention that it already uses a modified version of JavaScript called FBJS. These things make it almost impossible to use tools like FireBug to debug the code. Does anybody have a suggestion for such cases? I am thinking of some debugging library that traces the code, variables, etc., and show me some results in some other window, or something like that.
You can try adding the line debugger to your javascript where you want to break. Firebug should break point on that line.

Firefox add-on tools for checking JavaScript syntax?

Not sure if there is any Firefox add-on tool for checking JavaScript syntax, var declaration, or even pre-compiling available?
I find out is very difficult to debug JavaScript in a web html page. I have to add some script there. When the scripts get very big or long, it stops working. Basically, there must be some bugs. It is very frustrating even the load event stop working. I do need some good tools to find out the bugs.
I have tried FireBug. It is good but not enough. Maybe I don't know all its features. Anyway, I need any good suggestions.
This page may help you a bit as it also contains a screencast.
Debugging Javascript in Firefox with Firebug
It's not strictly an Add-On (although you can obviously run it in a Firefox web page), but I've found JSLint to be helpful in exposing expression anomalies that might or might not be strictly invalid syntax (although it will catch all those, too.)
My suggestion is to check you javascript with JSLint. JSLint will show you common problems in javascript code and helps you to create strict and compatible code.
YSlow includes JSLint as Tool.
As an alternative to FireBug check this debugger: Venkman JavaScript Debugger, has been out there for a while, and it's not bad at all...
I have always been a firebug fan and it sure is one of the best debuggers out there. Any JS issue Press F12, Enable the console for catching the errors and then you can find the exact line causing the error. Add a breakpoint and you can see the exact values of variables too. Very intuitive UI..just get used to using it and it will save a lot of your time.
I HIGHLY recommend Rainbow. It's still in Beta and only works in FF3, but it offers syntax highlighting. That will get you half-way there when it comes to syntax.
I constantly use firebug with a js file that has some 15000 lines. I've had no problems with it (sometimes I have to wait a few seconds for it to scroll to the breakpoint but even then it works fine).
Unfortunately JSLint does'nt work for us. We use some third party code that while beeing "valid" has unnecessary ";" according to jsLint. The code is in the beginning of our js file and jslint stops analyzing at 3% because it thinks there are too many errors (all of them unnecessary ";".)
You're missing the point on 2 counts:
First, being presented with a gazillion unnecessary error messages will make it impossible to find the problem in the first place.
Secondly, the errors are unnecessary. I used to use JSLint religiously, but now it's become too much of a code Nazi and I can't use it.
I'm aware that many of the things it checks for can be disabled, but I just don't have enough time to research what I'd have to do.
The issue is the usability of the default configuration. I, like the original poster, am just looking for a way to find true JavaScript syntax errors very quickly, including on HTML pages. I'm sure that Firebug can do it, but as in the case with JSLint, I don't have the spare time to find out how.
I do, however, use Firebug for debugging, though the version I'm using (1.10.3) has a bad habit of displaying errors, but reporting an incorrect file and line number.
Hi Gene: you could change one variable option.maxerr inside your jslint.js file into the number you want.
The default value is 50, you could change it to 500 or 1000 to suite your taste.
I use both the following for code validation.
JSHint # http://jshint.com
JSLint FF Plugin. Get at https://addons.mozilla.org/en-us/firefox/addon/jslinter/
Alternatively, jshint and jslint plugins are available for text editors like Notepad ++, sublime etc.

Categories

Resources