Posts

Showing posts with the label JavaScript

How to get first and last character of a string using 'String.startsWith' and 'String.endsWith' in JavaScript

Image
String starts with is an emcscript es6 feature that allows JavaScript developers to test a string if the first character of a string matches the given criteria , Take for instance you have a string, you want to test if it starts with characters '#' const str = "#JavaScript" cons strr = "I love #kotlin" str.startWith('#') // true strr.endsWith('#kotlin') // true strr.startWith('#') // false str.endsWith('#kotlin') // false Both functions return a boolean true for a match and false if there's no match. endsWith does what startsWith does except that it does it at the end of the string

How to tabulate array key values using console.table

console.table is a function for tabulating arrays key value pairs it retuns a table when given an array as input. const table = Array(5).fill(0) console.table(table) ┌─────────┬────────┐ │ (index) │ Values │ ├─────────┼────────┤ │ 0 │ 0 │ │ 1 │ 0 │ │ 2 │ 0 │ │ 3 │ 0 │ │ 4 │ 0 │ └─────────┴────────┘

How to use 'console.assert' for assertion in JavaScript

console.assert prints text passed as second argument if the first argument returns false; for example, const notTrue = false; console. assert(notTrue, 'I\'ts false') // return "it's false" You can use console.assert to perform simple unit tests of your JavaScript application. const application = function(params){ if(params.num < 10) return false else return true } const instance = new application({ num: 5 }) console.assert(instance, 'number less than ten') // return "number less than ten"

What is strict mode in JavaScript

Strict mode is a ECMAScript 5.1 feature used mainly for testing and debugging. when enabled the JavaScript engine catches more errors among others undeclared variables, duplicate object properties. How to enable strict mode, In your code include; 'use strict'; You can put the declarative on the top most line anything that comes after it will be handled in a strict manner.

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 format fetch('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-fetch Install it by typing; npm i node-fetch Or 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 duke You 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 promises const statusReport = function() {     return new Promise((resolve, reject) => {     setTimeout(() => resolve(), 10000)    }) } You can inquire statusReport as follows; const analysis = new statusReport() .then(() => console.log('hooray'), ()

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' How to create a constructor in JavaScript For 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 message Once 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 {    

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 interval You can use a twitter bot to promote an interest or a campaign unlike Facebook twitter is more tolerant on automated accounts I 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 all And 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 secret Twitter 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

How to wait for a promise within a loop block

JavaScript promises enable developers to write asynchronous applications in JavaScript Loops 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 output 1 sec 2 sec 3 sec 4 sec After 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 string JSON 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 data JSON.stringify is a method that converts JSON to a string its may be used for debug or simply to serialize JSON It accepts three arguments (JSON, FUNCTION, SPACER) JSON: maybe an array or object FUNCTION: Is an influencer it's a middle man that alters what is to be returned SPACER; Is a character used to indent or prettyfiy output For 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 JavaScript Object 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

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 them import('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 characteristics const pets = { {name: " Jenny ", eyes: "brown"}, {name: "max", eyes: "blue"} } To iterate through the characteristics using for loop for (pet in pets) {     console.log(`${pets[pet].name} has eye color ${pets[pet].eyes}`} } Alternatively you can use objects.keys and object. entries for (element in Object.entries(elements)) }

Handy array functions every developer should know JavaScript

Array make a good means of data storage and manipulation in JavaScript if used well arrays are way better than objects especially if you're working with numbers Array.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 // eat Array.pop () Is a method an array property similar to shift that removes the last element of an array and retu

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 page window.location.hostname  returns the domain name window.location.pathname  returns the pathname segment of the url window.location.protocol  returns the web protocol of the url window.location.assign ()  loads a new document