Javascript – AppDividend https://appdividend.com Latest Code Tutorials Wed, 15 May 2019 09:48:09 +0000 en-US hourly 1 https://wordpress.org/?v=5.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Javascript – AppDividend https://appdividend.com 32 32 Javascript Blob Object Tutorial With Example | Blob Object Explained https://appdividend.com/2019/05/15/javascript-blob-object-tutorial-with-example-blob-object-explained/ https://appdividend.com/2019/05/15/javascript-blob-object-tutorial-with-example-blob-object-explained/#respond Wed, 15 May 2019 09:44:58 +0000 http://localhost/wordpress/?p=7050 Javascript Blob Object Tutorial With Example | Blob Object Explained

Javascript Blob Object Tutorial With Example | Blob Object Explained is today’s topic. The Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn’t necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user’s system. Javascript Blob Object Tutorial […]

The post Javascript Blob Object Tutorial With Example | Blob Object Explained appeared first on AppDividend.

]]>
Javascript Blob Object Tutorial With Example | Blob Object Explained

Javascript Blob Object Tutorial With Example | Blob Object Explained is today’s topic. The Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn’t necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user’s system.

Javascript Blob Object Tutorial

Blobs are immutable objects that represent raw data. The file is a derivation of Blob that represents data from the file system. Use FileReader to read data from a Blob or File. Blobs allow you to construct file-like objects on the client that you can pass to apis that expect urls instead of requiring the server provides the file.

We can construct Blob from other non-blob objects and data, use the Blob() constructor.

Blob Constructor

The Blob Constructor allows one to create blobs from other objects. For example, to construct a blob from a string.

For this example, we will not use the node.js because node.js does not have blob datatype. You can refer to this StackOverflow link.

Now, create an index.html file and add the following code.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    let student = {name: 'Krunal'}
    let blob = new Blob([JSON.stringify(student, null, 2)], { type: 'application/json' });
    console.log(blob);  
  </script>
</body>
</html>

Now, go to the browser and run this file and you will see the following output in the browser console.

Javascript Blob Object Tutorial With Example

 

Blob size property

The Blob.size property returns the size in bytes of the Blob or a File.

Syntax

var sizeInBytes = blob.size

See the following example.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    let student = {name: 'Krunal'}
    let blob = new Blob([JSON.stringify(student, null, 2)], { type: 'application/json' });
    console.log(blob.size);  
  </script>
</body>
</html>

See the below output.

Blob size method

 

Blob.slice() method

The Blob.slice() function is used to create the new Blob object containing a data in the specified range of bytes of the source Blob.

See the following syntax.

instanceOfBlob.slice([start [, end [, contentType]]]);

See the following code.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    let student = {name: 'Krunal'}
    let blob = new Blob([JSON.stringify(student, null, 2)], { type: 'application/json' });
    console.log(blob.slice(10, 16, { type: 'application/json' }));  
  </script>
</body>
</html>

See the output.

Blob.slice() method

 

Conclusively, Javascript Blob Object Tutorial With Example | Blob Object Explained article is over.

The post Javascript Blob Object Tutorial With Example | Blob Object Explained appeared first on AppDividend.

]]>
https://appdividend.com/2019/05/15/javascript-blob-object-tutorial-with-example-blob-object-explained/feed/ 0
Javascript Function Call Example | Function​.prototype​.call() Tutorial https://appdividend.com/2019/05/15/javascript-function-call-example-function%e2%80%8b-prototype%e2%80%8b-call-tutorial/ https://appdividend.com/2019/05/15/javascript-function-call-example-function%e2%80%8b-prototype%e2%80%8b-call-tutorial/#respond Wed, 15 May 2019 08:32:18 +0000 http://localhost/wordpress/?p=7035 Javascript Function Call Example | Function​.prototype​.call() Tutorial

Javascript Function Call Example | Function​.prototype​.call() Tutorial is today’s topic. The call() method calls the function with the given this value and arguments provided individually. The call() allows for the method belonging to one object to be assigned and called for the different object. Javascript Function Call Example The call() provides a new value of this […]

The post Javascript Function Call Example | Function​.prototype​.call() Tutorial appeared first on AppDividend.

]]>
Javascript Function Call Example | Function​.prototype​.call() Tutorial

Javascript Function Call Example | Function​.prototype​.call() Tutorial is today’s topic. The call() method calls the function with the given this value and arguments provided individually. The call() allows for the method belonging to one object to be assigned and called for the different object.

Javascript Function Call Example

The call() provides a new value of this to the function/method. With a call, you can write the function once and then inherit it in the another object, without having to rewrite the function for a new object.

See the syntax of call() function below.

