Little Help with JavaScript

V

vaib

FWIW, I concur with Luuk. Granted, it may be a poor resource for those
asdvanced anough to already understand the difference between methods,
functions, properties, etc.

But is it a good "Javascript for Dummies" site. (It worked for me.)

Sir can we just discuss the problem instead of evaluating w3schools.
 
V

vaib

Well, this sample doesn't prove the harm of semicolons omission
because if-else *statement" will be indeed terminated by a semicolon
in the tokenizer while semicolon insertion between if-else statement
*expressions* is an error the tokenizer would not do.

This group had its "aggressive purism" period including the immediate
decapitation for any semicolon missing :) At that period some samples
were found where missing explicit semicolon would lead to a unexpected
result. The cases were not numerous at all and rather... special...
yet there are of them if one search the archives.

can we just discuss the problem instead of starting a sub thread on
semicolon usage ?
 
T

Thomas 'PointedEars' Lahn

vaib said:
can we just discuss the problem instead of starting a sub thread on
semicolon usage ?

Can you just get in informed where you are posting to, and accept that
Usenet is a support Web forum but a text-based electronic medium of
discussion? You do not own the thread.


PointedEars
 
T

Thomas 'PointedEars' Lahn

vaib said:
can we just discuss the problem instead of starting a sub thread on
semicolon usage ?

Can you just get in informed where you are posting to, and accept that
Usenet is not a support Web forum but a text-based electronic medium of
discussion? You do not own the thread.


PointedEars
 
V

VK

vaib said:
can we just discuss the problem instead of starting a sub thread on
semicolon usage ?

Are you still not answered? I did not read all posts in here as the
problem itself was not interesting to me. Sorry then, so OP was: "A
page where two DIVs are placed side by side and there's a button
below. On the click of the button the DIVs should exchange their
positions (of course, with everything in them also being exchanged). I
have to make it resolution free." As much as the task is described
that can be one of solutions:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<title>Demo</title>
<style type="text/css">
DIV#A {
position: absolute;
left: 4em; top: 4em;
width: 10em; height: 10em;
background-color: #FFFF00;
}
DIV#B {
position: absolute;
left: 18em; top: 4em;
width: 10em; height: 10em;
background-color: #00FF00;
}
P#menu {
position: absolute;
left: 4em; top: 18em;
}
</style>
<script type="text/javascript">

function swap() {
if (swap.originalPos) {
$('A').style.left = '18em';
$('B').style.left = '4em';
swap.originalPos = false;
}
else {
$('A').style.left = '4em';
$('B').style.left = '18em';
swap.originalPos = true;
}
}
swap.originalPos = true;

function $(id) {
return document.getElementById(id);
}
</script>
</head>
<body>
<div id="A"><p>A</p></div>
<div id="B"><p>B</p></div>
<p id="menu"><button type="button" onclick="swap();">swap</button></
p></body>
</html>
 
T

Thomas 'PointedEars' Lahn

VK said:
vaib said:
can we just discuss the problem instead of starting a sub thread on
semicolon usage ?

Are you still not answered? I did not read all posts in here as the
problem itself was not interesting to me. Sorry then, so OP was: [...]

We all have downloaded and read the OP already, thank you very much.
As much as the task is described that can be one of solutions:

<!DOCTYPE html>

Will you ever learn?
[...]
function swap() {
if (swap.originalPos) {
$('A').style.left = '18em';
$('B').style.left = '4em';
swap.originalPos = false;
}
else {
$('A').style.left = '4em';
$('B').style.left = '18em';
swap.originalPos = true;
}
}

Hopelessly inefficient, hard-to-maintain and hard-to-debug, idiotic coding;
so very typical for you.

function swap()
{
var a = document.getElementById("A");
var b = document.getElementById("B");
if (a && b)
{
var aPos = a.style.left;
a.style.left = b.style.left;
b.style.left = aPos;
}
else
{
/* DEBUG */
}
}

However, this would require either inline styles or computed values, so
I would rather swap CSS class names instead, e.g.:

