Categories
JavaScript Answers

How to add dictionaries in JavaScript like Python?

To add dictionaries in JavaScript like Python, we can create an object.

For instance, we write

const statesDictionary = {
  CT: ["alex", "harry"],
  AK: ["liza", "alex"],
  TX: ["fred", "harry"],
};
console.log(statesDictionary.AK[0]);

to create the statesDictionary object that has some keys and values inside.

Then we can access the object’s property values by writing

statesDictionary.AK[0]
Categories
JavaScript Answers

How to check if a string has white space with JavaScript?

To check if a string has white space with JavaScript, we can use the regex test method.

For instance, we write

const hasWhiteSpace = (s) => {
  return /\s/g.test(s);
};

to define the hasWhiteSpace function that checks if string s has any whitespaces with /\s/g.test.

We use \s to match any whitespaces in s.

The g flag makes test check for all instances of whitespaces.

Conclusion

To check if a string has white space with JavaScript, we can use the regex test method.

Categories
JavaScript Answers

How to insert HTML into a div with JavaScript?

To insert HTML into a div with JavaScript, we can set the innerHTML property.

For instance, we write

document.getElementById("tag-id").innerHTML = "<ol><li>html data</li></ol>";

to select the div with getElementById.

Then we set its innerHTML property to a string with the HTML we want to render.

Categories
JavaScript Answers

How to get visitor’s location using geolocation with JavaScript?

To get visitor’s location using geolocation with JavaScript, we can use the Ipregistry API.

For instance, we write

const response = await fetch("https://api.ipregistry.co/?key=tryout");
const payload = await response.json();
console.log(payload.location.country.name, payload.location.city);

to call fetch to make a get request to https://api.ipregistry.co/?key=tryout

Then we get the response from it with json.

And then we get the country and city data from the payload.

We put that in an async function.

Categories
JavaScript Answers

How to create a function in JavaScript that can be called only once?

To create a function in JavaScript that can be called only once, we can set a property on the function after it’s executed.

For instance, we write

const myFunc = () => {
  if (myFunc.fired) {
    return;
  }
  myFunc.fired = true;
  //...
};

to check the myFunc.fired property is set to true.

If it is, then we stop running myFunc with return.

Otherwise, we set myFunc.fired to true and run the rest of the code.

Conclusion

To create a function in JavaScript that can be called only once, we can set a property on the function after it’s executed.