function.call(this, arg1, arg2, ...)

this parameter is optional. The value of this provided for a call to a function.

The arg1, arg2,..argN is the optional parameter which is the argument of the function.

See the following example.

// app.js

function KGF(hero, villain) {
  this.hero = hero;
  this.villain = villain;
  console.log('Hero is: ' + this.hero + ' and Villain is: ' + this.villain);
}

function Blockbuster(hero, villain) {
  KGF.call(this, hero, villain)
}

let movie = new Blockbuster('Rocky', 'Garuda');

Here, we have used the function prototype.

The function Blockbuster() works as a parameterized constructor, and it accepts two arguments, hero and villain.

Inside that function body, it will call the function KGF() and pass those two arguments and finally in the console we will see the values are printed.

Run the file using the following command.

node app

See the output.

Javascript Function Call Example

 

Using a call to invoke a function and specifying the context for ‘this’

See the below example.

// app.js

function kgf() {
  console.log('Hero is: ' + this.hero + ' and Villain is: ' + this.villain);
}

let movObj = {
  hero: 'Rocky',
  villain: 'Garuda'
}

kgf.call(movObj);

In the example above, when we call kgf() function, the value of this will be bound to object movObj.

The output is the following.

Using a call to invoke a function and specifying the context for 'this'

 

Using a call to invoke a function and without specifying the first argument

See the code.

// app.js

let hero = 'Rocky';
let villain = 'Garuda';

function kgf() {
  console.log('Hero is: ' + this.hero + ' and Villain is: ' + this.villain);
}

kgf.call();

In the above code, we invoke the kgf() function without passing the first argument.

The output of the code is following.

Using a call to invoke a function and without specifying the first argument

 

Here, this does not refer to the global object. Hence, it will give us the undefined in the output. If you wrote above code in Javascript strict mode then also you will get the same result.

Using a call to invoke an anonymous function

See the below code.

// app.ja

let stars = [
  { actor: 'Yash', portrayed: 'Hero' },
  { actor: 'Ramachandra Raju', portrayed: 'Villain' }
];

for (var i = 0; i < stars.length; i++) {
  (function(i) {
    this.display = function() {
      console.log(this.actor +' is '+ this.portrayed);
    }
    this.display();
  }).call(stars[i], i);
}

In the above example, we create an anonymous function and use a call to invoke it on every object in an array. The primary purpose of the anonymous function here is to add a display function to every object, which can display the right index of an object in the array. Passing an object as this value was not strictly necessary, but is done for explanatory purpose.

See the below output.

Using a call to invoke an anonymous function

Finally, Javascript Function Call Example | Function​.prototype​.call() Tutorial is over.

The post Javascript Function Call Example | Function​.prototype​.call() Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/05/15/javascript-function-call-example-function%e2%80%8b-prototype%e2%80%8b-call-tutorial/feed/ 0
Javascript Object toString Example | Object toString() Method Tutorial https://appdividend.com/2019/04/21/javascript-object-tostring-example-object-tostring-method-tutorial/ https://appdividend.com/2019/04/21/javascript-object-tostring-example-object-tostring-method-tutorial/#respond Sun, 21 Apr 2019 09:18:33 +0000 http://localhost/wordpress/?p=6119 Javascript Object toString Example | Object toString() Method Tutorial

Javascript Object toString Example | Object toString() Method Tutorial is today’s topic. The Object​.prototype​.toString() method returns a string representing the object. Every object has the toString() method that is automatically called when an object is to be represented as the text value or when an object is referred to in a manner in which a string […]

The post Javascript Object toString Example | Object toString() Method Tutorial appeared first on AppDividend.

]]>
Javascript Object toString Example | Object toString() Method Tutorial

Javascript Object toString Example | Object toString() Method Tutorial is today’s topic. The Object​.prototype​.toString() method returns a string representing the object. Every object has the toString() method that is automatically called when an object is to be represented as the text value or when an object is referred to in a manner in which a string is expected.

Javascript Object toString Example

By default, Javascript Object toString() method is inherited by every object descended from the Object. If this method is not overridden in the custom object, toString() returns “[object type],” where type is an object type. The syntax is following.

object.toString()

It returns the string representing the object.

See the following example.
// app.js

function GoT(name) {
  this.name = name
}

let name = new GoT('Jon Snow')

console.log(name.toString())

The output is following.

Javascript Object toString Example

 

Overriding the default toString() method

You can create the function to be called in place of the default toString() method. Javascript Object toString() method takes no arguments and should return the string. Object toString method you create can be any value you want, but it will be the most useful if it carries information about an object. See the following example.

// app.js

function GoT(name) {
  this.name = name
}