function swap()
{
var a = document.getElementById("A");
var b = document.getElementById("B");
if (a && b)
{
var aClassName = a.className;
a.className = b.className;
b.className = aClassName;
}
else
{
/* DEBUG */
}
}
[...]
<p id="menu"><button type="button" onclick="swap();">swap</button></
p></body>

Unnecessarily complicated and incompatible. For a button with plain text
caption, one simply uses <input type="button" value="Swap" ...>. And that
button should be generated with scripting in any case.


PointedEars
 
J

John G Harris

Well, this sample doesn't prove the harm of semicolons omission

Not surprising as this sub-thread is about semicolon insertion, not
semicolon omission.

because if-else *statement" will be indeed terminated by a semicolon
in the tokenizer while semicolon insertion between if-else statement
*expressions* is an error the tokenizer would not do.
<snip>

An if or if-else statement is *never* terminated by a semicolon. It's
terminated by a nested, internal, statement. Also, the only expression
is the if-condition.

If you don't understand that then you don't understand the language. Nor
do you understand Algol, Pascal, Simula, C, C++, Java, and C# which all
have the same rules for if statements.

John
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]
8924D9443D28E23ED5CD>, Sun, 18 Oct 2009 15:08:15, John G Harris
<snip>

As you've not been able to find the problem on your own I suppose I'd
better give you a hint. Consider this piece of code :

var a = 2;
var b, c;
if (a == 2) switch (a) { case 2: b = 5; break; } ; else b = 6;
alert(b);

Convince yourself that it contains a syntax error.

IE, Firefox and Opera agree that does; that's convincing enough.
Decide exactly what
the problem is. Now review the following sentence in your web page :

"Then every statement will be terminated by a semicolon."

But I was writing about valid JavaScript, not JavaScript with a syntax
error.

Obviously adding more end-of-lines semicolons will not help.

That code becomes valid by removing the semicolon before "else".

Aesthetically, because a switch statement is complicated, I would
enclose it in {} or newlines or both, but that is only visually helpful.

Try reading my page more carefully. Then you might also see such as the
error in the previous section "White Space".
 
V

VK

And repeating again - it does not, and that was the reason of my
comment.
An if or if-else statement is *never* terminated by a semicolon. It's
terminated by a nested, internal, statement. Also, the only expression
is the if-condition.

If you don't understand that then you don't understand the language. Nor
do you understand Algol, Pascal, Simula, C, C++, Java, and C# which all
have the same rules for if statements.

I do "speak" Perl, JavaScript, AutoLISP, VBA BASIC, Java (applet level
mainly). I still do not understand the point you were trying to make
to Dr.Stockton and now making to me. First of all, JavaScript syntax
does require semicolons at all needed places. The other thing is that
the tokenizer does automatically insert missing semicolons on the fly
so the parser gets syntactically correct instructions even if the
programmer was too lazy to type them in. And the main rule of the auto-
correction is that the result always has to be grammatical. This way
it will not insert ; after a=1 here
if (cond)
a=1
else
a=2
not because "if-else statement is *never* terminated by a semicolon.
It's> terminated by a nested, internal, statement". It will not
insert ; because the stay alone instruction
else a=2;
is not grammatical. For the same grammatical reason the tokenizer will
not have troubles with say
{property: f()}
is this labeled statement in a block? is this object literal? of
course an object literal, otherwise it is not grammatical. I don't
know if it is so in "Algol, Pascal, Simula, C, C++, Java, and C#" but
in JavaScript it is this way and no other way around. You may find
interesting as well "Quibbling Over Semicolons" by Eric Lippert:
http://blogs.msdn.com/ericlippert/archive/2004/02/02/quibbling-over-semicolons.aspx
 
V

VK

Will you ever learn?

