Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Monday, December 13, 2021

Javascript: Working with Arrays using Asynchronous operations

Let’s say we have a list of names. For each name, we want to make an API call and get some information, and then keep a new list with this collection of information. A typical approach may look like this.

Refactoring to using map or forEach is not that straightforward here. The callbacks provided to map or forEach (or any of the array-methods) are not awaited, so we have no way of knowing when the full collection of information is done and ready to use. However, there is still a way we can write this in a nice way. Using the Promise.all method.

Awesome! Now, map returns a list of promises, and the Promise.all method takes a list of promises and resolves them in parallel. Not only did the code become much more nice and clean - but we also benefit from the fact that the promises are not resolved sequentially, which speeds up the process and increases performance.

Share This:    Facebook Twitter

Javascript: sort() and Array destructuring

Take a look at the code below.

At first glance, this looks good. We’re not using let, and we’re not mutating on the original array using something like push. But take a look at the console.log statement. It turns out that the sort method does not create a copy of the original array. Instead, it both mutates on the original array and returns its own array from the method call.

And there are a handful of old Array-methods that do this. Be careful with push, shift, unshift, pop, reverse, splice, sort, and fill. Fortunately, most often we can simply avoid calling these methods at all, to stay out of trouble.

However, there are cases, like using sort, where we have to use a method that mutates the original array, in lack of better options. Array destructuring to the rescue! Whenever these occasions arise, make sure to manually copy the array first, before performing an operation on it. It’s as simple as this.

That [...grades] makes the entire difference.

Share This:    Facebook Twitter

Javascript: Pass arguments as an object

Say we have a function, createUser, which requires four arguments in order to create a new user (by calling some API).

When looking at the function signature itself, things seem to make pretty good sense. But how about when we call it?

It’s pretty unclear what the arguments mean, right? Especially the last two booleans. I would have to go to the implementation to look it up. Instead, we can wrap the arguments in an object.

Thanks to ES6 object destructuring, we can do this easily by simply adding curly brackets around the arguments. Now, whenever we call createUser, we pass an object as a single argument with the required values as properties instead.

See how nice that reads out now. We’re no longer in doubt what those booleans mean. There’s another version of this that I’ve seen very often: Passing optional arguments as an options object. The idea is to pass 1-2 essential arguments and then pass the remaining arguments as an options object.

Now we need to check if the options object is set before accessing its values and provide proper fallbacks. On the other hand, calling the createUser function now looks very clean.

The first two arguments are pretty obvious, and we can now optionally provide options when needed.

Share This:    Facebook Twitter

Javascript: Guard clauses and avoiding using 'else'

Guard clauses

“In computer programming, a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question. Regardless of which programming language is used, guard code or a guard clause is a check of integrity preconditions used to avoid errors during execution.”

— Wikipedia

Let’s take a look at an example. We have a function, getValidCandidate, which checks if a candidate is valid, provided a list of members and returns the member if the candidate is valid, or undefined otherwise.

Look how nested the code is? Ifs wrapping other ifs, nested 3 times. Let’s rewrite this and use guard clauses instead.

Guard clauses prevent the function from continuing what it’s doing and instead returning early if the guarding condition is not met. Naturally, we also know that the end result is the last return of the function.

Skip the ‘else’ part

Whenever you’re about to write else, stop and reconsider what you’re doing and search for an alternative way to express the logic.

Let’s cover a few ways that we can avoid using else. One of them is guard clauses, which we just covered above. Another approach is using default values. Let’s take an example.

Let’s say we have a function, negateOdd, which takes a number and negates it if the number is odd.

The function does what it’s supposed to. But it’s unnecessarily using an else. Let’s refactor it, and instead, use a default value.

We now assign result with a default value, and the variable will only be changed if the condition in the if-statement is met. But let’s do even better. We’re supposed to question the use of let and imperative (altering the state of your program step by step) code. Let’s see if we can make this function even more readable and concise.

There is a version of if-else that is generally accepted. It’s the ternary operator.

