JavaScript object literals syntax error
The NodeJS REPL evaluates code as an expression, by wrapping the code in parentheses, causing {"hello":1}
to be ({"hello":1})
which is parsed successfully as an object literal.
Usually and elsewhere (in Chrome/Firefox's console), the curly braces are parsed as the delimiters of a block, like:
/*imagine if (true) */ {
"hello": 1 // <-- What's this syntax? It's meaningless.
}
{hello:1}
parses successfully, because hello
in this context has the meaning of a label:/*imagine if (true) */ {
hello: 1;
} // ^-- Automatic Semicolon Insertion
Why does this object literal cause a syntax error?
JavaScript object literals syntax error
Here is a similar answer (assuming you used the REPL). Basically Node will wrap the code in parentheses, thus parsing it successfully as an object literal.
{"hello":1} to be ({"hello":1})
javascript object literal dynamic key SyntaxError
You need to wrap your {}
in ()
, or it will be interpreted as the body of a function:
['a', 'b'].map((x) => ({[x]: x }))
SyntaxError: Unexpected token ... in object literal
This code is using object spread properties, which are not a part of ECMAScript 6. They are currently an ECMAScript proposal at stage 3. To use them, you have to configure Babel to use stage-3
preset.
I can't write object literal notation in Dev Console?
{ /* ... */ }
is a block statement.
If you want it to be parsed as an object initialiser, you must use it in a place where an expression is expected.
Some examples:
{} + ''; // `0`, parsed as block
'' + {}; // `"[object Object]"`, parsed as expression
{} * 1; // Error, parsed as block
1 * {}; // `NaN`, parsed as expression
A way to parse it as an expression and get the resulting object as the result is enclosing it inside parentheses:({ /* ... */ })
Why does an object literal get ignored in a statement in JavaScript?
Inside a block, an expression consisting of a label followed by a number literal is valid.I would expect that if it was interpreted as a block, it would result in a syntax error. Why is this the case?
It doesn't need to look ahead. It is a block because of what is on the left hand side of thebut this does not answer how this is not a syntax error unless it is doing a lookahead to determine if it's an object literal or a block
{
(i.e. nothing). Javascript Object Syntax Error when declaring function
You're missing a comma in line 8, separating taxi.mileage
and taxi.drive
. You've also spelled 'function' incorrectly on line 9.
Fixing those, it seems to work fine:
var taxi = { make: "Toyota", model: "Taxi", year: 1955, colour: "yellow", passengers: 4, convertible: false, mileage: 281341, drive: function() { alert("Voom Voom"); }};
function prequal(car) { if (car.mileage > 10000 || car.year > 1960) { return false; } return true;}
var worthALook = prequal(taxi);
if (worthALook) { console.log("Check it out! " + taxi.make + " " + taxi.model);}else { console.log("Not worth! " + taxi.make + " " + taxi.model); }
taxi.drive();
JavaScript string literal in object literal syntax error
You have an unclosed string literal. JavaScript strings are not multi line by default.
var modalcontent = {
description1 : '<div id = "description"><div class = "tbc"> '+
'<label class = "tbc" for = "tbc">Description</label>'+
'</div>'+
'<div class = "tbc">'+
'<input type = "text" class = "tbc" name = "description" id = "tbc" placeholder = "Enter description">'+
'</div>'+
'</div>'+
'<!--end description div-->'
}
(fiddle)Alternatively, you can create multi line string by using the \
character, those only work in newer implementations. See this related question or the language specification.
Note: It's usually not the best idea to store HTML in strings, it makes it harder to debug and work with. You can usually use templates. It's not that there are no good use cases, it's just rarely the case.
Uncaught SyntaxError: Unexpected identifier in Object Literal
This is the correct syntax to assign a function to a property:
var myObject = {
foo: 'bar',
talk: function thisNameIsOptional() {
console.log('Hello world')
}
};
Also you can do it this way:var myObject = {
foo: 'bar',
talk: talk
};
function talk() {
console.log('Hello world')
}
As you see the syntax is always the same:{
literal1: (object or function),
literal2: (object or function)
... and so on ...
}
The second one on your question is wrong.If this is not enough, you have a complete guide for variables and literals on MDN.
Related Topics
React Jsx: Selecting "Selected" on Selected <Select> Option
Understanding JavaScript Promise Object
Convert CSV Data into JSON Format Using JavaScript
How Do Cors and Access-Control-Allow-Headers Work
How to Send Email by Using JavaScript or Jquery
Adding New Data to Firebase Users
How to Use Local Storage in Angular
Dynamic Require in Requirejs, Getting "Module Name Has Not Been Loaded Yet for Context" Error
Does Use of Anonymous Functions Affect Performance
JavaScript Es6 Typeerror: Class Constructor Client Cannot Be Invoked Without 'New'
Initializing Select with Angularjs and Ng-Repeat
How to Send Authorization Header with Axios
Get Visitors Language & Country Code with JavaScript (Client-Side)
Why Do I Need to Copy an Array to Use a Method on It
Check If an Object Implements an Interface at Runtime with Typescript
Using Fetch API to Access JSON
Why Does ('0' ? 'A':'B') Behave Different Than ('0' == True ? 'A':'B')