Posts

Showing posts with the label JavaScript

How to change a String's Case in JavaScript

Image
Strings can be capitalized using String.toUpperCase
For instance;
const str = 'John swana' str.toUpperCase() // 'JOHN SWANA' String.toLowerCase turns strings to their small letters or 'lowerCase'

const strr = "Lorem ipsum" strr.toLowerCase() // lorem ipsum Numbers are not converted, they remain constant, untouched and unchanged.


'65'.toLowerCase() // '65'

Array concat method in JavaScript

Image
Array concat is a method and an array property for concating one array onto another to archive merging of array elements.
Syntax for array concat;
const arr = [0,1,2,3]
const arrr = [4,5]
arr.concat(arrr) // [0,1,2,3,4,5]
Merging nested arrays using spread operator. It's possible to merge nested arrays to form a uniform array.
Take for instance you have two 2-dimensional arrays,
Or let's call them matrices
const arr2d = [[1,0],[0,1]]
//[[1,0],
// [0,1]] const arrr2d = [[1,1],[0,1]]
//[[1,1],
// [0,1]]
For instance you want to reduce the two 2-dimentional arrays and create a new array instance;
[].concat(...arr2d.concat(...arrr2d)) // [1, 0, 0, 1, 1, 1, 0, 1]

How to get user's ip address in JavaScript

An IP address is a unique numerical label given to a computer when connected to a network;ipify.org is a free service that retrieves IP addresses in JSON formatfetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(response => console.log(JSON.stringify(response)))// response
{"ip":"--.---.---.---"}
In nodejs you can use a package node-fetchInstall it by typing;npm i node-fetchOr using curl, in your terminal type;curl 'https://api6.ipify.org?format=json'// response
{"ip":"--.---.---.---"}

How to evaluate a string on a regular expression rule in JavaScript

JavaScript has a built in regular expression function for testing if a string arguments is matching the given regular expression rule;Syntax of the regular expression tester is as follows;/regex/.test(string)Take for instance you want to test if a string contains only alphanumeric upper and lower case characters, space and numbers;const str = "Eat code sleep"/[A-Z,a-z,0-9, ]*/.test(str)
// returns boolean 'true'Or in another example;const str = "Eat, Code, Sleep"/[A-Z,a-z,0-9, ]*/.test(str)
// returns boolean 'false'Because commas are not included in the regular expression match rules.

What is 'this.' keyword in JavaScript

In JavaScript 'this' is an object and a reference to the current object that is used to get and to set properties of the current object.Take for instance within a function;const func = function (name){
    this.name = name
}func.name instance property name is set to that of the first argument;const inst = new func('duke')inst.name
// returns dukeYou can as well extend func to set name using 'this';func.prototype.set = function(name){
    this.name = name
}Running the previous instance with this set method;inst.set('John')
// returns John

How to create promises in JavaScript