let name = new GoT('Jon Snow')

GoT.prototype.toString = function() { 
  return ''+this.name;
}

console.log(name.toString())

The output is following.

 

Object toString() Method Tutorial

Finally, Javascript Object toString Tutorial is over.

The post Javascript Object toString Example | Object toString() Method Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/04/21/javascript-object-tostring-example-object-tostring-method-tutorial/feed/ 0
How To Get Distinct Values From Array In Javascript https://appdividend.com/2019/04/11/how-to-get-distinct-values-from-array-in-javascript/ https://appdividend.com/2019/04/11/how-to-get-distinct-values-from-array-in-javascript/#respond Thu, 11 Apr 2019 18:14:48 +0000 http://localhost/wordpress/?p=5901 How To Remove Duplicate Values From Array in Javascript Tutorial

In this tutorial, we will see How To Get Distinct Values From Array In Javascript. Primitive values in the JavaScript are immutable values except for objects. Types of primitive values include Null, Undefined, Boolean, Number, Symbol and String. This tutorial also gives you the answer to the How can I get a list of unique […]

The post How To Get Distinct Values From Array In Javascript appeared first on AppDividend.

]]>
How To Remove Duplicate Values From Array in Javascript Tutorial

In this tutorial, we will see How To Get Distinct Values From Array In Javascript. Primitive values in the JavaScript are immutable values except for objects. Types of primitive values include Null, Undefined, Boolean, Number, Symbol and String. This tutorial also gives you the answer to the How can I get a list of unique values in an array. So see the following example.

Get Distinct Values From Array In Javascript

Write the following code inside the app.js file.

// app.js

const unique = (value, index, self) => {
  return self.indexOf(value) === index
}

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30]
const uniqueAges = ages.filter(unique)

console.log(uniqueAges)

In the above function, we have used the two in-built javascript functions. Javascript Array Filter and Javascript Array Indexof. We have also used an arrow function which is the feature of ES6.

So, actually, in the above code, we filter out each repetitive value using filter function and pass the unique callback to each array item.  The array indexOf() method returns a first index at which the given element can be found in an array, or -1 if it is not present in an array. That way, we filter out the values, and remaining values form an array, and that result array has unique values.

The native method filter will loop through the array and leave only those entries that pass the given callback function unique.

The unique function checks, if the given value is the first occurring. If not, it must be a duplicate and will not be copied.

This solution works without any extra library like jQuery or prototype.js.

It works for arrays with mixed value types too.

The output is following.

 

How To Get Distinct Values From Array In Javascript

Above Code Using ES6

We can reduce the above code to only just three lines of code and actual logic to 1 line. See the following code.

// app.js

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30]
const uniqueAges = ages.filter((x, i, a) => a.indexOf(x) == i)
console.log(uniqueAges)

It will give the same output.

Get Unique Values using Javascript Set

In ES6, the code is much simpler. The code snippet below utilizes the Set object to store the collection of unique values then we have used spread operator to construct the new array. See the following example.

// app.js

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30]
const uniqueAges = [...new Set(ages)]

console.log(uniqueAges)

The constructor of Set takes an iterable object, like Array, and the spread operator  transform the set back into an Array.

The output is following.

 

Get Unique Values using Javascript Set

Above solution only works for the primitive values. If you have the array of dates, then you need some more customized methods.

Using Set and Array From Method

We can also use the Javascript Set and Javascript Array From method to get unique values. It will eliminate the duplicate values from an array. See the following code.

// app.js

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30]
const result = Array.from(new Set(ages));
console.log(result)

It will give us the same output.

Distinct property values of the array of objects

Let’s get the unique values from an array of objects. See the following code.

// app.js

const students = [
  {
    name: 'Krunal',
    age: 26
  },
  {
    name: 'Ankit',
    age: 25
  },
  {
    name: 'Krunal',
    age: 26
  }
]
const uniqueArr = [... new Set(students.map(data => data.name))]
console.log(uniqueArr)

In the above code, we defined one object with the repeated properties and then we have used the set and use the Javascript Array Map function to form an array with unique values. See the following output.

 

Distinct property values of an array of objects

Define our own Array Unique Prototype

We can also define the prototype that can give us the unique value of the array. Our prototype function will be following.

// app.js

Array.prototype.unique = function() {
  var arr = [];
  for(var i = 0; i < this.length; i++) {
      if(!arr.includes(this[i])) {
          arr.push(this[i]);
      }
  }
  return arr; 
}

Now, call the Javascript Array Unique function on an array and see the output. The final code is following.

// app.js

Array.prototype.unique = function() {
  let arr = [];
  for(let i = 0; i < this.length; i++) {
      if(!arr.includes(this[i])) {
          arr.push(this[i]);
      }
  }
  return arr; 
}