Share This:    Facebook Twitter

Friday, March 8, 2019

Javascript: Arrow functions and this

Arrow functions are anonymous; there are only arrow function expressions. You can assign arrow function expression to a variable, can be used in an IIFE as well as a callback function. Below you will find valid arrow functions:

(a, b) => a + b // implicitly returning a + b

(a, b) => {                // explicitly returning a + b
   return a + b;
}

a => a * a                // omit () when there is one parameter

() => 2                   // () mandatory when there are no parameters

(a, b) => {               // explicitly returning JS object
   return {
      a1: a, b1: b
   }
}

(a, b) => ({              // implicitly returning JS object
   a1: a, b1: b
})

An arrow function does not have its own this. this in arrow functions is always statically defined by the surrounding lexical scope.
In the example below, when using traditional function, this refers to the num object, whereas when using arrow notation, this is pointing to the global object. Arrow functions doesn't have its own this, and so this refers to outer scope, and outer scope for num object is the window object.


Even if I use call() method, result is the same.


In the below example, when using traditional function, this refers to the global object, whereas using arrow function, we get the desired result.


In order to get the greeting message using the traditional function, there are several ways to keep reference to this object inside of setTimeOut function. You can create a self variable like below:

const str = {
    value: 'Delayed greeting',
    greet: function() {
        const self = this;
        setTimeout(function() {
            console.log(self.value);
        }, 2000)
    }
};

str.greet();

or bind with this like below:

const str = {
    value: "Delayed greeting",
    greet: function() {
        setTimeout(
            function() {
                console.log(this.value);
            }.bind(this),
            2000
        );
    }
};

str.greet();

It is not possible to use arrow function expression as a function constructor and create new objects from it.
Share This:    Facebook Twitter

Sunday, January 27, 2019

Javascript: Preventing Object Modification


All objects you create are extensible by default, meaning new properties can be added to the object at any time. By setting Extensible attribute on an object to false, you can prevent new properties from being added to an object. There are three different ways to accomplish this.

Preventing Extensions

One way to create a nonextensible object is with Object.preventExtensions(). In the code below, as person1 is nonextensible, the sayName() method is never added to it.
var person1 = {
   name: "Nicholas"
};

console.log(Object.isExtensible(person1));  // true

Object.preventExtensions(person1);
console.log(Object.isExtensible(person1));  // false

person1.sayName = function() {
   console.log(this.name);
};

console.log("sayName" in person1);   // false

Sealing Objects

You can use the Object.seal() method on an object to seal it. A sealed object is nonextensible, and all of its properties are nonconfigurable. That means not only can you not add new properties to the object, but you also can’t remove properties or change their type.
var person1 = {
   name: "Nicholas"
};

console.log(Object.isExtensible(person1));  // true
console.log(Object.isSealed(person1));   // false

Object.seal(person1);
console.log(Object.isExtensible(person1));  // false
console.log(Object.isSealed(person1));   // true

person1.sayName = function() {
   console.log(this.name);
};

console.log("sayName" in person1);   // false

person1.name = "Greg";
console.log(person1.name);    // "Greg"

delete person1.name;
console.log("name" in person1);   // true
console.log(person1.name);    // "Greg"

var descriptor = Object.getOwnPropertyDescriptor(person1, "name");
console.log(descriptor.configurable);   // false

Freezing Objects

If an object is frozen, you can’t add or remove properties, you can’t change properties’ types, and you can’t write to any data properties. In essence, a frozen object is a sealed object where data properties are also read-only. Frozen objects can’t become unfrozen, so they remain in the state they were in when they became frozen.
var person1 = {
   name: "Nicholas"
};
console.log(Object.isExtensible(person1));  // true
console.log(Object.isSealed(person1));   // false
console.log(Object.isFrozen(person1));   // false

Object.freeze(person1);
console.log(Object.isExtensible(person1));  // false
console.log(Object.isSealed(person1));   // true
console.log(Object.isFrozen(person1));   // true