Will you?
http://groups.google.com/group/comp.lang.javascript/msg/f4d3681cd2960ea5
Very slowly one more time: I am posting HTML5 valid code. If you don't
like HTML5 it is your problem. If you declare that W3C Validator green-
sign validated code is still not valid until Thomas 'PointedEars' Lahn
admitted it as valid then it is your problem also (and a big one I
would say).
Hopelessly inefficient, hard-to-maintain and hard-to-debug, idiotic coding;
so very typical for you.
[...]

etc. void blah-blah-blah snipped

I need to sort out all chars in range \u0100 - \u2000 as a part of a
complex case-insensitive regexp. Is it doable or do I need to split
the regexp on two:
[\u0100 - \u2000]
then case-insensitive match part
? If you have time in your hand you may answer it in the "i madness"
thread.
 
S

SAM

Le 10/18/09 5:00 PM, vaib a écrit :
ya thats when you use the second replaceChild.

Of course as at this time it no more exists
so you have to move (replace with) clones of the divs.
Clones must both exist before replacing.

did you read and try the example of code I gave ?
(normaly working with any div, no importance if divs to xchange are in
another div or not)
 
V

VK

Richard said:
On the contrary, inserting a semi-colon in that location is required.
The statement following the closing parenthesis of the - if - expression
is an ExpressionStatement and ExpressionStatements are semicolon
terminated (ECMA 262 3rd Ed. Section 12.4) (in contrast to
SwitchStatements, which are not).

You know my highly skeptical attitude to the Books Of ECMA wording and
statements ("statements" in the common human language use sense). Yet
if we decided to quote the Books then let's us quote them right.
Chapter 12 Song 4 :) has nothing to do with the issue because in
if (cond) a=1
a=1 is not an ExpressionStatement. I am leaving on you the necessary
reductio ad absurdum steps with the starting rules:
1) "an ExpressionStatement cannot start with an opening curly
brace" (Books of ECMA, Chapter 12, Song 4)
2) if (cond) {a=1} is a grammatically correct valid language
instruction

The relevant to the topic part would be Chapter 12, Song 5 ("The if
Statement") but it is so badly written that not really usable in the
practical sense yet still good for meditations :)

The correct explanation is that if-else statement has implied {block}
part after each part of the statement. And besides auto-insertion of
semicolons the tokenizer has other error-correction mechanics in it,
and among it - an auto block wrapping for *simple* if-else cases.
Other words when meeting
"if (cond) a=1 LINE_TERMINATOR else a=0 LINE_TERMINATOR"
tokenizer brings it to the form
if (cond) {a=1;} else {a=0;}"
and this goes to the parser. You seem to relay on Firefox back-to-
source reverse tools such as toSource: which is a very dangerous thing
as it is merely a debugging tool left by Gecko developers - and it
outputs what they wanted for their internal code tracking needs. Yet
one may try this as it is pretty close to what the actual bytecode
does:

function demo() {
if (false) window.alert(arguments.callee.toSource()+'\n1');
else window.alert(arguments.callee.toSource()+'\n2');
}
demo();

I do understand the excitement of purists around if-else case as it
produces so much wanted "missing ; before statement" error message to
show to everyone. As a side note I want to state that personally I
never rely on error correction mechanics and I always use explicit
block syntax even for single statement:
if (cond) {a=1;} else {a=0;}
and I strongly encourage anyone to do the same. Yet let do not mix the
actual look-ahead mechanics with badly written descriptions of this
mechanics and some misleading error messages.
IF (true) a=1
else a=0

true else false

etc. are still "missing ; before statement" but it proves nothing (nor
does it mean a lot)
The statement:-

if (cond) a=1; else  a=2;

- is grammatical

As it was explained earlier it is not, because there is not stay alone
operator or expression "else", only "else" as a part of if-else block.
But the semicolon helps the tokenizer look-ahead mechanics to decrypt
the possible author's intentions so it produces grammatically correct
if (cond) {a=1;} else {a=2;}
In isolation it is a Block statement, containing a labelled statement,
labelling a function call that represents and ExpressionStatement. And
an automatic semicolon insertion happens here, making the point. Load
this into Friefox 3:-

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title></title>
  </head>
  <body>