const ages = [26, 27, 26, 26, 28, 28, 29, 29, 30]
const uniqueAges = ages.unique()
console.log(uniqueAges)

The output is following.

 

Define our own Array Unique Prototype

Finally, How To Get Distinct Values From Array In Javascript or How To Remove Duplicate Values From Array in Javascript Tutorial is over.

The post How To Get Distinct Values From Array In Javascript appeared first on AppDividend.

]]>
https://appdividend.com/2019/04/11/how-to-get-distinct-values-from-array-in-javascript/feed/ 0
Javascript Object Is Example | Object.is() Tutorial https://appdividend.com/2019/04/09/javascript-object-is-example-object-is-tutorial/ https://appdividend.com/2019/04/09/javascript-object-is-example-object-is-tutorial/#respond Tue, 09 Apr 2019 16:23:15 +0000 http://localhost/wordpress/?p=5811 Javascript Object Is Example | Object.is() Demo Tutorial

Javascript Object Is Example | Object.is() Tutorial is today’s topic. Javascript Object.is() method determines whether two values are the same value. Object.is() method was introduced in ES2015. It aims to help to compare values. Javascript Object Is Example The Object.is() decides whether two values are the same value. Two values are the same if one […]

The post Javascript Object Is Example | Object.is() Tutorial appeared first on AppDividend.

]]>
Javascript Object Is Example | Object.is() Demo Tutorial

Javascript Object Is Example | Object.is() Tutorial is today’s topic. Javascript Object.is() method determines whether two values are the same value. Object.is() method was introduced in ES2015. It aims to help to compare values.

Javascript Object Is Example

The Object.is() decides whether two values are the same value. Two values are the same if one of the following holds,

  • both are undefined
  • both are null
  • both are true or both false
  • both strings are of the same length with the same characters in the same order
  • both are the same object (means both objects have the same reference)
  • both numbers are and
    • both +0
    • both -0
    • both NaN
    • or both non-zero and both not NaN and both have the same value

The syntax of Javascript Object.is() method is following.

Object.is(value1, value2);

The value1 parameter is required, and it is the first value to compare.

The value2 parameter is required, and it is the second value to compare.

It returns the boolean value indicating whether or not the two arguments are the same value.

Let’s see the example.

// app.js

let a = 'app'
let b = 'app'

console.log(Object.is(a, b))

The output is following.

 

Javascript Object Is Example | Object.is() Tutorial

Both variable’s value is the same. So it returns a true.

Let’s compare the undefined and null.

let a = null
let b = undefined

console.log(Object.is(a, b))

The output is following.

 

Object.is() Tutorial

Now, let’s compare two empty arrays and see the output.

// app.js

let arrA = []
let arrB = []

console.log(Object.is(arrA, arrB))

 

Javascript Object Is Example

See the output is false.

Now, check for the objects.

// app.js

let objA = {}
let objB = {}

console.log(Object.is(objA, objB))

The output is of course false.

Okay, see the following example.

// app.js

let objA = {a: 1}
let objB = {a: 1}

console.log(Object.is(objA, objB))

We have defined the same values of the objects, but the reference is different; that is why it is going to output false.

See the following scenario.

// app.js

let objA = {a: 1}
let objB = {a: 1}

console.log(Object.is(objA, objA))

In this case, we will get true because value and reference are the same. That is why it gives true.

Finally, see some following cases.

// app.js

console.log(Object.is(undefined, undefined))
console.log(Object.is(null, null))
console.log(Object.is(0, -0))
console.log(Object.is(-0, -0))
console.log(Object.is(NaN, 0/0))

The output is following.

 

The Object is() method

Finally, Javascript Object Is Example | Object.is() Tutorial is over.

The post Javascript Object Is Example | Object.is() Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/04/09/javascript-object-is-example-object-is-tutorial/feed/ 0
Javascript Null, Undefined and NaN Tutorial With Example https://appdividend.com/2019/04/08/javascript-null-undefined-and-nan-tutorial-with-example/ https://appdividend.com/2019/04/08/javascript-null-undefined-and-nan-tutorial-with-example/#respond Mon, 08 Apr 2019 22:16:37 +0000 http://localhost/wordpress/?p=5781 Javascript Null, Undefined and NaN Tutorial

Javascript Null, Undefined and,  NaN Tutorial With Example is today’s topic. The value null represents the intentional absence of any object value. The undefined property indicates that the variable has not been assigned a value, or not declared at all. The NaN property represents a “Not-a-Number” value. The NaN property indicates that a value is not […]