person1.sayName = function() {
   console.log(this.name);
};

console.log("sayName" in person1);   // false

person1.name = "Greg";
console.log(person1.name);    // "Nicholas"

delete person1.name;
console.log("name" in person1);   // true
console.log(person1.name);    // "Nicholas"

var descriptor = Object.getOwnPropertyDescriptor(person1, "name");
console.log(descriptor.configurable);   // false
console.log(descriptor.writable);   // false

Share This:    Facebook Twitter

Monday, January 21, 2019

Javascript modules, named and default exports


Take this code where we have multiple classes defined in the same file.
class Person {
  constructor(name) {
    this.name = name;
  }

  walk() {
    console.log("Walk");
  }
}


class Teacher extends Person {
  constructor(name, degree) {
    super(name);
    this.degree = degree;
  }

  teach() {
    console.log("Teach");
  }
}

const teacher = new Teacher("John", "MA");
teacher.walk();

If we can split this code across multiple files, we call it modularity, and each file is known as module. So let's modularize this code as below so that each class will be in a separate file. The objects we define in a module are private by default. To make it public, we use the export keyword, and to use it we use the import keyword.

person.js
export class Person {
  constructor(name) {
    this.name = name;
  }

  walk() {
    console.log("Walk");
  }
}

teacher.js
import { Person } from "./person";

class Teacher extends Person {
  constructor(name, degree) {
    super(name);
    this.degree = degree;
  }

  teach() {
    console.log("Teach");
  }
}

index.js
import { Teacher } from "./Person";

const teacher = new Teacher("John", "MA");
teacher.walk();

The way we have used the export keyword, we call it named exports. To use default exports, modify person.js as follows:
export default class Person {
  constructor(name) {
    this.name = name;
  }

  walk() {
    console.log("Walk");
  }
}

and in teacher.js file, import Teacher module as below:
import Person from "./person";

...
...

Share This:    Facebook Twitter

Wednesday, January 9, 2019

Javascript: Destructuring

Destructuring Objects

With destructuring, you can extract multiple pieces of data at the same time via patterns in locations that receive data.

const person = {
   first: "John",
   last: "Doe",
   links: {
      social: {
         twitter: "https://twitter.com/john.ca",
         facebook: "https://facebook.com/johndoe"
      },
      web: {
         blog: "https://johndoe.com"
      }
   }
};

const { twitter, facebook } = person.links.social;

Rename the variables as you destructure
const { twitter: tweet, facebook: fb } = person.links.social;

Set fallback or default value
const settings = { width: 300, color: "black" };
const { width = 100, height = 100, color = "blue", fontSize = 25 } = settings;

Destructuring arrays

const details = ["John Doe", 123, "johndoe.com"];
const [name, id, website] = details;
console.log(name, id, website);

Destructuring comma separated string

const data = "Basketball,Sports,90210,23,John,Doe,cool";
const [itemName, category, sku, inventory] = data.split(",");

Destructuring into Rest - an example using rest parameter

const team = ["John", "Harry", "Sarah", "Keegan", "Riker"];
const [captain, assistant, ...players] = team;

Swapping Variables with Destructuring

let inRing = "Hulk Hogan";
let onSide = "The Rock";

[inRing, onSide] = [onSide, inRing];

To make order of arguments independent, wrap these 3 arguments in , and then pass an object in tipCalc function so that it destructures the object.

function tipCalc({ total = 100, tip = 0.15, tax = 0.13 }) {
   return total + tip * total + tax * total;
}

const bill = tipCalc({ tip: 0.2, total: 200 });
console.log(bill);

What is we don't pass anything in tipcalc?

function tipCalcDefault({ total = 100, tip = 0.15, tax = 0.13 } = {}) {
   return total + tip * total + tax * total;
}

const newBill = tipCalcDefault();
console.log(newBill);
Share This:    Facebook Twitter

Javascript: Spread and Rest Operators

Rest Operator

