Javascript resulting in SyntaxError: Unexpected identifier - javascript

I am learning Javascript on Codecademy, and after entering in my code to make a short contact list, it returns an error message of:
SyntaxError: Unexpected identifier
Here is my code:
var friends = {
var bill: {
firstName: "Bill",
lastName: "Gates",
number: "1800 4 charity",
};
var steve: {
firstName: "Steve",
lastName: "Jobs",
number: "1800 I have lots of jobs",
};
};
Any help is greatly appreciated thanks :)

You don't need var if you are in an object. Also be sure to get rid of trailing commas.
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "1800 4 charity"
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "1800 I have lots of jobs"
}
};
When dealing with JSON remember you are just creating lists of names and values.
The format is
var object = {
nameOfProperty: value,
nameOfAnotherProperty: value2
};
Remember you only need commas between values not at the end of the list and no semicolons within the object (because then JS thinks you're missing the rest!).
The tricky part is then objects within Objects but as you're exploring, using an object as a value is perfectly legal. So start with the innermost objects and work your way out and you shoudl be fine.

Related

Why getting "Destructuring expressions can only have identifier references" when trying to destruct an object?

I have the following object:
const john = {
family: [
{ firstName: 'david', secondName: 'jana' },
{ firstName: 'eyal', secondName: 'shani ' },
],
};
I want to get 'david' string in one operation. So i tried the following code:
const { family:[0]{firstName}}} = john;
But i'm getting the error :
"Destructuring expressions can only have identifier references"
Can someone tell me in simple words (cause i'm new in the language) what i'm doing wrong?
To extract a deeply nested value with destructuring, the syntax is nearly identical to when declaring an object with those properties. family:[0] isn't valid syntax - instead, you need to surround the contents of family in array delimiters:
const john = {
family: [{
firstName: 'david',
secondName: 'jana'
},
{
firstName: 'eyal',
secondName: 'shani '
},
],
};
const { family:[{firstName}]} = john;
console.log(firstName);
But I'd highly recommend against using nested destructuring like this. It's so hard to write and read and understand. Better to use plain dot notation at least for the outer accesses, eg
const john = {
family: [{
firstName: 'david',
secondName: 'jana'
},
{
firstName: 'eyal',
secondName: 'shani '
},
],
};
const { firstName } = john.family[0];
console.log(firstName);

Javascript Property with three dots (...)

I have a problem with code I am supposed to work with. I found a syntax I am not familiar with and I have trouble googling the documentation:
export const Something = class Something {
constructor(someObject = {}) {
this.someObject = {...Something.someObjectDefaultAsStaticMethod,...someThing};
};
// The rest of the class
};
I have problems understanding what the three dots (...) in front of the parameter do. And "dots in parameter javascript" is a bad search term. Can someone help me, maybe tell me what this syntax is actually called or just directly link me to documentation?
That is not ES6 but has only been added in ECMAScript 2018.
It is called "Object Rest/Spread Properties" and is part of the Spread Syntax.
... (three dots in Javascript) is called the Spread Syntax or Spread Operator. This allows an iterable such as an array expression or string to be expanded or an object expression to be expanded wherever placed.
I want to list down the mostly used practical Use Cases of the Spread Syntax (Spread Operator). The following has been explained with examples in this stackoverflow answer.
Combine Arrays (Concatenate Arrays)
Copying Arrays
Calling Functions without Apply
Destructuring Arrays
Function Arguments as Rest Parameters
Using Math Functions
Combining Two Objects
Separate a String into Separate Characters
The [...something] is the spread operator. It in essence allows for an array or string to be expanded. You will see it used often in React, but has many other use cases.
MDN has great documentation on the spread operator:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
You can use "..." in an object. In this example below, "...data" gets 'name: "John", age: 24':
const data= { name: "John", age: 24 };
const newData = {
...data, // Here
sex: "Male"
}
console.log(newData);
This is the result:
{ name: "John", age: 24, sex: "Male" }
This is other example with "...data[key]" to add "id" to each object in an array:
const data = [
{ name: "John", age: 24 },
{ name: "Marry", age: 18 },
{ name: "Tom", age: 15 },
]
const newData = [];
for(const key in data) {
const obj = {
id: Number(key),
...data[key] // Here
}
newData.push(obj);
}
console.log(newData);
This is the result:
[
{ id: 0, name: "John", age: 24 },
{ id: 1, name: 'Marry', age: 18 },
{ id: 2, name: 'Tom', age: 15 }
]
Context: One of the use cases is to do a "copy", but you should take care of this particular "by reference" behavior when working with sub-properties.
Finding: Take care that sub-properties are NOT passed by value, but by reference. In other words, only first level properties are passed as a copy "by value". See the example:
sourcePerson = { name: 'John', colors: ["red", "blue"] }
targetPerson = { ...sourcePerson }
console.log("Target person result:\n", JSON.stringify(targetPerson), "\n\n") //it seems a copy, but...
console.log("Let's update the name source value:\n")
sourcePerson.name = 'Kevin'
console.log("Updated source person:\n", JSON.stringify(sourcePerson), "\n")
console.log("Target person is NOT updated, It keeps a copy by value\n")
console.log(JSON.stringify(targetPerson), "\n\n")
//But if you update a sub-property, it has NOT been copied by value
console.log("Let's update a color sub-property:\n")
sourcePerson.colors[0] = "YELLOW"
console.log("Updated source person:\n", JSON.stringify(sourcePerson), "\n")
console.log("Target person is updated BY REFERENCE!\n")
console.log(JSON.stringify(targetPerson)) // it is not a copy, it is a reference!
console.log("\nCONCLUSION: ... spread syntax make a copy 'by value' for first level properties, but 'by reference' for sub-properties, so take care!\n")

JavaScript Syntax Explanation - return { ...state}; [duplicate]

I have a problem with code I am supposed to work with. I found a syntax I am not familiar with and I have trouble googling the documentation:
export const Something = class Something {
constructor(someObject = {}) {
this.someObject = {...Something.someObjectDefaultAsStaticMethod,...someThing};
};
// The rest of the class
};
I have problems understanding what the three dots (...) in front of the parameter do. And "dots in parameter javascript" is a bad search term. Can someone help me, maybe tell me what this syntax is actually called or just directly link me to documentation?
That is not ES6 but has only been added in ECMAScript 2018.
It is called "Object Rest/Spread Properties" and is part of the Spread Syntax.
... (three dots in Javascript) is called the Spread Syntax or Spread Operator. This allows an iterable such as an array expression or string to be expanded or an object expression to be expanded wherever placed.
I want to list down the mostly used practical Use Cases of the Spread Syntax (Spread Operator). The following has been explained with examples in this stackoverflow answer.
Combine Arrays (Concatenate Arrays)
Copying Arrays
Calling Functions without Apply
Destructuring Arrays
Function Arguments as Rest Parameters
Using Math Functions
Combining Two Objects
Separate a String into Separate Characters
The [...something] is the spread operator. It in essence allows for an array or string to be expanded. You will see it used often in React, but has many other use cases.
MDN has great documentation on the spread operator:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
You can use "..." in an object. In this example below, "...data" gets 'name: "John", age: 24':
const data= { name: "John", age: 24 };
const newData = {
...data, // Here
sex: "Male"
}
console.log(newData);
This is the result:
{ name: "John", age: 24, sex: "Male" }
This is other example with "...data[key]" to add "id" to each object in an array:
const data = [
{ name: "John", age: 24 },
{ name: "Marry", age: 18 },
{ name: "Tom", age: 15 },
]
const newData = [];
for(const key in data) {
const obj = {
id: Number(key),
...data[key] // Here
}
newData.push(obj);
}
console.log(newData);
This is the result:
[
{ id: 0, name: "John", age: 24 },
{ id: 1, name: 'Marry', age: 18 },
{ id: 2, name: 'Tom', age: 15 }
]
Context: One of the use cases is to do a "copy", but you should take care of this particular "by reference" behavior when working with sub-properties.
Finding: Take care that sub-properties are NOT passed by value, but by reference. In other words, only first level properties are passed as a copy "by value". See the example:
sourcePerson = { name: 'John', colors: ["red", "blue"] }
targetPerson = { ...sourcePerson }
console.log("Target person result:\n", JSON.stringify(targetPerson), "\n\n") //it seems a copy, but...
console.log("Let's update the name source value:\n")
sourcePerson.name = 'Kevin'
console.log("Updated source person:\n", JSON.stringify(sourcePerson), "\n")
console.log("Target person is NOT updated, It keeps a copy by value\n")
console.log(JSON.stringify(targetPerson), "\n\n")
//But if you update a sub-property, it has NOT been copied by value
console.log("Let's update a color sub-property:\n")
sourcePerson.colors[0] = "YELLOW"
console.log("Updated source person:\n", JSON.stringify(sourcePerson), "\n")
console.log("Target person is updated BY REFERENCE!\n")
console.log(JSON.stringify(targetPerson)) // it is not a copy, it is a reference!
console.log("\nCONCLUSION: ... spread syntax make a copy 'by value' for first level properties, but 'by reference' for sub-properties, so take care!\n")

How to call for object keys in javascript (codecademy)

I'm following an online course in Javascript from Codecademy but i'm stuck in an assignment.
I'm trying to list the firstName key from my "friends list".
I have to do this with a "for in" statement in a function.
The firstName key is within the object "Steve", which in in an object "Friends".
This is the code that i have at the moment:
var friends = {
steve: {
firstName: 'Steve',
lastName: 'Jobs',
number: '1',
address: ['Fregataan','65','8546','RG','Amsterdam','The Netherlands'],
},
bill: {
firstName: 'Bill',
lastName: 'Gates',
number: '2',
address: ['Fregataan','665','8546','RG','Amsterdam','The Netherlands'],
},
};
function list(friends){
for (var firstName in friends){
console.log(friends.keys(firstName))
}
}
list(friends.keys);
This is the assignment I get from the course:
1. Create a function list that takes a single parameter.
2. In the body of the function, write a for/in loop.
3. In the loop, use console.log to print out the key. (For example, if you only have bill and steve as entries, list should just print out "bill" and "steve".)
The object "friends" was already written in a previous assignment. The function has to be written in this assignment. Can someone please find my mistake and tell me what i did wrong?
Greetings,
Luuk
I think it might be a tricky question. You are trying to print the firstName key which (if done correctly) will print out "Steve" and "Bill", but the assignment, as you described it, is to print out the key (i.e. "steve" and "bill"). So if that's the case, you should just print out the key:
function list(friends){
for (var key in friends){
console.log(key);
}
}
Hope this helps.
You should play around with it a bit more.
No need to use 'keys'.
var friends = {
steve: {
firstName: 'Steve',
lastName: 'Jobs',
number: '1',
address: ['Fregataan','65','8546','RG','Amsterdam','The Netherlands'],
},
bill: {
firstName: 'Bill',
lastName: 'Gates',
number: '2',
address: ['Fregataan','665','8546','RG','Amsterdam','The Netherlands'],
},
};
function list(friends){
console.log(friends);
for (var friend in friends){
console.log(friend);
var f = friends[friend];
console.log(f.firstName);
}
}
list(friends);

how to check true condition in iCanHaz (Moustache Template engine)

I've this json return
data = [
{ firstName: "Christophe",
lastName: "Coenraets"},
{ firstName: "John",
lastName: "Smith"}
];
I want to display each object in a li list and want to use Enumerable condition. I understand if it'd been like
data = { elem :[
{ firstName: "Christophe",
lastName: "Coenraets"},
{ firstName: "John",
lastName: "Smith"}
]};
I can use something like
{{#elem}}
<li>{{firstName}} {{lastName}}</li>
{{/elem}}
But in the first case, how do I check the condition?
I don't work with icanhaz, it very well may have a method to parse the data that you get, but you could always modify the JSON object and wrap it into a parent element like in your second case:
myData = { elem : data};

Categories