The post Javascript Null, Undefined and NaN Tutorial With Example appeared first on AppDividend.

]]>
Javascript Null, Undefined and NaN Tutorial

Javascript Null, Undefined and,  NaN Tutorial With Example is today’s topic. The value null represents the intentional absence of any object value. The undefined property indicates that the variable has not been assigned a value, or not declared at all. The NaN property represents a “Not-a-Number” value. The NaN property indicates that a value is not a legitimate number.

Javascript null, undefined and NaN

The null is one of JavaScript’s primitive values. The NaN is a property of the global object. The global undefined property represents the primitive value undefined. It is one of JavaScript’s primitive types. Let’s see one by one.

Javascript null

The value null is written with a literal: null. The null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected, but no object is relevant. In short, In JavaScript, the data type of null is an object.

Let’s see some examples of null.

// app.js

const marvel = null
console.log(marvel)

The output is null.

Now, let’s remove the first line from the above code and see the output.

// app.js

console.log(marvel)

Now, run the file in the node environment and see the output.

 

Javascript null Tutorial With Example

See, it throws an error. So when we assign the null value, it gives the null in return.

Let’s check the typeof null. See the following code.

// app.js

let marvel = null
console.log(typeof(marvel))

The output is following.

Javascript Null, Undefined and NaN Tutorial With Example

 

So, null is an object in Javascript.

Javascript null basic math operations

Check out the basic math operations on null. Write the following code.

// app.js

console.log(null / 7)
console.log(null % 7)
console.log(null - 7)
console.log(null + 7)
console.log(null * 7)

The output is following.

Javascript null basic math operations

Javascript undefined

The undefined is the property of a global object; i.e., it is the variable in the global scope. An initial value of undefined is the primitive value undefined. A variable that has not been assigned a value is of type undefined. The method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. See the following example.

// app.js

let marvel
console.log(marvel == undefined)

So, if the marvel is undefined, then it will return a true otherwise false. We have not assigned the value to the marvel yet, that is why it returns undefined. The output is following,

 

Javascript undefined

Typeof operator and undefined

See the following code.

// app.js

let marvel
if (typeof marvel === 'undefined') {
   console.log('Marvel is undefined')
}
else {
  console.log('It is not undefined')
}

In the above code, we have compared the undefined with the unassigned variable marvel. So, if the condition is true, it will print the console message. The output is following.

 

Typeof operator and undefined

Difference between null and undefined in Javascript

The undefined and null are equal in value but different in type.

See the following code.

// app.js

console.log(typeof undefined)
console.log(typeof null)
console.log(null === undefined )
console.log(null == undefined)

The output is following.

Difference between null and undefined in Javascript

 

See, if you compare the value, then they both are same, but if you compare its datatype, then they are different that is why we get false.

Javascript NaN

NaN is a property of the global object. I think the definition is clear enough. JavaScript returns this value when number we’re supposed to get isn’t a number. For example, when you’re trying to subtract an “appdividend” from 21 or divide 12 by “KDL”.

See the following example.

// app.js

console.log('Appdividend' - 30)

The output is following.

 

Javascript NaN

The NaN property is a same as the Number.Nan property. We can use the isNaN() global function to check if a value is a NaN value when you’re adding something to the string. If JavaScript sees a + sign and a string, it automatically converts the second element of addition into the string as well.

Now, let’s check the typeof NaN.

// app.js

console.log(typeof NaN)

Run the file and see the output.

 

typeof NaN Example

So, the datatype of NaN is number. Not an object or undefined or null.

 If NaN compared to itself returns false, then no matter what we’re going to compare it to, it will always give false. See the following code.

// app.js

console.log(NaN === NaN)
console.log(NaN == NaN)

The output is following.

 

NaN in Javascript

Finally, Javascript Null, Undefined and NaN Tutorial With Example is over.

The post Javascript Null, Undefined and NaN Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/04/08/javascript-null-undefined-and-nan-tutorial-with-example/feed/ 0
Javascript Object defineProperty Example | Object.defineProperty() Tutorial https://appdividend.com/2019/04/06/javascript-object-defineproperty-example-object-defineproperty-tutorial/ https://appdividend.com/2019/04/06/javascript-object-defineproperty-example-object-defineproperty-tutorial/#respond Sat, 06 Apr 2019 13:00:32 +0000 http://localhost/wordpress/?p=5715 Object.defineProperty() Tutorial Example

Javascript Object defineProperty Example | Object.defineProperty() Tutorial is today’s topic. The static method Object.defineProperty() defines the new property directly on the object, or modifies an existing property on the object, and returns an object.Object.defineProperty() allows the precise addition to or modification of the property on the object. Normal property addition through assignment creates the properties which […]