Takes multiple things and packs it into a single array

function convertCurrency(rate, ...amounts) {
   console.log(rate, amounts); // 1.5 [10, 20, 30]
}
convertCurrency(1.5, 10, 20, 30);

Can be used while destructuring into an array

const team = ["John", "Kait", "Lux", "Sheena", "Kelly"];
const [captain, assistant, ...players] = team;
console.log(captain, assistant, players);

Spread Operator

(3 dots in-front of an array or any iterable) Takes every single item from an iterable (that can loop over with for-of loop) and spread it into a new array

const featured = ["Deep Dish", "Pepperoni", "Hawaiian"];
const specialty = ["Meatzza", "Spicy Mama", "Margherita"];

const pizzas = [...featured, "veg", ...specialty];

Using above example, creating a new array fridayPizzas

const fridayPizzas = [...pizzas];

pizzas != fridayPizzas (shallow copy)

Spread string
const name = "john";
console.log([...name]); // ["j", "o", "h", "n"]

Remove an object from an array of objects
const comments = [
   { id: 209384, text: "I love your dog!" },
   { id: 523423, text: "Cuuute! 🐐" },
   { id: 632429, text: "You are so dumb" },
   { id: 192834, text: "Nice work on this wes!" }
];
const id = 632429;
const commentIndex = comments.findIndex(comment => comment.id === id);

const newComments = [
   ...comments.slice(0, commentIndex),
   ...comments.slice(commentIndex + 1)
];
console.log(newComments);

Spreading into a function
const inventors = ["Einstein", "Newton", "Galileo"];
const newInventors = ["Musk", "Jobs"];
inventors.push(...newInventors); // and not inventors.push(newInventors);
console.log(inventors);

One more example

const name = ["John", "Doe"];

function sayHi(first, last) {
   alert(`Hey there ${first} ${last}`);
}

sayHi(...name);
Share This:    Facebook Twitter

Friday, January 4, 2019

Javascript: Execution Context


Execution Context allows the Javascript engine to manage the complexity of interpreting and running the code. Every execution context has 2 phases: Creation phase and Execution phase.

The first execution context, the Global Execution Context, gets created when the Javascript engine runs your code. In this execution context,
  • Global object gets created, which is the window object.
  • this object gets created, pointing to the window object.
  • We set up memory space for variables and functions. 
  • All the variables declarations are assigned a default value of undefined (this is hoisting), while the function declaration is put entirely into memory.
In the execution phase, Javascript starts executing your code line by line.

Invoking a function creates the Function Execution Context. It is precisely the same as the global execution context except that instead of creating a global object, an arguments object gets created. Take, for example, the code below:
function fn() {
   console.log(arguments);
}

fn(x, y);

Here arguments is an array-like object for all of the arguments passing inside of this function, and a keyword in Javascript.

Now anytime a function is invoked, a new execution context is created and added to the execution stack. Whenever a function is finished running through both the creation phase and the execution phase, it gets popped off the execution stack.

Anytime you pass a variable to a function, that variable during the creation phase of a function execution context is going to be put in the variable environment of the current execution context as if they are local variables to the execution context. So for the code below
var name = 'John';
var handle = '@johndoe';

function getURL (handle) {
   var url = 'https://facebook.com/';
   return url + handle;
}

getURL(handle);

during the creation phase of getURL function, the value of url is undefined, while the value of handle is @johndoe as the variable is passed to a function. The value of arguments object during creation phase is {0:"@johndoe", length:1}.

If the Javascript engine can't find a variable local to the function's execution context, it will look to the nearest parent execution context for that variable. This process will continue all the way up until the engine reaches the global execution context. If the global execution context doesn't have the variable, then it will throw a reference error because that variable doesn't exist anywhere up to the scope chain or the execution context chain.

var name = 'John';

function logName() {
   console.log(name);
}

logName();

Now let's look at the code below:
var count = 0;

function makeAdder(x) {
   return function inner(y) {
      return x + y;
   };
}