<pre>
<script type="text/javascript">
function x(){
  {property: f()}

}

document.write(x.toString());
</script>
</pre>
  </body>
</html>

- and observe that the output is:-

function x() {
property:
    f();

}

- and see not only the inserted semicolon but also that he redundant
block statement has been optimised away. If the code had been (or could
have been) interpreted as an object literal then the output would have
reflected that.

Sorry, but it is a complete nonsense. Are you implying that any {prop:
f()} is interpreted as
label:
function call
and 99.99% of existing code is in rewrite emergency? You cannot be
serious.

function f() {
return 'bar';
}
window.alert({foo:f()}.foo); // 'bar'
 
R

Richard Cornford

Richard Cornford wrote:

Didn't you want to quote those statements of yours that I was replying
to? I cannot say I am suppressed, but it is not like you to be that
embarrassed by being that wrong. Editing without marking your edits is
disingenuous regardless of your reasons for doing it.
You know my highly skeptical attitude to the Books Of ECMA
wording and statements ("statements" in the common human
language use sense).

I know that you have difficulty understanding the spec, and would
rather construct an elaborate fiction of your own rather than
attempting to understand it.
Yet if we decided to quote the Books then let's us quote them
right. Chapter 12 Song 4 :) has nothing to do with the issue
because in
if (cond) a=1
a=1 is not an ExpressionStatement.

The - a=1 - in if (cond) a=1 - absolutely is an ExpressionStatement.
I am leaving on you the necessary
reductio ad absurdum steps with the starting rules:
1) "an ExpressionStatement cannot start with an opening curly
brace" (Books of ECMA, Chapter 12, Song 4)

Fine, - a=1 - does not start with either an opening curly brace or the
- function - keyword, so it is not precluded from being an
ExpressionStatement by that.
2) if (cond) {a=1} is a grammatically correct valid language
instruction

Yes, in that case the closing parenthesis after the - if - condition
expression is followed by a Block expression (ECMA 262 3rd Ed. Section
12.1). The StatmentList inside that Block statement is a single
ExpressionStatement consisting of - a=1- but that has no relevance for
an - if - statement that does not include any Block statements.
The relevant to the topic part would be Chapter 12, Song 5 ("The
if Statement") but it is so badly written that not really usable
in the practical sense yet still good for meditations :)

Section 12.5 is entirely understandable. The two productions for - if
- are:-

if ( Expression ) Statement else Statement

- and:-

if ( Expression ) Statement

- which means that the conditional expression can be anything that
qualifies as an Expression, but it must be parenthesised, and you can
substitute anything that qualifies as a Statement where the words
"Statement" appear. Which could be a Block statement, a
SwitchStatement or an ExpressionStatement, or any of the others
available in the language, including another IfStatement.
The correct explanation

Here comes the 'made up off the top of your head' fiction.
is that if-else statement has implied {block}
part after each part of the statement.

Well, no.
And besides auto-insertion of
semicolons the tokenizer has other error-correction mechanics
in it,

There are no other error correcting mechanisms specified, and while
syntax extensions are possible they are not needed to explain anything
that is occurring here.
and among it - an auto block wrapping

"Auto block wrapping" being your fiction of the day.
for *simple* if-else cases.
Other words when meeting
"if (cond) a=1 LINE_TERMINATOR else a=0 LINE_TERMINATOR"
tokenizer brings it to the form
if (cond) {a=1;} else {a=0;}"

Then why is:-

if (cond) a=1 else a=0

-(without line terminators) - a syntax error when:-

if (cond) { a=1 } else { a=0}

- is not? If some sort of implied Block insertion was going on why
does it not happen in the first case. I suppose your next fabrication
would be the suggestion that this can only happen if the - if -
statement is spread across multiple lines, but going back to John G
Harris' original example, why is:-

if (a == 2)
switch (a) { case 2: b = 5; break; } ;
else
b = 6;

- a syntax error when:-

if (a == 2) {
switch (a) { case 2: b = 5; break; } ;
} else {
b = 6;
}