The post Javascript Object defineProperty Example | Object.defineProperty() Tutorial appeared first on AppDividend.

]]>
Object.defineProperty() Tutorial Example

Javascript Object defineProperty Example | Object.defineProperty() Tutorial is today’s topic. The static method Object.defineProperty() defines the new property directly on the object, or modifies an existing property on the object, and returns an object.Object.defineProperty() allows the precise addition to or modification of the property on the object. Normal property addition through assignment creates the properties which show up during a property enumeration (for…in loop or Object.keys() method), whose values may be changed and may be deleted.

Javascript Object defineProperty Example

When a property specified doesn’t exist in an object, Object.defineProperty() creates the new property as described. Fields may be omitted from a descriptor, and default values for those fields are inputted.

Syntax

The syntax of Object.defineProperty is following.

Object.defineProperty(obj, prop, descriptor)

obj: The object on which to define the property.

prop: The name or Symbol of the property to be defined or modified.

descriptor: The descriptor for the property being defined or modified.

See the following example.

// app.js

const marvel = {}
Object.defineProperty(marvel, 'ironman', {
  value: 'Tony Stark'
})
console.log(marvel.ironman)

The output is following.

 

Javascript Object defineProperty Example

So, we have defined the property on marvel object.

Now, let’s print the object.

// app.js

const marvel = {}
Object.defineProperty(marvel, 'ironman', {
  value: 'Tony Stark'
})
console.log(marvel)

The output is following.

 

Object.defineProperty() Tutorial

See, the object is empty, but when you try to print the property, it gives its value.

We can use enumerable property. The enumerable is true if and only if this property shows up during enumeration of the properties on the corresponding object.

Now, add an enumerable property to true while defining a property on an object.

// app.js

const marvel = {}
Object.defineProperty(marvel, 'ironman', {
  value: 'Tony Stark',
  enumerable: true,
})
console.log(marvel.ironman)
console.log(marvel)

Okay, let’s see the output.

 

Javascript Object defineProperty Example Tutorial

Modifying a property

Now, let’s change the existing property.

// app.js

const marvel = {}
Object.defineProperty(marvel, 'ironman', {
  value: 'Tony Stark',
  enumerable: true,
  writable: true,
  configurable: true
})
console.log(marvel.ironman)
marvel.ironman = 'RDJ'
console.log(marvel.ironman)
console.log(marvel)

The output is following.

 

Javascript Object defineProperty Example | Object.defineProperty() Tutorial

Finally, Javascript Object defineProperty Example | Object.defineProperty() Tutorial is over.

 

The post Javascript Object defineProperty Example | Object.defineProperty() Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/04/06/javascript-object-defineproperty-example-object-defineproperty-tutorial/feed/ 0
WebSockets Tutorial With Example | Getting Started With WebSockets https://appdividend.com/2019/04/03/websockets-tutorial-with-example-getting-started-with-websockets/ https://appdividend.com/2019/04/03/websockets-tutorial-with-example-getting-started-with-websockets/#respond Wed, 03 Apr 2019 20:28:17 +0000 http://localhost/wordpress/?p=5676 WebSockets Tutorial With Example | Getting Started With WebSockets

WebSockets Tutorial With Example | Getting Started With WebSockets is today’s topic. Web sockets are defined as two-way communication between the servers and clients, which mean both parties can communicate and exchange data at the same time. WebSockets are the alternative to HTTP communication in the Web Applications. They offer a long-lived, bidirectional communication channel […]

The post WebSockets Tutorial With Example | Getting Started With WebSockets appeared first on AppDividend.

]]>
WebSockets Tutorial With Example | Getting Started With WebSockets

WebSockets Tutorial With Example | Getting Started With WebSockets is today’s topic. Web sockets are defined as two-way communication between the servers and clients, which mean both parties can communicate and exchange data at the same time. WebSockets are the alternative to HTTP communication in the Web Applications. They offer a long-lived, bidirectional communication channel between the client and the server. Once established, the channel is kept open, offering the high-speed connection with low latency and overhead.

WebSockets Tutorial With Example

Web socket protocol is being standardized, and it is becoming a real-time communication between web servers and clients. Web sockets are transforming to cross-platform standard for real-time communication between a client and the server. HTTP protocol has its own set of schemas such as the http and https. Web socket protocol also has a similar kind schema defined in its URL pattern.

Web Socket is the independent TCP-based protocol, but it is designed to support any other protocol as well that would traditionally run only on top of the pure TCP connection.

Web Socket is the transport layer on the top of which any other protocol can run. The Web Socket API supports this ability to define the sub-protocols: protocol libraries that can interpret specific contracts.