var add5 = makeAdder(5);
count += add5(2);

Here we have a function nested inside a function (inner inside of makeAdder), and whenever that happens, the inner function is going to create a closure over the outer function's execution context. This is because later on when inner function is invoked, it needs to have access to any of the variables declared in the parent function's execution context even though that parent function's execution context has been removed from the stack. So the variables inside of this closure execution context are same as the variables that were in the makeAdder execution context. This whole concept is known as closure.
Share This:    Facebook Twitter

Saturday, November 18, 2017

Javascript: Pattern to create instance-specific private data


To make a property private, just make it local to the constructor. Any outside code trying to access age variable will result in an undefined. But the outside code can still call the property that accesses this private variable using the public function getAge.
function Person(name) {

   // Define a variable only accessible inside of the Person constructor
   var age = 25;

   this.name = name;

   this.getAge = function() {
      return age;
   };

   this.growOlder = function() {
      age++;
   };
}

var person = new Person("Nicholas");

console.log(person.name);     // "Nicholas"
console.log(person.getAge()); // 25

person.age = 100;
console.log(person.getAge()); // 25

person.growOlder();
console.log(person.getAge()); // 26

Share This:    Facebook Twitter

Javascript: Predict the value of this argument


this is determined by the calling context, the way in which function is called.

Calling standalone functions directly

When a function is executed as a simple object function directly, this refers to the global object.
function foo() {
   console.log('Hello World!');
   console.log(this);
}

foo();


Calling functions as property of an object reference

Here we have created an object obj, and there is a property on it which is a function. The function is being called as a property on the object. Here this refers to the object obj itself.
var obj = {};

obj.foo = function() {
   console.log('Hello World!');
   console.log(this);
}

obj.foo();

Calling standalone functions using 'new' keyword

When a function is called using the new keyword, this always refer to the newly created object, an empty object.
function foo() {
   console.log('Hello World!');
   console.log(this);
}

new foo();

Share This:    Facebook Twitter

Friday, November 17, 2017

Javascript: Identifying Primitive and Reference Types


Identifying Primitive Types

There are five primitive types in JavaScript:
  • boolean
  • number
  • string
  • null
  • undefined

The best way to identify primitive types is with the typeof operator, which works on any variable and returns a string indicating the type of data.
console.log(typeof "John Doe");   // "string"
console.log(typeof 10);           // "number"
console.log(typeof 5.1);          // "number"
console.log(typeof true);         // "boolean"
console.log(typeof undefined);    // "undefined"

When you run typeof null, the result is "object". The best way to determine if a value is null is to compare it against null directly, like below. Make sure that when you’re trying to identify null, use triple equals so that you can correctly identify the type.
console.log(value === null);    // true or false

Identifying Reference Types

The built-in reference types are
  • Array
  • Date
  • Error
  • Function
  • Object
  • RegExp

A function is the easiest reference type to identify because when you use the typeof operator on a function, the operator should return "function":
function reflect(value) {
 return value;
}
console.log(typeof reflect);   // "function"

Other reference types are trickier to identify because, for all reference types other than functions, typeof returns "object". To identify reference types more easily, you can use JavaScript’s instanceof operator. The instanceof operator takes an object and a constructor as parameters. When the value is an instance of the type that the constructor specifies, instanceof returns true; otherwise, it returns false.
var items = [];
var object = {};

function reflect(value) {
 return value;
}
console.log(items instanceof Array);    // true
console.log(object instanceof Object);    // true
console.log(reflect instanceof Function);   // true

Array.isArray() is the best way to identify arrays.
var items = [];
console.log(Array.isArray(items));    // true

Share This:    Facebook Twitter

Monday, October 30, 2017

JavaScript: Module Pattern


The module pattern is an object-creation pattern designed to create singleton objects with private data. The basic approach is to use an immediately invoked function expression (IIFE) that returns an object. An IIFE is a function expression that is defined and then called immediately to produce a result. That function expression can contain any number of local variables that aren’t accessible from outside that function. Because the returned object is defined within that function, the object’s methods have access to the data. Methods that access private data in this way are called privileged methods.

