"Uncaught SyntaxError: Cannot use import statement outside a module" in JS import statement [duplicate] - javascript

This question already has answers here:
javascript modules and CORS
(4 answers)
"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6
(31 answers)
Closed yesterday.
I know people have had issues with this, but I have a slightly different problem. I'm getting the error, "Uncaught SyntaxError: Cannot use import statement outside a module", using the import statement, "import Lemmatizer from 'js/lemmatizer.js';" in JavaScript. Here's my code:
import Lemmatizer from 'js/lemmatizer.js';
let all = [];
function lemmatise(word) {
var lemmatizer = new Lemmatizer();
all.push(lemmatizer.lemmas(word));
}
function process() {
// Get the input
let input = document.getElementById("input").value;
// Define the words that add no extra meaning (to remove later)
let useless = ["the", "is", "a", "an", "are"];
// Tokenise
let tokens = input.split(" ");
// Lemmatise
tokens.forEach(lemmatise);
alert(tokens);
alert(all);
}
I don't know why this is happening. Thanks!

Related

Trying to check if input is an array React Javascript using JSON.parse() throws an error if it's not [duplicate]

This question already has answers here:
How to check if a string is a valid JSON string?
(27 answers)
Closed 2 years ago.
I am trying to check if the value in the input is Array.
This is working great if the input is an array, but if the input is not an array, I get JSON errors: Uncaught SyntaxError: Unexpected token s in JSON at position 0
Any other solutions that won't throw errors and keep the code working so if it's a different input I can render something else?
function App() {
const [input, setinput] = React.useState("");
const handleSubmit = (event) => {
event.preventDefault();
let parsed = JSON.parse(input);
let condition = Array.isArray(parsed);
if(condition === true){
console.log('working')
}
Array.isArray(input)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
Scroll down to examples.

What does "?." (dot after questiion mark) mean in JS [duplicate]

This question already has an answer here:
What does this symbol mean in JavaScript?
(1 answer)
Closed 2 years ago.
I stumbled upon the "?." syntax in another SO question. Something like this -
console.log(x?.y?.z);
What does it do?
This is called Optional Chaining.
It allows to use the property chaining without having to validate properties in each level. It short circuits property evaluation without raising exceptions - thus avoiding the "Cannot read X of undefined" error.
let o = {p: {q: 'foo'}};
try {
console.log('Trying to access the property x');
console.log(o.x.y);
}
catch(e) {
console.log('That was an error');
}
console.log('Trying to access the property x with Optional Chaining');
console.log(o?.x?.y);
Optional chaining more use cases
With function calls
let result = someInterface.customMethod?.();
With expressions
let nestedProp = obj?.['prop' + 'Name'];
With array elements
let arrayItem = arr?.[42];
ECMAScript Draft

Let vs Var with AsyncStorage Strange Exception [duplicate]

This question already has answers here:
Cannot use let to define a variable with the same name of function's parameter
(2 answers)
Javascript ES6 'let' and 'var' - unexpected behavior inside function with argument name matching redeclared variable
(1 answer)
Closed 3 years ago.
To replicate the below, run this code on React Native 0.59.8
I have a function that looks like the below:
import AsyncStorage from 'react-native';
const saveToStorage = async (value) => {
await AsyncStorage.setItem('#store.key', value);
let value = await AsyncStorage.getItem('#store.key');
// Exception is thrown on ios because value is seen as null
}
But if I changed let to var the request is processed successfully.
const saveToStorage = async (value) => {
await AsyncStorage.setItem('#store.key', value);
var value = await AsyncStorage.getItem('#store.key');
// No exception is thrown on ios
}
Does anyone have an idea what is going on?
I would comment this if I could but I think there's a couple things that you could change. Don't name that variable value because you are passing a parameter called value into your async function, so value will already be defined. Also I think you are missing an await in your AsyncStorage.getItem('#store.key')

Javascript API syntax help - const { uport, MNID } [duplicate]

This question already has answers here:
What is the difference between const and const {} in JavaScript
(4 answers)
Closed 4 years ago.
So while I was making my react native app, I tried to use an API from
https://github.com/uport-project/react-native-uport-connect and there is a syntax that I've yet to understand.
May I know what does const { uport, MNID } mean from this code
import configureUportConnect from 'react-native-uport-connect'
const { uport, MNID } = configureUportConnect({
appName: 'uPort Demo',
appAddress: '2oeXufHGDpU51bfKBsZDdu7Je9weJ3r7sVG',
privateKey:'<PRIVATE_KEY>',
})
Im quite new to this and this code is placed on a seperate js file and im trying to export const { uport, MNID } so I could use it in my Components and im not sure if it's a variable, object or some js syntax. Thank you!
This is called destructuring, and it means you are assigning your variables, not to the object that the function returns, but to the individual properties of that object, specifically the properties at the keys uport and MNID. The alternative syntax would be to say const variableName = // etc... and then you would access the properties like: variableName.uport.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

Why is √ is not allowed as a objectName/stringName/functionName/NumberName? [duplicate]

This question already has answers here:
What characters are valid for JavaScript variable names?
(12 answers)
Closed 7 years ago.
I am coding a scientific calculator and I need some help:
function √(in){
return Math.sqrt();
}
// throws an error
var √ = function(in){
return Math.sqrt();
}
// also throws an error
var √ = "sqrt";
√randomSqNum = 100,
√random = {sqrt:4,cubert:8},
√sqNum = ["0","1","4","9","16","25"],
√null = null,
√undefined = undefined;
They all throw an error!
Please explain why they throw an error.
Also, Is there a way around this?
In Javascript, variable names must begin with a letter, _ or $. More information here:
http://www.w3schools.com/js/js_variables.asp
JavaScript follows annex 31 of the unicode standard regarding identifier names.
I assume you are using U+221A as character. As you can see from the linked page, it can neither be used at the beginning of an identifier nor within it:
(likely because it is not even a letter).
Compare that to π, which is a letter and which can be used in an identifier name.
Also, Is there a way around this?
No. However, you can always try to find letters that look similar.
You cannot use it directly as a name, but you can use it as key.
var f={}
f["√"] = Math.sqrt
alert(f["√"](5))
In such way you can define +-*/ and many other funcions.
f["+"] = function(a){
return a.reduce(function(p,v){
return p+v
},0)
}
And when you have a parsed statement tree in form {o:fn,a:[s1,...,sn]} where fn is function name and s1,...,sn are subtrees or values, then you can simply get the result:
function calc(st){
return (typeof st == 'object')?f[st.o].apply(null,st.a.map(calc)):st
}

Categories