Javascript Processing in browser [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How does a JavaScript parser work?
How do browsers compile Javascript scripts? What type of compiler it used?

JavaScript isn't compiled, but rather parsed and interpreted. This differs from browser to browser.
Chrome, uses V8, which happens to also be used by node.js. Internet Explorer has a proprietary engine known as Chakra.
As for general rules, the Annotated ES5 shares some insight:
The source text of an ECMAScript program is first converted into a sequence of input elements, which are tokens, line terminators, comments, or white space. The source text is scanned from left to right, repeatedly taking the longest possible sequence of characters as the next input element.

The browsers don't compile javascript, it just parse the file and execute it.
Look here: JavaScript_engine

Javascript gets interpreted; this is like compiled on the fly, while running, when needed. That's why a page with javascript errors will just work until a part of bad code gets used. the bad code block will just stop.

Related

Spaces in equal signs

I'm just wondering is there a difference in performance using removing spaces before and after equal signs. Like this two code snippets.
first
int i = 0;
second
int i=0;
I'm using the first one, but my friend who is learning html/javascript told me that my coding is inefficient. Is it true in html/javascript? And is it a huge bump in the performance? Will it also be same in c++/c# and other programming languages? And about the indent, he said 3 spaces is better that tab. But I already used to code like this. So I just want to know if he is correct.
Your friend is a bit misguided.
The extra spaces in the code will make a small difference in the size of the JS file which could make a small difference in the download speed, though I'd be surprised if it was noticeable or meaningful.
The extra spaces are unlikely to make a meaningful difference in the time to parse the file.
Once the file is parsed, the extra spaces will not make any difference in execution speed since they are not part of the parsed code.
If you really want to optimize download or parse speed, the way to do that is to write your code in the most readable fashion possible for best maintainability and then use a minimizer for the deployed code and this is a standard practice by many web sites. This will give you the best of both worlds - maintainable, readable code and minimum deployed size.
A minimizer will remove all unnecessary spacing, shorten the names of variables, remove comments, collapse lines, etc... all designed to make the deployed code as small as possible without changing the run-time meaning of the code at all.
C++ is a compiled language. As such, only the compiler that the developer uses sees any extra spaces (same with comments). Those spaces are gone once the code has been compiled into native code which is what the end-user gets and runs. So, issues about spaces between elements in a line are simply not applicable at all for C++.
Javascript is an interpreted language. That means the source code is downloaded to the browser and the browser then parses the code at runtime into some opcode form that the interpreter can run. The spaces in Javascript will be part of the downloaded code (if you don't use a minimizer to remove them), but once the code is parsed, those extra spaces are not part of the run-time performance of the code. Thus, the spaces could have a small influence on the download time and perhaps an even smaller influence on the parse time (though I'm guessing unlikely to be measurable or meaningful). As I said above, the way to optimize this for Javascript is to use spaces to enhance readability in the source code and then run a minimizer over the code to generate a deployed version of the code to minimize the deployed size of the file. This preserves maximum readability and minimizes download size.
There is little (javascript) to no (c#, c++, Java) difference in performance. In the compiled languages in particular, the source code compiles to the exact same machine code.
Using spaces instead of tabs can be a good idea, but not because of performance. Rather, if you aren't careful, use of tabs can result in "tab rot", where there are tabs in some places and spaces in others, and the indentation of the source code depends on your tab settings, making it hard to read.

Does JSON.parse() use eval() internally? [duplicate]

This question already has answers here:
What is JSON.parse written in / Is it open source?
(4 answers)
Closed 9 years ago.
Does JSON.parse in modern browsers use eval() internally for evaluating and executing the dynamic code?
Because I have been looking through Douglas Crockford's JSON library. It also uses eval() when using parse() but after preprocessing prior to the actual evaluation. Such as:-
A wall against Unicode characters in the code.
A code shows malicious intent.
Do the modern browsers which supports JSON.parse natively perform this or they follow other protocols?
No, JSON.parse() doesn't Use eval()
This is by design, as eval() being able to execute any arbitrary JavaScript code you feed it, it could execute things you wouldn't want it to. So JSON.parse() does what it says on the tin: it actually parses the whole string and reconstructs and entire object tree.
JSON.parse is usually delegated to an internal function implemented with "native" code, where "native" means whatever is considered "native" in the context of your browser's javascript engine (could be compiled machine code, could be bytecode for a VM, etc...). I don't think there's any strong requirement on that.
Differences in the Implementations?
JSON (the notation) itself is codified by the RFC4627.
Regarding the implemetation of the JSON object and its methods, all modern browsers implementing should behave the same, as they should follow the same specifications for ECMAScript 5's JSON object. However, there's always the chance for potential defects. For instance, V8 originally contained this nasty bug.
Also, note that the implementation listed in comments above are for you to add JSON.parse() support to browsers that do not support it natively (also known as "these damn old browsers you sometimes need to support"). But it doesn't mean that it's necessarily how they implemented it.
For instance, for Google's V8 implementation used in Chrome, see json.js which invokes native code from json_parser.h.
It would be a very funny thing to do, if you think about it.
To understand why, see if this analogy helps: you're traveling with your boss to a country where you speak the language but she doesn't. Since you're fluent, you will serve two roles: as her assistant (doing tasks for her) as well as her translator (telling her what things mean).
So you have these two jobs, which are complementary. Your boss could tell you to do something--in any language you both understand (say, English)--as well as ask you to tell her what something says, like a sign or a document. She could even do both: hand you a set of instructions written in this other language and say, "This was given to me by someone I trust. Please do everything it says here."
In this analogy, reading signs or documents to your boss is like JSON.parse. Your boss handing you instructions and telling you to do everything they say is like eval.
If JavaScript engines used eval internally for JSON.parse, that would be analogous to your boss asking you what a document says, and you choosing to act out everything written in the document in order to explain it to her. Instead of just reading it.

why {key:value}["key"] doesn't work?

1:{key:value}["key"]
2:({key:value})["key"]
I'm wondering how the JS interpreter works on the above codes, and why 1 doesn't work and why 2 works?
I assume you are asking the question because you saw this effect in a JavaScript REPL (shell). You are using a JavaScript shell which assumes the leading "{" begins a block statement instead of an object literal.
For example, if you use the JavaScript interpreter that comes with the Chrome browser, you see the following:
> {key:"value"}["key"]
["key"]
Here, Chrome saw what you entered as a block statement, followed by the expression that was an array of one element, the string "key". So it responded with the result of that expression, namely the array ["key"]
But not all shells work this way. If you use the interpreter with node.js, then #1 will work for you!
$ node
> {key:"value"}["key"]
'value'
>
In interpreters like Chrome, you have to use parentheses to tell it that you want the first part to be an object literal. (This technique, by the way, is guaranteed to work in all shells, including node's).
EDIT
As pointed out in one of the comments, if you use that construct in an expression context anywhere in an actual script, it will produce "value". It's the use in the shell that looks confusing.
This fact was actually exploited in the famous WAT video by Gary Bernhardt.

Get exact syntax of javascript base functions [duplicate]

This question already has answers here:
Where can I find javascript native functions source code? [duplicate]
(3 answers)
Javascript native sort method code
(3 answers)
Closed 8 years ago.
Is there a way to know how test (for regex) or cos (for math) or substring (for string) or splice (for array) have been coded in the exact syntax either by a way in Javascript (like alert(function)) or by seeking in the files that come with Firefox?
Well, the source code of javascript likely isn't written in javascript itself, so you would be unable to just print it to the browser console or alert.
You can browse the source code of google's V8 engine, and see if it helps you ;)
http://code.google.com/p/v8/
These functions are actually implemented differently by browsers in one of the OS native languages.
So these algorithms are written in c, c++, c#, java etc. but not in JavaScript.

Why use semicolon? [duplicate]

This question already has answers here:
Do you recommend using semicolons after every statement in JavaScript?
(11 answers)
Closed 9 years ago.
Are there any reasons, apart from subjective visual perception and cases where you have multiple statements on the same line, to use semicolon at the end of statements in JavaScript?
It looks like that there's plenty of evidence suggesting that use of semicolons is highly optional and is required in only few of the specific cases.
Because JavaScript does nasty things to you when it guesses where to put semicolons. It's better to be explicit and let the interpreter know exactly what you meant than it is to let the idiot box guess on your behalf.
References:
http://www.webmasterworld.com/forum91/521.htm
http://www.howtocreate.co.uk/tutorials/javascript/semicolons
http://robertnyman.com/2008/10/16/beware-of-javascript-semicolon-insertion/
...and a cast of thousands.
It looks like there are very few reasons, or, actually, edge cases, when one would want to use semicolons.
http://aresemicolonsnecessaryinjavascript.com/ <- this is down now, use
https://github.com/aresemicolonsnecessaryinjavascript/aresemicolonsnecessaryinjavascript.github.com
If you asked, because you come from a Python background: The difference is:
in Python you shouldn't terminate lines with anything, but are allowed to use the semicolon, if you must
in JavaScript you should terminate the lines with a semicolon, but are allowed (PDF, page 26, point 7.9) to omit it, if it's unambiguous
Because
Debugging the subtle bugs that occur when you don't is a waste of time you could be spending doing something cool
It makes it clearer to someone maintaining the code later what you intend
Not all code maintainers understand the rules for automatic insertion well enough to maintain code with them left out
Leaving them out relies on all tools that process JavaScript code in your toolchain getting the rules exactly right (for instance, some minifiers/packers/compressors don't, including Crockford's jsmin, which will break code that relies on ASI in some places)
As Douglas Crockford suggests -
Put a ; (semicolon) at the end of every simple statement. Note that an assignment statement which is assigning a function literal or object literal is still an assignment statement and must end with a semicolon.

Categories

Resources