Promises enable asynchronous programming, JavaScript is single threaded,
You can use them to wait a lengthy promises take for instance an ajax or fetch process then once ready process the response.How do declare an asynchronous function,
To declare an asynchronous function add async keyword befor function name;const func = async function() {
    return 'OK'
}function func will now return a promise;const inst = func()
.then(response => console. Log(response))
.catch(err => {
    throw new Error(err)
}You can also await it like ummm;const response = await func()
console.log(response)Rejecting and resolution of promises,
This is done to distinguish successful promises from failed promisesconst statusReport = function() {
    return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), 10000)
   })
}You can inquire statusReport as follows;const analysis = new statusReport()
.then(() => console.log('hooray'), () => console.log('failure'…

How to use fetch api submit an html form

Fetch api allows asynchronous means of reading files and a more simplified way of making http requests in JavaScript.How to submit an existing html form using fetch api;Assuming you have html source code with a form and some input fields;<form id="form" action="./submit" method="post"
onsubmit="handle(event)">
<input name="query">
<button>
    submit
</button>
</form>You can pass an instance of a dom form to formData constructor as the first parameter;const handle = function(event) {
    event.preventDefault()
    const data = new formData(event.target)fetch('//localhost/api/post', {
    method: 'POST',
    body: data
})
}Fetch api returns a new pending promise to process the response you will need to await asynchronous process once ready to consume parse it as follows;.then(response => response.json()).then(response => console.log(response))

Constructor functions in JavaScript

A constructor function is a function whose instance is created using the 'new' keyword.Constructor functions in JavaScript can be declared using classes or by using JavaScript functions 'with few tweaks'HowtocreateaconstructorinJavaScriptFor JavaScript functions construction declaration can be made as follows;const greeting = function(name) {
    this.name = name
}greeting.morning = function() {
    const name = this.name
    return `morning ${name}`
}In the code bove declared a function greeting with a parameter named 'name'I further created a method named morning it returns a template greeting messageOnce the program gets run on a JavaScript engine the expected output is;morning + 'name provided'For instance;const greet = new greeting('John')greet.morning()
// returns 'morning John'Similar to using functions as constructors you can as well declare using classes;const greeting = class {
    constructor(name) {
        this.name = name
 …

How to build a twitter retweet bot using JavaScript

I'm sharing the code of my tweeter bot called 'JavaScript bot' I forked the original source code from a certain github repository written in nodejs the bot retweets a giver hashTag at a specified time intervalYou can use a twitter bot to promote an interest or a campaign unlike Facebook twitter is more tolerant on automated accountsI used to build Facebook automated accounts which were posting user friendly comments on my Facebook friends posts with no success few months down the line Facebook suspended my account until then i decided to stop using Facebook at allAnd twitter is just the right platform for this kind of thing.For this bot to work you'll simply need an APIs key and a secretTwitter doesn't need waiting the long verification process as of 2020 I created my developer account and almost instantaneously my account got approved.The twitter hard limit on the number of retweets per day is 1000;clone git repository using the command;git clone https://github.co…

How to wait for a promise within a loop block

JavaScript promises enable developers to write asynchronous applications in JavaScriptLoops are ways of iterating elements
For instance doing an asynchronous task within a for loop can be done as follows;
Note that lag is used to emulate some delay.const items = [1, 2, 3, 4]
const lag = async (delay) => {
    return new Promise((resolve) =>
        setTimeout(() => res(`${delay / 1000} sec`), delay))
}items.forEach(async (item) => {
    const seconds = await lag(1000 * item)
    console.log(seconds)
})expected output1 sec
2 sec
3 sec
4 secAfter running the code above every second some text was printed

How to pretty print JSON.stringify output

JSON.stringify is a method of JSON global which converts valid JSON to a serialized stringJSON is an abbreviation of 'JavaScript Object Notation' it's an independent data type that is not specific to JavaScript programming language.JSON is a global object with methods for manipulating JSON dataJSON.stringify is a method that converts JSON to a string its may be used for debug or simply to serialize JSONIt accepts three arguments (JSON, FUNCTION, SPACER)JSON: maybe an array or objectFUNCTION: Is an influencer it's a middle man that alters what is to be returnedSPACER; Is a character used to indent or prettyfiy outputFor instance take a look;const name = 'John'
const surname = 'swana'
const me = {name, surname}JSON.stringify(me, null, '    ')Returns the following output;{
    'name': 'John',
    'surname': 'swana'
}

Object assign in JavaScript

Object assign in JavaScriptObject assign is a static method of JavaScript Object global.Object assign is mainly used for merging two or more objects, where keys match Object assign overwrites one value of an object with the corresponding value of the same key in the second object.Example usage of object assign;const max = {
    name: 'max',
  type: 'dog',
    bread: 'fluffy'
}Given a situation where you want to derive a new pet of a certain name you will not need to redefine the whole pet structure instead just add or replaced the characteristics of the pet to that of your desire;const khloe = Object.assign(max, {
  name: 'khloe'
  type: 'cat',
  color: 'blue'
})// output after running the code above on a JavaScript engine;{
    "name": "khloe",
    "type": "kitty",
    "bread": "fluffy",
    "color": "blue"
}You can notice that Object khloe is a clone of ma…

E2020 dynamic imports in JavaScript

Escmascript Is a standard from which JavaScript and typescript are both derived from.ES2020 is out it comes with it new ways of writing JavaScript code.Dynamic imports enable importing dependencies in a rather dynamic way.Initially JavaScript developers were restricted to statically load their dependencies for instance;import { property } from 'dependency'On runtime the JavaScript engine loads the required dependencies and makes them accessible globally.However that is a rigid way of writing code.Dynamic imports are  relatively more flexible therefore you can included them at any segment within your program.For instance if you want to load file system module only if a certain criteria is met you would do as follows;If(process.argv[2] == 'start')
Import fs from 'fs'Dynamic imports return a promise use the syntax below to make use of themimport('fs')
.then(fs => {
   // consume module fs
})

Ways of iterating Object properties in JavaScript

For Objects the ways of iterating their properties are not that plentiful as with Arrays.take for instance we have an object of dogs and cat characteristicsconst pets = {
{name: "Jenny", eyes: "brown"},
{name: "max", eyes: "blue"}
}To iterate through the characteristics using for loopfor (pet in pets) {
    console.log(`${pets[pet].name} has eye color ${pets[pet].eyes}`}
}Alternatively you can use objects.keys and object.entriesfor (element in Object.entries(elements)) }

Handy array functions every developer should know JavaScript

Array make a good means of data storage and manipulation in JavaScriptif used well arrays are way better than objects especially if you're working with numbersArray.push(element)
Its a method used for quickly appending an element to an array
For instance
const arr = ['code']
arr.push('eat')
// ['eat', 'code']Array.unshift(element)
It's a method that's pretty similar to array.push except that unshift prepends an element to the end of the array
For instance
const arr = ['eat', 'code']
arr.unshift('sleep')
// ['eat', 'code', 'sleep']Array.shift()
Array.shift is a function that removes the first element of an array and returns it
For instance
const arr = ['eat', 'code']
const err = arr.shift()
arr returns
// ['sleep']
err returns
// eatArray.pop()
Is a method an array property similar to shift that removes the last element of an array and returns it. Array.pop() and array.sh…

Get current url port, hostname and path in JavaScript

window.location is an Object with properties of current location namely window.location.href returns the href url of the current pagewindow.location.hostname returns the domain namewindow.location.pathname returns the pathname segment of the urlwindow.location.protocol returns the web protocol of the urlwindow.location.assign() loads a new document

Redirecting a webpage in JavaScript

Redirects are way of navigating a user to another webpage or location redirects are normally done by server side implementations.it's possible to do redirects using JavaScript too window.location is a object that stores current location information such as path, port, hostname and href or the location in the address bar of your browser changing it invokes a redirect it's a simple way to redirect a user to another webpageSyntax
window.location.asign('https://example.com')or simply likewindow.location = "https://example.com"or simply omit windowlocation = "https://example.com"

How to target all elements of a given class name in JavaScript

JavaScript getByClassName only targets one element by default Workarounds "loops"
Loops can mess up your code I personally don't like them.
To target all elements you will have to iterate through all of them for each element you will have to add a event listenerExample
For instance the are 3 links of a same class and you want to add event listeners on all of them
....
....
....
// JavaScript
const links = document.getByClassName("links")
for(var i = 0; i < links.length; i++)
links[i].addEventListener('click', event => console.log(event.target.get attribute('class')))

JavaScript event prevent default

JavaScript event preventdefault is a method for intervening event actions preventing normal events behaviorTake for instance you have an anchor on a page when a user clicks on it the browser by default navigates to a url in it's href attributepreventdefault syntax/// HTML
<a href="/" id="home">
    home
</a>/// JavaScript
home.addEventListener('click', function(event){
    event.preventdefault()
    // rest of
    // the code
})

With statement in JavaScript

JavaScript 'with statement' is a simplified way to access object properties as variables.Take for instance;const dog = "puppy"
const mascots = {
    'tux': "tuxedo",
    'cow': 'cow'
}with(mascots) {
    console.log(tux)
    // tuxedo
    console.log(cow)
    // cow
    console.log(dog)
    // puppy
}properties of mascots are converted to variables accessible within the with block 'dog' is not part of mascots and as a fallback, dog global is returned.At the time of writing this post with statement is discouraged.It's not allowed in 'safe mode'With the above sample you can do the same thing using destructureing operatorconst {cow, dog, tux} = mascotsconsole.log(tux)
// tuxedo
console.log(cow)
// cow
console.log(dog)
// puppy