Here’s the basic format for the module pattern. In this pattern, an anonymous function is created and executed immediately. (Note the extra parentheses at the end of the function. You can execute anonymous functions immediately using this syntax.) That means the function exists for just a moment, is executed, and then is destroyed.
var yourObject = (function() {

   // private data variables

   return {
      // public methods and properties
   };

}());

The below code creates the person object using the module pattern. The age variable acts like a private property for the object. It can’t be accessed directly from outside the object, but it can be used by the object methods. There are two privileged methods on the object: getAge(), which reads the value of the age variable, and growOlder(), which increments age. Both of these methods can access the variable age directly because it is defined in the outer function in which they are defined.
var person = (function() {

   var age = 25;

   return {
      name: "Nicholas",

      getAge: function() {
         return age;
      },

      growOlder: function() {
         age++;
      }
   };

}());

console.log(person.name);   // "Nicholas"
console.log(person.getAge());   // 25

person.age = 100;
console.log(person.getAge());   // 25

person.growOlder();
console.log(person.getAge());   // 26

Revealing Module Pattern

There is a variation of the module pattern called the revealing module pattern, which arranges all variables and methods at the top of the IIFE and simply assigns them to the returned object. You can write the previous example using the revealing module pattern as follows:
var person = (function() {

   var age = 25;

   function getAge() {
      return age;
   }

   function growOlder() {
      age++;
   }

   return {
      name: "Nicholas",
      getAge: getAge,
      growOlder: growOlder
   };
   
}());
In this pattern, age, getAge(), and growOlder() are all defined as local to the IIFE. The getAge() and growOlder() functions are then assigned to the returned object, effectively "revealing" them outside the IIFE.

Source: The principles of object-oriented JavaScript by Nicholas

Reference: https://coryrylan.com/blog/javascript-module-pattern-basics
Share This:    Facebook Twitter

Friday, October 20, 2017

JavaScript Prototype


Every constructor function has a property on it called prototype which is an object. This prototype object has a property on it called constructor which points back to the original constructor function.

This prototype property can have methods and properties placed on it. These methods and properties are shared and accessible like any object that is created from that constructor function when the new keyword is used. Anytime an object is created using the 'new' keyword, a property called "__proto__" gets created, linking the object and the prototype property of the constructor function.

Lets define a constructor function Person with a property called name.
function Person(name) {
    this.name = name;
}

Functions are basically objects in Javascript. So Person happens to be a function object. Now when Javascript processes functions, it creates 2 objects. The second object that gets created for every function is the prototype object. To access this prototype object, it turns out that a property by the name 'prototype' gets created on function object that points to the prototype object. So to access this property, we will type Person.prototype as below:

This applies to all functions. Now I will create two objects from the constructor function using the new keyword.
var elie = new Person("Elie");
var colt = new Person("Colt");

Since I have used new keyword, a property has been added to each of these objects called __proto__ which points to the prototype object on the Person function constructor.
var elie = new Person("Elie");
var colt = new Person("Colt");

elie.__proto__ === Person.prototype
true

To validate this, we can set a custom property on Person.prototype and try to access it from elie.__proto__
So they are pointing to the same object.

Also, the prototype object has a property on it called constructor which points back to the original function.
Person.prototype.constructor === Person
true

Now let's write some code and use prototype object.
function Person(name, age) {
   this.name = name;
   this.age = age;
}

Person.prototype.eat = function() {
   console.log('I eat');
}

Person.prototype.sleep = function() {
   console.log('I sleep');
}

var elie = new Person('Elie', 20);

Check the output below in your browser console. You will note that Javascript will first search for sleep property in the elie object. If it isn’t there, then JavaScript will search for it in the object’s prototype.

Please note that you used the new keyword to create elie object. If you had invoked the Person function simply like below:
var elie = Person('Elie', 20);