- is not?

This "auto block wrapping" does not appear to be doing a very good job
of explaining what is going on here. Unsurprising as you made it up on
the spot.
and this goes to the parser. You seem to relay on Firefox
back-to-source reverse tools such as toSource:

No, I just observed that they do show the automatically inserted
semicolons, which makes them useful if debating when and were
semicolons are automatically inserted.
which is a very dangerous thing as it is merely a debugging
tool left by Gecko developers - and it outputs what they
wanted for their internal code tracking needs.

That does not stop what it outputs from corresponding with the
specified behaviour.
Yet one may try this as it is pretty close to what the actual
bytecode does:

function demo() {
if (false) window.alert(arguments.callee.toSource()+'\n1');
else window.alert(arguments.callee.toSource()+'\n2');}

demo();

To what end? All that shows is that the complier is smart enough to
recognise that - if (false ) - is the condition there is no point in
having anything but the contents of the - else - branch and the other
code is unreachable. A reasonable optimisation.
I do understand the excitement of purists around if-else case
as it produces so much wanted "missing ; before statement" error
message to show to everyone.

You are becoming incoherent again.
As a side note I want to state that personally I
never rely on error correction mechanics and I always use explicit
block syntax even for single statement:
if (cond) {a=1;} else {a=0;}
and I strongly encourage anyone to do the same. Yet let do not
mix the actual look-ahead mechanics with badly written
descriptions of this mechanics and some misleading error messages.

All we have seen here is the application of the rules for automatic
semicolon insertion, as specified. Yet you have dreamt up "error
correction mechanics", " look-ahead mechanics" and "misleading error
messages" as part of your bullshit explanation.
IF (true) a=1
else a=0

Where the missing semicolon is the one that should terminate the
ExpressionStatement - IF ( true) -, which is a function call.
true else false

Where the missing semicolon is the one that should terminate the
ExpressionStatement - true -, which is worthless but legal.
etc. are still "missing ; before statement" but it proves nothing
(nor does it mean a lot)

It means that your code contains syntax errors, and probably points
you to where those errors are located.
As it was explained earlier it is not,

It is. That code fully stratifies the ECMA 262 rules. The ability to
load that code into any javascript environment without error or
complaint pretty much guarantees that it is free of syntax errors.
because there is not stay alone operator or expression "else",
only "else" as a part of if-else block.

You asserted that in:-

if (cond )
a=1
else
a=2

- the parser (though you actually incorrectly attributed the behaviour
to the tokenise (see the opening sentence of Section 7.9.1)) could not
add a semicolon after the - a=1 -. However, as I said, no only can a
semicolon be automatically added, but it must be automatically added.
That addition corrects the first Statement in;-

if ( Expression ) Statement else Statement

- so it really has nothing to do with - else - being part of the
structure that contains that Statement.
But the semicolon helps the tokenizer look-ahead mechanics to decrypt
the possible author's intentions

"Look-ahead mechanics", "decrypt", "possible author's intentions". I
would suggest that you couldn't make this stuff up, except that you
clearly have.
so it produces grammatically correct

if (cond) {a=1;} else {a=2;}

Why would it do that when:-

if (cond )
a=1;
else
a=2;

- is all that is necessary, and achievable only by the applying of the
automatic semi-colon insertion rules.

Sorry, but it is a complete nonsense.

How could you possibly tell?
Are you implying that any {prop:
f()} is interpreted as
label:
function call

No, I am saying that in isolation such a construct is interpreted in
exactly that way. You mentioned yourself earlier that an Expression
Statement cannot start with an opening curly brace. That is to prevent
object literals being ambiguous with Block statements, so in a context
where statements are expected (which will always be the case when the
construct is in isolation) the opening curly brace can only be
interpreted as starting a Block statement.

When you asserted that - {property: f()} - would be interpreted as an
object literal you provided no context that would force such an
interpretation, and the 'default' interpretation certainly is not as
an object literal.
and 99.99% of existing code is in rewrite emergency? You cannot
be serious.