Examples of such protocols include XMPP, STOMP, and AMQP. The developers have no longer have to think in terms of an HTTP request-response paradigm.

The only requirement on the browser-side is to run the JavaScript code that can interpret the Web Socket handshake, establish and maintain the Web Socket connection.

On the server side, the industry standard is to use existing protocol libraries that run on top of TCP and leverage a Web Socket Gateway.

A simple example of initial request headers is as follows.

GET ws://websocket.appdividend.com/ HTTP/1.1
Origin: http://appdividend.com
Connection: Upgrade
Host: websocket.appdividend.com
Upgrade: websocket

How WebSockets differ from HTTP

HTTP is a different protocol, and also a different way of communicating. HTTP is the request/response protocol: the server returns some data when the client requests it.

In the WebSocket, the server can send a message to the client without the client explicitly requesting something.

A client and a server can talk to each other simultaneously.

Very little data overhead needs to be exchanged to send messages. This means low latency communication.

Secured WebSockets

Always use the secure, encrypted protocol for WebSockets, wss://.

The ws:// refers to the unsafe WebSockets version (the http:// of WebSockets), and should be avoided for obvious reasons.

Create a new WebSockets connection

We can create a connection using the following code.

const url = 'wss://appdividend.com/post'
const connection = new WebSocket(url)

The connection is a WebSocket object.

When the connection is successfully established, the open event is fired.

Attaching some event handlers immediately to the connection allows you to know when the connection is opened, received incoming messages, or there is an error.

The second argument accepts optional subprotocols. It can be a string or an array of strings. Each string should represent a subprotocol name and server accepts only one of passed subprotocols in the array. Accepted subprotocol can be determined by accessing the protocol property of the WebSocket object.

Listen for it by assigning a callback function to the onopen property of the connection object.

connection.onopen = () => {
  //...
}

If there’s an error, the onerror function callback is fired.

connection.onerror = error => {
  console.log(`WebSocket error: ${error}`)
}

Implement WebSocket on Node.js Server

Let’s take an example and implement the WebSocket on Node.js server.

Create the project folder and inside that folder, create a file called server.js.

Also, open up the terminal and create a package.json file and using the following command.

npm init -y

Then we need to install the ws library for WebSocket.

 

Implement WebSocket on Node.js Server

Then add the following code inside the server.js file.

// server.js

const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', ws => {
  ws.on('message', message => {
    console.log(`Received message => ${message}`)
  })
  ws.send('Message From Server!!')
})

So, we have created our server. Now, we need to create a client. So, when the client is connected to the server, we will send and receive the message between client and server.

Now, go to the terminal and start the node server by the following command.

node server

Write the following code inside the client.js file.

// client.js

const WebSocket = require('ws')
const url = 'ws://localhost:8080'
const connection = new WebSocket(url)

connection.onopen = () => {
  connection.send('Message From Client') 
}

connection.onerror = (error) => {
  console.log(`WebSocket error: ${error}`)
}

connection.onmessage = (e) => {
  console.log(e.data)
}

Here, we have written the code that can connect the server WebSocket, and when the connection is open, we send a message to the server and also, if the server has any message that needs to be received by a client then it will display the message at client-side as well.

Okay, now we need to start a client-side server by the following command.

node client

So, at this time, we have started the two-node server.

  1. client.js
  2. server.js

The output is following for client.js.

 

Create a new WebSockets connection

The output is following for server.js.

 

Secured WebSockets

As soon as we have a connection to the server (when a open event is fired) we can start sending data to the server using the send(‘your message’) method on the connection object.

So, two-way communication is done quickly.

Finally, WebSockets Tutorial With Example | Getting Started With WebSockets is over.

The post WebSockets Tutorial With Example | Getting Started With WebSockets appeared first on AppDividend.

]]>
https://appdividend.com/2019/04/03/websockets-tutorial-with-example-getting-started-with-websockets/feed/ 0
Javascript Array ToString Example | Array.prototype.toString() Tutorial https://appdividend.com/2019/04/02/javascript-array-tostring-example-array-prototype-tostring-tutorial/ https://appdividend.com/2019/04/02/javascript-array-tostring-example-array-prototype-tostring-tutorial/#respond Tue, 02 Apr 2019 18:12:24 +0000 http://localhost/wordpress/?p=5633 Javascript Array ToString Example | Array.prototype.toString() Tutorial

Javascript Array ToString Example | Array.prototype.toString() Tutorial is today’s topic. The Array toString() method returns a string representing the specified array and its elements. Javascript toString() method converts an array into a String and returns the result.  For Array objects, the toString() method joins an array and returns one string that containing each array element separated […]