then this is how the constructor should look like:
function Person(name, age) {
   var person = Object.create(Person.prototype);
   person.name = name;
   person.age = age;
   return person;
}

As of ES6, Javascript has now a class keyword. So we can refactor the code as follows:
class Person {
   constructor(name, age) {
      this.name = name;
   this.age = age;
   }

   eat() {
      console.log(this.name + ' eats.');
   }

   sleep() {
      console.log(this.name + ' sleeps.');
   }
}

var elie = new Person('Elie', 20);

This new way is just syntactical sugar over the existing way that we saw earlier. Now let's say that we want to get the prototype of elie. So use Object.getPrototypeOf() and pass in the specific instance of the object like below:
var proto = Object.getPrototypeOf(elie);

NOTE: Arrow functions don't have their own this keyword. As a result, arrow functions cannot be constructor functions, and if you try to invoke an arrow function using new keyword, it will give you an error. And so there is no prototype property in such functions.
const person = () => {}
const elie = new Person()  // Error: Person not a constructor

Person.prototype // undefined

Share This:    Facebook Twitter

Wednesday, October 18, 2017

Callback functions in JavaScript


Synchronous operation
const posts = [
    {title: "Post One", body: "This is post one"},
    {title: "Post Two", body: "This is post two"}
];

function createPost(post) {
    setTimeout(function () {
        posts.push(post);
    }, 2000);
}

function getPosts() {
    setTimeout(function () {
        let output = "";
        posts.forEach(function (post) {
            output += `<li>${post.title}</li>`;
        });
        document.body.innerHTML = output;
    }, 1000);
}

createPost({title: "Post Three", body: "This is post three"});

getPosts();

Asynchronous operation
const posts = [
    {title: "Post One", body: "This is post one"},
    {title: "Post Two", body: "This is post two"}
];

function createPost(post, callback) {
    setTimeout(function () {
        posts.push(post);
        callback();
    }, 2000);
}

function getPosts() {
    setTimeout(function () {
        let output = "";
        posts.forEach(function (post) {
            output += `<li>${post.title}</li>`;
        });
        document.body.innerHTML = output;
    }, 1000);
}

createPost({title: "Post Three", body: "This is post three"}, getPosts);

References:
http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/
https://houssein.me/javascript/2016/05/10/asynchronous-javascript-callbacks.html
http://callbackhell.com/
https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
Share This:    Facebook Twitter

Friday, August 25, 2017

Javascript Accessor Properties

There are two different types of properties: data properties and accessor properties.

  • Data properties contain a value.
  • Accessor properties don’t contain a value but instead define a getter function and a setter function.
const person1 = {
   _name: "Nicholas",

   get name() {
      console.log("Reading name");
      return this._name;
   },

   set name(value) {
      console.log("Setting name to %s", value);
      this._name = value;
   }
};

console.log(person1.name);   // "Reading name" then "Nicholas"

person1.name = "Greg";
console.log(person1.name);   // "Setting name to Greg" then "Greg"

This example defines an accessor property called name. There is a data property called _name that contains the actual value for the property.

The leading underscore is a common convention to indicate that the property is considered to be private, though in reality it is still public. The syntax used to define the getter and setter for name looks a lot like a function but without the function keyword. The special keywords get and set are used before the accessor property name, followed by parentheses and a function body.

Share This:    Facebook Twitter

Javascript Object properties

Detecting Properties

The in operator looks for a property with a given name in a specific object and returns true if it finds it.

console.log("name" in person1);   // true
console.log("age" in person1);    // true
console.log("title" in person1);  // false

Keep in mind that methods are just properties that reference functions, so you can check for the existence of a method in the same way.

const person1 = {
   name: "Nicholas",
   sayName: function() {
      console.log(this.name);
   }
};

console.log("sayName" in person1);  // true

In some cases, however, you might want to check for the existence of a property only if it is an own property. The in operator checks for both own properties and prototype properties, so you’ll need to take a different approach. Enter the hasOwnProperty() method, which is present on all objects and returns true only if the given property exists and is an own property.

