I have the following code in one module :
export let person = {
name : "henry",
age : 5
}
in another module i import :
import {person} from './person'
When try to change person module:
person = {
name : "joe",
age : 20
}
I get a syntax Error.
But when i change any property on the person object it does so successfully
person.name = "joe" // works
person.age =50 //works
why is it so?
When you doing import {person} from './person' you are acctely getting const person with the exported object.
You cant change the content of your person object, but, becuse the only thing that is const in the case- is the refrence to object, you can change the content of the object itself.
For example:
const obj = {};
obj.stackoverflow = "Cool site"; // works!
obj = "stackoverflow"; //TypeError: Assignment to constant variable
Related
I want to access local variables from a function inside a file using a nested function imported from another file, but when I try to access it, it displays undefined instead.
File 1:
import { getFirstName } from './getfirstname'
let name = { "fullname" : "John Doe" }
export class Class1 extends React.Component {
getName = (x) => {
var y = x.fullname
getFirstName(y)
}
}
getName(name);
File 2 (getfirstname.js) :
export const getFirstName = (z) => {
var fname = z.split(/\|/).map(s => s .split (/\s+/) [0])
console.log(fname)
}
How can I make sure using getName(name) returns John instead of undefined?
Edit: this working example should be more relevant to the question: https://codepen.io/marwann/pen/VwvRWrr
There are several problems with your code as posted:
Your Class1 extends React.Component for no apparent reason
You define getName as a instance method of Class1 but then try to call it directly, instead of as a property on an instance of Class1
You speak of "returning" but none of your code here returns anything-- it only logs to the console.
Ultimately, I don't think your issue is at all related to importing, and I suspect it is throwing an error when you try to call getName which does not exist in scope.
If we rewrite it with those things fixed, we should be able log a result:
const getFirstName = (z) => {
var fname = z.split(/\|/).map(s => s .split (/\s+/) [0])
return fname
}
let name = { "fullname" : "John Doe" }
class Class1 {
getName = (x) => {
var y = x.fullname;
return getFirstName(y);
}
}
const instance = new Class1();
const fname = instance.getName(name);
console.log(fname);
Note that I've created an instance of your class and called getName from that instance. I've additionally updated both getName and getFirstName to actually return a value.
A few other items to consider:
Nothing about your class as currently exists leverages the benefits you get from organizing your code into a class. It might be worth considering whether or not it is actually necessary.
I would recommend against mixing var with let and const. If you are working in an environment that allows you to leverage let/const, you can just replace any var with a let if it must be reassigned and a const if it will never be reassigned.
I have declared an object in JS and trying to assign a value to its properties.
But I can do it when only one property is defined, but not with more than one property.
This works fine:
let User = {
name
};
User['name']='Praveen';
alert(User.name);
But this does not
let User = {
name,
email
};
User['name']='Praveen';
User['email']='incopraveen#gmail.com';
alert(User.email); //says email is not defined.
NB: I have tried removing semicolons also.
Tried dot notation also
Because this:
let User = {
name,
email
};
is a shortform for:
let User = {
name: name,
email: email,
};
So it directly initializes both properties to the value that the variables name and email are holding. name is defined, it is the name of the page you are in, which you can easily check with:
console.log(name);
but email is not defined yet, and trying to get an undeclared variable results in an error:
console.log(email); // email is not defined
To solve that, explicitly declare both variables before:
let name = "test";
let email = "test#example.com";
let User = {
name,
email
};
Or initialize the properties not at all:
let User = {};
or directly set the properties to a value:
let User = {
name: "test",
email: "test#example.com",
};
Your code is ok,
Please check do you have any existing name,email variable which you are set in the User Object,
I think you do not have existing name and email variable. So that It can not create the User Object itself.
You can do like this..
let User = {};
User['name']='Praveen';
User['email']='incopraveen#gmail.com';
This link could help you, https://alligator.io/js/object-property-shorthand-es6/
I have the following code, inside a constants.js file:
var constants = (
conversationUsername: "user1",
conversationPassword: "pass1",
conversationVersionDate: "date1",
conversationWorkspaceId: "work1"
};
module.exports.constants = constants;
Now, inside another file, I have the following:
var constants = require('./../constants');
console.log(constants);
Which outputs me:
{ constants:
{ conversationUsername: 'user1',
conversationPassword: 'pass1',
conversationVersionDate: 'date1',
conversationWorkspaceId: 'work1' } }
Which I alright, I guess.
My question is, how can I now access these fields? If i try:
console.log(constants.conversationUsername);
I get:
undefined
Access its constants field first
console.log(constants.constants.conversationUsername);
or export that object directly
module.exports = constants;
Another fast forward solution is to extract the property from import:
var constants = require('./../constants').constants
or short
var {constants} = require('./../constants')
Then access the properties as expected:
constants.conversationUsername
I have this object that is being exported and imported by other files. Initially, the object is empty but during an event change ( a button clicked), the object is filled with keys and values but still remains empty in the files that imported it. How can I dynamically update an object and then export it with it's new values.
The code looks something like this:
firstFile.js
const anObject = {};
function clicked() {
anObject.firstName = "John";
anObject.lastName = "Doe" ;
}
module.exports = anObject;
secondFile.js
const importedObject = require("./firstFile");
console.log(importedObject) // always returns an empty object
You have to export and call the clicked function. Otherwise you are never actually updating that object.
For example.
firstFile.js
const anObject = {};
function clicked() {
anObject.firstName = "John";
anObject.lastName = "Doe" ;
}
module.exports = anObject;
module.exports.clicked = clicked;
secondFile.js
const importedObject = require("./firstFile");
console.log(importedObject.firstName) //undefined
importedObject.clicked()
console.log(importedObject.firstName) //John
Edit
After discussing further with the OP this is an Electron application. The code above works in Node.js. Electron might have a different setup and require extra steps to make this work.
My understanding of modules is that they are distinct from each other. However I don't understand why this code works then.
Lets say I have three files in the node.js framework. One "app.js" driver file and two modules:
Module "one.js" simply has a property called "name":
module.exports = {
name: null
}
Module "two.js" loads module "one.js" and declares a function that prints out the contents of the property "name" in the "one.js" module:
var one = require('./one');
module.exports = {
printname: function()
{
console.log(one.name);
}
}
Now the driver (app.js) imports both modules, sets the property of the first module, then calls the name printing function of the second:
var one = require("./one");
var two = require("./two");
two.printname();
one.name = "John";
two.printname();
When I run this, it prints "null" (fine, it should be empty), then "John" (not fine). How is the second module learning of the value in the first module?
My thought process is: when "two.js" loads its own version of "one.js", the property "name" should always be null. Why is this not the case?
Because you are modifying a property of an Object, and Objects are passed by reference, therefore all the instances that imported one.js got the same instance.
If you need different instances you should export a class and create an instance on demand.
Something like that:
//one.js
class Data {
constructor(data) {
this.data = data;
}
}
export.module = Data;
//two.js
const Data = require('./one');
const data = new Data('John');
one's export is a static object. It it not new every time.
You can change it like so:
module.exports = function() {
return { name: null }
}
Then:
var one = require("./one");
var willAlwaysBeNew = one();
willAlwaysBeNew.name = "john"
var willAlwaysBeNewToo = one();
console.log(willAlwaysBeNew.name) // john
console.log(willAlwaysBeNewToo.name) // null