The post Javascript Array ToString Example | Array.prototype.toString() Tutorial appeared first on AppDividend.

]]>
Javascript Array ToString Example | Array.prototype.toString() Tutorial

Javascript Array ToString Example | Array.prototype.toString() Tutorial is today’s topic. The Array toString() method returns a string representing the specified array and its elements. Javascript toString() method converts an array into a String and returns the result.  For Array objects, the toString() method joins an array and returns one string that containing each array element separated by the commas.

Javascript Array ToString Example

The syntax of Javascript Array ToString() method is following.

array.toString()

Let’s take an example.

// app.js

let arr = ['krunal', 'ankit', 'rushabh', 'dhaval'];
console.log(arr.toString());

The output is following.

 

Javascript Array ToString Example

So, that means it has returned the comma separated values.

JavaScript calls a toString() method automatically when the array is to be represented as the text value or when the array is referred to in a string concatenation.

The returned string will separate the elements in the array with commas.

A slightly less common approach is to use the Javascript Array join() method. By default, it adds the comma to resulting values, though you can also specify that it adds nothing or some other separator value. Javascript Array join() method creates and returns the new string by concatenating all of the elements of an array.

You can also take advantage of JavaScript’s type coercion: the + operator can either add the two numbers or concatenate the two strings. But what happens when we try to join the object (the array [] is also the object) with something else? JavaScript is forgiving so it will not crash the program. Instead of that, it does know how to concatenate the strings so that it will convert everything into the string.

Convert Array of Arrays to String

We can also convert an array of arrays into a String. Let’s see the following example.

// app.js

let arr = [['krunal', 'ankit', ['hello']], ['rushabh', 'dhaval']];
console.log(arr.toString());

The output will be a single string with all the items comma separated. Notice that also, subarrays are separated by comma as well.

See the below output.

 

Convert Array of Arrays to String

Finally, Javascript Array ToString Example | Array.prototype.toString() Tutorial is over.

The post Javascript Array ToString Example | Array.prototype.toString() Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/04/02/javascript-array-tostring-example-array-prototype-tostring-tutorial/feed/ 0
Javascript encodeURIComponent Function Tutorial With Example https://appdividend.com/2019/03/29/javascript-encodeuricomponent-function-tutorial-with-example/ https://appdividend.com/2019/03/29/javascript-encodeuricomponent-function-tutorial-with-example/#respond Fri, 29 Mar 2019 19:37:59 +0000 http://localhost/wordpress/?p=5488 Standard builtin objects

Javascript encodeURIComponent Function Tutorial With Example is today’s topic. The encodeURIComponent() function encodes the Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing a UTF-8 encoding of the character. The new string representing the provided string encoded as the Uniform Resource Identifier (URI) component. […]

The post Javascript encodeURIComponent Function Tutorial With Example appeared first on AppDividend.

]]>
Standard builtin objects

Javascript encodeURIComponent Function Tutorial With Example is today’s topic. The encodeURIComponent() function encodes the Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing a UTF-8 encoding of the character. The new string representing the provided string encoded as the Uniform Resource Identifier (URI) component.

Javascript encodeURIComponent Function Tutorial

It returns a new string representing the provided string encoded as a Uniform Resource Identifier (URI) component. The syntax of encodeURIComponent is following.

encodeURIComponent(str)

It takes the required argument that is str. It is the component of the URI.

The encodeURIComponent escapes all the character except A-Z a-z 0-9 – _ . ! ~ * ‘ ( ).

The encodeURI differs from encodeURIComponent.

Let’s encode the reserved characters.

// app.js

let ex1 = ";,/?:@&=+$"

console.log(encodeURIComponent(ex1))

The output is following.

 

Javascript encodeURIComponent Function Tutorial With Example

Okay, now let’s see the unescaped characters.

// app.js

let ex2 = "-_.!~*'()"
console.log(encodeURIComponent(ex2))

The output is following.

 

Javascript encodeURIComponent Function

Now, let’s encode the number sign. See the following example.

// app.js

let ex3 = "#"
console.log(encodeURIComponent(ex3))

The output is following.

 

encodeURIComponent

Also, we can encode the Alpha Numeric characters plus space. See the following example.

// app.js

let ex4 = "AppDividend appdividend 21"
console.log(encodeURIComponent(ex4))

The output is following.

 

Javascript encodeURIComponent

Use encodeURIComponent on user-entered fields from forms POST’d to the server. This will encode “&” symbols that may inadvertently be generated during data entry for individual HTML entities or other characters that require encoding/decoding.

The post Javascript encodeURIComponent Function Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/03/29/javascript-encodeuricomponent-function-tutorial-with-example/feed/ 0