const person1 = {
   name: "Nicholas",
   sayName: function() {
      console.log(this.name);
   }
};

console.log("name" in person1);                         // true
console.log(person1.hasOwnProperty("name"));            // true

console.log("toString" in person1);                     // true
console.log(person1.hasOwnProperty("toString"));        // false

Removing Properties

You need to use the delete operator to completely remove a property from an object.

const person1 = {
   name: "Nicholas"
};

console.log("name" in person1);  // true

delete person1.name;             // true - not output
console.log("name" in person1);  // false
console.log(person1.name);       // undefined

Enumeration

By default, all properties that you add to an object are enumerable, which means that you can iterate over them using a for-in loop. This example uses bracket notation to retrieve the value of the object property and output it to the console, which is one of the primary use cases for bracket notation in JavaScript.

var property;

for (property in object) {
   console.log("Name: " + property);
   console.log("Value: " + object[property]);
}

If you just need a list of an object’s properties, use Object.keys() method to retrieve an array of enumerable property names. Typically, you would use Object.keys() in situations where you want to operate on an array of property names and for-in when you don’t need an array.

var properties = Object.keys(object);

// if you want to mimic for-in behavior
var i, len;

for (i=0, len=properties.length; i < len; i++){
   console.log("Name: " + properties[i]);
   console.log("Value: " + object[properties[i]]);
}

Keep in mind that not all properties are enumerable. You can check whether a property is enumerable by using the propertyIsEnumerable() method, which is present on every object:

var person1 = {
   name: "Nicholas"
};

console.log("name" in person1);    // true
console.log(person1.propertyIsEnumerable("name"));  // true

var properties = Object.keys(person1);

console.log("length" in properties);    // true
console.log(properties.propertyIsEnumerable("length")); // false
Share This:    Facebook Twitter

Sunday, April 2, 2017

Javascript: Functions


There are actually two literal forms of functions. The first is a function declaration, which begins with the function keyword and includes the name of the function immediately following it.
function add(num1, num2) {
   return num1 + num2;
}

The second form is a function expression, which doesn’t require a name after function. These functions are considered anonymous because the function object itself has no name. Instead, function expressions are typically referenced via a variable or property, as in this expression:
var add = function(num1, num2) {
   return num1 + num2;
};

Function hoisting

Function declarations are hoisted to the top of the context when the code is executed. That means you can actually define a function after it is used in code without generating an error.
var result = add(5, 5);

function add(num1, num2) {
   return num1 + num2;
}

Function hoisting happens only for function declarations because the function name is known ahead of time. Function expressions, on the other hand, cannot be hoisted because the functions can be referenced only through a variable. So this code causes an error:
// error!
var result = add(5, 5);

var add = function(num1, num2) {
   return num1 + num2;
};

Functions as Values

function sayHi() {
   console.log("Hi!");
}

sayHi(); // outputs "Hi!"

var sayHi2 = sayHi;

sayHi2(); // outputs "Hi!"

Parameters

You can pass any number of parameters to any function without causing an error. That’s because function parameters are actually stored as an array-like structure called arguments. The values are referenced via numeric indices, and there is a length property to determine how many values are present.
function sum() {

   var result = 0,
   i = 0,
   len = arguments.length;

   while (i < len) {
      result += arguments[i];
      i++;
   }
 
   return result;
}

console.log(sum(1, 2));       // 3
console.log(sum(3, 4, 5, 6)); // 18
console.log(sum(50));         // 50
console.log(sum());           // 0

Overloading

The fact that functions don’t have signatures in JavaScript doesn’t mean you can’t mimic function overloading. You can retrieve the number of parameters that were passed in by using the arguments object, and you can use that information to determine what to do.
function sayMessage(message) {

   if (arguments.length === 0) {
      message = "Default message";
   }

   console.log(message);
}

sayMessage("Hello!");    // outputs "Hello!"

Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top