Receiving error message when initialising JavaScript function - javascript

So below is my javascript code. It's wrapped in module.exports, but that's not the error.
parseMention = (arg, asId = false) => {
if(!arg.startsWith('<#') && arg.endsWith('>')) return undefined
let id = arg.slice(2, -1)
if(id.startsWith('!')) id.slice(1)
if(asId === true) return id
if(asId === false) return bot.users.cache.get(id)
}
despite it seeming correct to me, I get the following error message:
SyntaxError: Invalid shorthand property initializer
Any help would be much appreciated

It's wrapped in module.exports, but that's not the error.
I'm pretty sure there is the error.
This part of your code won't throw a SyntaxError: Invalid shorthand property initializer error. It would be great to see your module.exports, but it's 99.9% that you're trying to export an object like this and the = after parseMention is an invalid shorthand property initialiser:
// This is invalid syntax
module.exports = {
parseMention = (arg, asId = false) => {
if (!arg.startsWith('<#') && arg.endsWith('>')) return undefined;
let id = arg.slice(2, -1);
if (id.startsWith('!')) id.slice(1);
if (asId === true) return id;
if (asId === false) return bot.users.cache.get(id);
}
}
This should work:
module.exports = {
parseMention(arg, asId = false) {
if (!arg.startsWith('<#') && arg.endsWith('>')) return undefined;
let id = arg.slice(2, -1);
// it won't do anything, slice won't mutate id and you don't return
if (id.startsWith('!')) id.slice(1);
if (asId === true) return id;
if (asId === false) return bot.users.cache.get(id);
},
};

Related

how can i avoid error "can't convert undefined to an object "

some of the document does not consists planDetails planId properties and its returning error "can't convert undefined to an object , but i have to fetch that document if these properties exists or not , how can i avoid this error
this.profile.find({ userId: ObjectId(req.id) }).populate("planId").lean().exec(function(err, profileFound) {
console.log(profileFound);
if (err) return callback(err);
if (profileFound && profileFound.length === 0) {
return callback(false, common.errorMsg("PROFILE DOES NOT EXIST"));
} else {
var profileData = profileFound[0];
profileData["isPlanTaken"] = false;
profileData["planDetails"] = {};
if(profileData.hasOwnProperty("planId") && profileData.planId){
if(Object.keys(profileData.planId).length>0){
profileData["isPlanTaken"]=true;
profileData["planDetails"]=profileData.planId;
}
}
return callback(
false,
common.successMsg("PROFILE FETCHED",profileData )
);
}
});
I think there was missing the initialization of profileData variable only...
const profileData = {};
profileData["isPlanTaken"] = false;
console.log(profileData);
profileData["planDetails"] = {};
if(profileData.hasOwnProperty("planId") && Object.keys(profileData.planId)){
profileData["isPlanTaken"]=true;
profileData["planDetails"]=profileData.planId;
}
console.log(profileData);
And I think that is also enough to check a property is exists in an object. Can you please give me more data for example, because I don't really know what do you need.
const profileData = {};
profileData.isPlanTaken = false;
console.log(profileData);
profileData.planId = 5; // for example
if (profileData.planId) {
profileData.isPlanTaken = true;
profileData.planDetails = profileData.planId;
}
console.log(profileData);

How to fix cannot ready property of undefined