I can be serious, but it tends to go right over your head when I am.
function f() {
return 'bar';}

window.alert({foo:f()}.foo); // 'bar'

The items in an ArgumentsList are AssignmentExpressions (and it makes
no sense to try to use a Statement as an argument anyway), so in that
context - {foo:f()} - has to be interpreted as an object literal. When
you were asserting that - {property: f()} - had to interpreted as an
object literal you provided no context, but instead asserted that the
alternative, Block containing label statement, was not "grammatical".
While in reality, without context, the interpretation is going to be
as a Block, and the contract is completely legal under that
interpretation.

Richard.
 
V

VK

Richard Cornford wrote:

[...]
When you asserted that - {property: f()} - would be interpreted as an
object literal you provided no context that would force such an
interpretation, and the 'default' interpretation certainly is not as
an object literal.

And that is extremely interesting.

First of all you are completely right, a simple test shows that
{ key1 : "value1"}
is interpreted as a block of statements with a single labeled
statement in it, and not as an stay-alone object initialization.
Respectively
{ "key1" : "value1"}
leads to syntax error because label literal cannot be quoted.

That implies that JSON is not exactly "based on a subset of the
JavaScript Programming Language, Standard ECMA-262 3rd Edition -
December 1999" as http://json.org states because its object data
structures are not JavaScript syntax compatible per se as their key
values have to be quotes by specs. They become JavaScript syntax
compatible only if used in the right side of assignments. IMHO that
should be mentioned somewhere on the page.
 
V

VK

VK said:
That implies that JSON is not exactly "based on a subset of the
JavaScript Programming Language, Standard ECMA-262 3rd Edition -
December 1999" ashttp://json.orgstates because its object data
structures are not JavaScript syntax compatible per se as their key
values have to be quotes by specs. They become JavaScript syntax
compatible only if used in the right side of assignments. IMHO that
should be mentioned somewhere on the page.

I just narrowed and fixed a set of highly spurious syntax errors all
caused by this context-dependent language rules violation in JSON in
stay-alone data files. Can I buy you a beer or something?! :)
 
R

Richard Cornford

Richard Cornford wrote:
[...]
When you asserted that - {property: f()} - would be interpreted
as an object literal you provided no context that would force
such an interpretation, and the 'default' interpretation
certainly is not as an object literal.

And that is extremely interesting.

That probably depends on which side of understanding the language's
syntax rules you are observing from.
First of all you are completely right,

And you have been guilty of making things up off the top of your head
again.
a simple test shows that

That would be a test like the one I posted earlier, and to which you
responded "Sorry, but it is a complete nonsense".
{ key1 : "value1"}
is interpreted as a block of statements with a single labeled
statement in it, and not as an stay-alone object initialization.
Respectively
{ "key1" : "value1"}
leads to syntax error because label literal cannot be quoted.

Or more precisely because the label in a LabelledStatement is an
Identifier and a string literal is not an Identifier.
That implies that JSON is not exactly "based on a subset of the
JavaScript Programming Language, Standard ECMA-262 3rd Edition -
December 1999"

No it doesn't. It really has nothing to do with JSON.
as http://json.orgstates because its object data
structures are not JavaScript syntax compatible

Yes they are.
per se as their key
values have to be quotes by specs.

Using string literals to provide the property names in an object
literal is valid javascript syntax.
They become JavaScript syntax
compatible only if used in the right side of assignments.

JSON is subset of javascript object literal notation regardless. JSON
is a text format for data exchange, so there is no real sense in "the
right hand side of assignments" where it is concerned. If you take a
JSON text and insert it into javascript source code then you would
only get away with that where its particular subset is applicable.
Object literal source text will be interpreted as an object literal in
all locations where an Expression is allowed, so, for example, as an
argument to a function call.

Data in JSON format is usually acquired in the form of a string value,
and so is independent of the source text of the code that employs it.
IMHO that
should be mentioned somewhere on the page.

Your opinions remain utterly worthless.

Richard.
 
V

VK