So, i've been coding a discord bot, and i'm getting this error when trying to check if "mrole" has the property "app". I have no idea why this is not working.
I want it to read the team's id so i can sort out the json file like this:
let barney = message.guild.roles.find(r => r.name === "Barney")
let deadpool = message.guild.roles.find(r => r.name === "Deadpool")
let hulk = message.guild.roles.find(r => r.name === "Hulk")
let mario = message.guild.roles.find(r => r.name === "Mario")
let spiderman = message.guild.roles.find(r => r.name === "Spider-Man")
let umbreon = message.guild.roles.find(r => r.name === "Umbreon")
let app = message.guild.member(message.mentions.users.first());
let app2 = message.mentions.users.first().username
var mrole
if (app.roles.has(barney.id)){
mrole = barney.id
}
else if (app.roles.has(deadpool.id)){
mrole = deadpool.id
}
else if (app.roles.has(hulk.id)){
mrole = hulk.id
}
else if (app.roles.has(mario.id)){
mrole = mario.id
}
else if (app.roles.has(spiderman.id)){
mrole = spiderman.id
}
else if (app.roles.has(umbreon.id)){
mrole = umbreon.id
}
if(mrole = barney.id || deadpool.id || hulk.id || mario.id || spiderman.id || umbreon.id){
if (client.memberspoints.mrole[app.id].name != app2){
client.memberspoints [mrole] = {
[app2.id]: {
name: `${app2}`,
mpoints: `${+args[1]}`
}
}
message.channel.send(`${app} agora tem ${+args[1]} pontos`);
}
else{
let _mpoints = client.memberspoints.mrole[app.id].mpoints
var smpoints = +_mpoints + +args[1]
client.memberspoints [mrole] = {
[app.id]:{
name: `${app2}`,
mpoints: `${smpoints}`
}
}
message.channel.send(`${app} agora tem ${smpoints} pontos`);
}
fs.writeFile ('./memberspoints.json', JSON.stringify (client.memberspoints, null, 2), err => {
if (err) throw err;
console.log('Salvo');
});
Here is the error i'm geting:
if (client.memberspoints.mrole[app.id].name != app2){
^
TypeError: Cannot read property 'app.id' of undefined
I basically want it to check if the "mrole" already has the name of the person on it, so i an sort it out by team and by name. Any ideas?
To check if an object has a certain property, you should use the object.hasOwnProperty method:
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
so, it would go like this:
if(mrole.hasOwnProperty('app')) { // do stuff }
I recently learned that in this could potentially be a security problem, so its better to use it like this: if( Object.prototype.hasOwnProperty.call(mrole, 'app'). ( you can read more here ).
now, the probelm might be something else entirely- I noticed that in the line
if(mrole = barney.id || deadpool.id || hulk.id || mario.id || spiderman.id || umbreon.id), you ASSIGN to the mrole, and not comparing! should be if(mrole == ...

Uncaught TypeError: Cannot read property 'get' of null in map function

I have findPlayerWithID function which return matched player id
function findPlayerWithID(players, id) {
let i = 0;
for (; i < players.count(); i++) {
if (players.map((degisken) => degisken.get('id'))._tail === undefined) { continue; }
if (players.map((degisken) => degisken.get('id'))._tail.array[i] === id) {
return i;
}
}
return -1;
}
But sometimes it give error in this line
if (players.map((degisken) => degisken.get('id'))._tail === undefined) { continue; }
error is
gameStore.js:38 Uncaught TypeError: Cannot read property 'get' of null
at gameStore.js:38
at immutable.js:3018
at Ue.__iterate (immutable.js:2208)
at r.__iterateUncached (immutable.js:3017)
at F (immutable.js:606)
at r.T.__iterate (immutable.js:322)
at r.toArray (immutable.js:4260)
at new Ue (immutable.js:2067)
at _t (immutable.js:3572)
at Ue.map (immutable.js:4403)
I think error because of null object
How can I check null in this line
if (players.map((degisken) => degisken.get('id')).
immutable.js:1317 Uncaught TypeError: Cannot read property 'merge' of null
at immutable.js:1317
at Ne (immutable.js:1973)
at Ne (immutable.js:1982)
at Ne (immutable.js:1982)
at pe.updateIn (immutable.js:1280)
at pe.mergeIn (immutable.js:1314)
at gameStore.js:207
at createReducer.js:15
at combineReducers.js:133
at c (createStore.js:178)
Updated
with #canaan-seaton answear I change
this
if (players.filter(degisken => degisken !== null).map((degisken) => degisken.get('id'))._tail.array[i] === id) {
return i;
}
this work
but it give another error in immutablejs
Uncaught TypeError: Cannot read property 'merge' of null
at immutable.js:1317
at Ne (immutable.js:1973)
at Ne (immutable.js:1982)
at Ne (immutable.js:1982)
at pe.updateIn (immutable.js:1280)
at pe.mergeIn (immutable.js:1314)
at gameStore.js:207
at createReducer.js:15
at combineReducers.js:133
at c (createStore.js:178)
at this line in immutablejs
function(m ) {return typeof m.merge === 'function' ?
I searcg for that error
there is some info but I don't understand what should I do https://github.com/facebook/immutable-js/issues/597
here is my console
Generally , it is not a good practice to check for equality to undefined.
I would try to do it this way:
First of all, to make sure that degisken does exists you can go with degisken && degisken.get(id)
Second, you might want to use Object's hasOwnProperty method, which will be useful in here:
players.map((degisken) => {
const id = degisken && degisken.get('id');
if(id && id.hasOwnProperty('_tail') && id._tail.array[i] === id){
return i
}
});
if you just want to check if the array has elements then you can do something like the following....
if (players && players.length > 0) {/* Do Stuff */}
if you are concerned with specific indices within the array being null then you could do something like this....
if (players.filter(degisken => degisken !== null)
.map((degisken) => degisken.get('id'))._tail === undefined)
{/* Do Stuff */}

I am trying to check for undefined but it's not working

I have the following code:
$scope.$watch("pid", _.debounce(function (pid) {
var a = pid;
$scope.$apply(function (pid) {
if (typeof pid == "undefined" || pid == null || pid === "") {
$scope.pidLower = null;
$scope.pidUpper = null;
}
else if (pid.indexOf("-") > 0) {
pid = pid.split("-");
$scope.pidLower = parseInt(pid[0]);
$scope.pidUpper = parseInt(pid[1]);
}
else {
$scope.pidLower = parseInt(pid);
$scope.pidUpper = null;
}
});
}, 1000));
The very first time the code runs (when the pid field is empty) I check pid with the google development tools and it shows as "undefined". However when the code runs it does not go into the first if condition. Rather it goes to the second and gives an error saying:
TypeError: Object # has no method 'indexOf'
Can anyone tell me why it ignores the first if statement ?
Here is what I get when I use the console to check pid on the first line with an if:
console.log(typeof pid)
object
undefined
Here is what I get when I use the console to check pid on the first line with an if:
console.log(typeof pid)
object
undefined
This says that the type of pid is an object. It then says that the return value of console.log() is undefined.
It isn't going into the first if because the variable is not, as you thought, undefined.
It then fails because, whatever kind of object pid is, it isn't one with an indexOf method.
Try this:
if (!pid) {
$scope.pidLower = null;
$scope.pidUpper = null;
}
else if (pid.indexOf("-") > 0) {
pid = pid.split("-");
$scope.pidLower = parseInt(pid[0]);
$scope.pidUpper = parseInt(pid[1]);
}
else {
$scope.pidLower = parseInt(pid);
$scope.pidUpper = null;
}

Check two variables for undefined

JS:
var ctoken = req.cookies.user;
var stoken = req.session.passport.user;
if(ctoken === 'undefined' || stoken === 'undefined'){
return res.send('invalid token');
}else{
if (ctoken.split('_')[0] !== stoken) {
return res.send('invalid token');
}
}
At
ctoken.split('_')[0]
an error is thrown :
cannot call split of undefined.
Why? This should not happen because of the if condition.
Remove the quotes :
if (ctoken === undefined || stoken === undefined) {
Maybe you were confused by a trend during which some programmers recommended to test using
if (typeof something === 'undefined') {
But the best test is to simply compare with undefined.

Categories

Resources