Richard said:
Yes they are.

Now you are definitely kidding.

{"key1":"value1"}
structure is a valid JSON object data but it is not JavaScript syntax
compatible for the above spelled reasons and leads to "invalid label"
syntax error. By creating the assignment context like
var obj = {"key1":"value1"}
we are masking this potential error and successfully instantiating obj
over assignment. If - as many others - we are using JavaScript allowed
shortcut without quotes around the key name then we also masking this
ticking bomb:
{"key1":"value1"}

And
var obj = eval( '{key1:"value1"}' );
window.alert(typeof obj); // string
?

And
var obj = eval( '{"key1":"value1"}' );
// syntax error "invalid label"
?

And
var obj = eval('{"key1":"value1", "key2" : "value2"}');
// syntax error "invalid label"
?

And so on? I did over last hours more than planned for the week -
grace to you and thank you again.
 
R

Richard Cornford

Richard Cornford wrote:

Why is it that cannot even manage to do the simplest things correctly?
The attributions belong at the top, and the number of chevrons that
precede them should be precisely one less than the number of chevrons
that mark the quotes that each attribution refers to.
Now you are definitely kidding.

No I am not. There are plenty of constructs that "syntax
compatible" (as you put it) that cannot just be dropped into source
code at whim with any expectation that the outcome will not be a
syntax error. For example, we have seen that - key1: - is fine for
labelling a statement, and to declare a property name in an object
literal but put it in an arguments list and you have a syntax error.
However, - key1: - is still a subset of javascript syntax regardless
of that.
{"key1":"value1"}
structure is a valid JSON object data but it is not JavaScript
syntax compatible for the above spelled reasons

It is fine as javascript source code, it is just the source code for
an Expression not a Statement.
and leads to "invalid label"
syntax error.

Only if you do not use it in a context appropriate for an Expression.
By creating the assignment context like
var obj = {"key1":"value1"}
we are masking this potential error

There is no potential error, particularly as asserting an object
literal is as worthless as writing:-

true;
and successfully instantiating obj
over assignment. If - as many others - we are using JavaScript
allowed shortcut without quotes around the key name then we also
masking this ticking bomb:
{"key1":"value1"}

An expression statement taking the form:-

({ key1 : "value"});

- is utterly worthless as the resulting object literal is then
inaccessible. If you are already writing worthless code then having:-

{ key1 : "value"}

- interpreted as a block statement containing a labelled statement is
not going to make anything any worse.
And
var obj = eval( '{key1:"value1"}' );
window.alert(typeof obj); // string
?

And
var obj = eval( '{"key1":"value1"}' );
// syntax error "invalid label"
?

And
var obj = eval('{"key1":"value1", "key2" : "value2"}');
// syntax error "invalid label"
?

But the - eval - function evaluates its string arguments as javascript
Programs, and the two structures that can make up a Program as
Statements and FunctionDeclarations. Your string arguments are clearly
not FunctionDeclarations so it should not be surprising if they get
interpreted as a Statement. And as has already been seen, an initial
opening curly brace in a Statement context can only be the beginning
of a Block statement. Whatever follows the brace can then only be
acceptable content for a Block statement or a syntax error, either way
it is never going to be an object literal as the only form of
statement that can consist of an Expression is an ExpressionStatement
and they are forbidden from starting with an opening brace.

Of course the 'solution' to the eval-ing JSON strings issues is a well
known as it is obvious (at least to anyone who understands the
language). You explicitly parenthesise the JSON expression and then
the result can be an ExpressionStatement because it no longer starts
with an opening brace (and that is never ambiguous with a Block as
statements are not allowed (directly, as they may still appear in the
bodies of contained function expressions) inside parenthesise). So:-

var obj = eval( '(' + JSON_String + ')' );
And so on? I did over last hours more than planned for the
week - grace to you and thank you again.

It remains pretty hard to believe that anyone is fool enough to employ
you to write computer software. The amount of time you must waste as a
result of taking the things in your head seriously is unimaginable.

Richard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top