Cribsheet for JavaScript Coding Interview

The coding interviews / coding challenges are designed to assess how productive someone can be with the language. In contrast to the algorithm whiteboarding interview, which assesses how the candidate go about solving a problem, or the architecture design interview, which assesses how the candidate’s experience in system engineering and product design, the coding interview is is utilized by the company interviewing you to answer one question:

The coding interviews / coding challenges are designed to assess how productive someone can be with the language. In contrast to the algorithm whiteboarding interview, which assesses how the candidate go about solving a problem, or the architecture design interview, which assesses how the candidate’s experience in system engineering and product design, the coding interview is is utilized by the company interviewing you to answer one question:

Can you be productive with JavaScript?
You are usually given the flexibility of choosing the language you are most comfortable with to complete the coding challenge. Thus it’s expected you know how to take advantage of all the language specific features and deal with the language specific idiosyncrasies (JavaScript has a lot) to solve problems.

These tests are also designed to gauge your knowledge of computer science fundamentals like various data structures (e.g., arrays, strings, object/dictionaries), logic building blocks (e.g., loops, if-statements, functions), and problem solving patterns (e.g., recursion, pattern matching, higher order functions).

For coding challenges, there’s always a time limit. The faster you can solve a problem correctly, the better. Thus, this post introduces JavaScript features, best practices, to leverage and common pitfalls to avoid to help you get productive with JavaScript and get the right result quickly.

Working with Strings

Regex

In a nutshell, regular expression, or regex for short, are patterns you specify to test a string. There are whole books written about Regexes. We are going to focus on the most likely problem we’re going to need to solve with regex during a coding challenge:

Does the string contain this pattern? If so, how many times does this pattern appear? Where does it appear?
Let’s consider this coding challenge:
Given a string, determine if the string is a url.
We can assume we only want to test for websites with the .com and .org top level domains. We don’t care if the website actually exists or not.

Input and expected output:

  • “google.com” → true
  • “www.icann.org" → true
  • “google.foobar” → false
const isStrUrl = str => {
  const matchTld = /(\.com|\.org)$/i
  return matchTld.test(str);
};

The matchTld is the regex that specifies that we are looking for a string that ends with .com or .org. The \. escapes the dot (.). The ```The coding interviews / coding challenges are designed to assess how productive someone can be with the language. In contrast to the algorithm whiteboarding interview, which assesses how the candidate go about solving a problem, or the architecture design interview, which assesses how the candidate’s experience in system engineering and product design, the coding interview is is utilized by the company interviewing you to answer one question:

Can you be productive with JavaScript?
You are usually given the flexibility of choosing the language you are most comfortable with to complete the coding challenge. Thus it’s expected you know how to take advantage of all the language specific features and deal with the language specific idiosyncrasies (JavaScript has a lot) to solve problems.

These tests are also designed to gauge your knowledge of computer science fundamentals like various data structures (e.g., arrays, strings, object/dictionaries), logic building blocks (e.g., loops, if-statements, functions), and problem solving patterns (e.g., recursion, pattern matching, higher order functions).

For coding challenges, there’s always a time limit. The faster you can solve a problem correctly, the better. Thus, this post introduces JavaScript features, best practices, to leverage and common pitfalls to avoid to help you get productive with JavaScript and get the right result quickly.

Working with Strings

Regex

In a nutshell, regular expression, or regex for short, are patterns you specify to test a string. There are whole books written about Regexes. We are going to focus on the most likely problem we’re going to need to solve with regex during a coding challenge:

Does the string contain this pattern? If so, how many times does this pattern appear? Where does it appear?
Let’s consider this coding challenge:
Given a string, determine if the string is a url.
We can assume we only want to test for websites with the .com and .org top level domains. We don’t care if the website actually exists or not.

Input and expected output:

  • “google.com” → true
  • “www.icann.org" → true
  • “google.foobar” → false
const isStrUrl = str => {
  const matchTld = /(\.com|\.org)$/i
  return matchTld.test(str);
};

The matchTld is the regex that specifies that we are looking for a string that ends with .com or .org. The \. escapes the dot (.). The `` at the end of the regex means this pattern should appear at the end of the string. In summary:

const matchApple = /^apple$/
matchApple.test(‘apple’); //> true
matchApple.test(‘orange’); //> false
matchApple.test(‘apples’); //> false
matchApple.test(‘Apple’); //> false

As illustrated with the above example, regex is case sensitive.

If you want to match a sequence of characters regardless of whether the letters are upper case or lower case, you could convert every letter in the string to lowercase, then do the pattern matching:

const str = ‘Apple’.toLowerCase();
matchApple.test(str); //> true

String manipulation

Suppose we have a string containing alphanumeric characters sprinkled with some illegal characters, in particular, angle brackets, forward slash, backward slash, and quote. We want to remove the illegal characters and retain just the letters. How would we go about this string manipulation?

Using regex:

const dirtyStr = "<script>window.location=\"http://evil.com\"</script>";
const matchIllegals = /<|>|\\|\/|"/g;
const cleanStr = dirtyStr.replace(matchIllegals, "");
console.log(cleanStr); //> scriptwindow.location=http:evil.comscript

We are using the JavaScript built-in function for string, i.e., replace, to replace every angle bracket, slash, and quote in the string with empty string, effectively removing them from the string.

Get Characters from String

str.chartAt(i) gives us the character at a index i from str.

let str = 'hello'
str.charAt(0) //> 'h'
str.charAt(str.length-1) //> 'o'
str.charAt(str.length) //> ''

What happens if we do the following?

str.charAt(str.length) //> ''

It returns an empty string! You don’t get any help like the index out of bounds error that people who work with a statically typed language with a compiler like Java would be familiar with. This could be a really nasty bug. A similar thing happens with arrays when you access an index out of bound array element: arr[arr.length] gives you undefined.

Getting Multiple Characters (Substrings)

Say we have “hello world” as our string but we only want “world”. What do we do? Slice recursively. “hello” plus space is 6 characters.

“hello world”.slice(6) //> “world”

Using slice works because a string is really just an array of characters.

A more general function for obtaining the substring is appropriately called substring and it takes two arguments: where to start (inclusive) and where to stop (exclusive). Here’s how you use substring:

'hello'.substring(0, 2); //> 'he'

However, using slice and substring for extracting the sub-string requires knowing exactly where is the starting index is. Usually, the substring we want to extract are delimited by a space or a special character such as a slash. Suppose we have the following problem:

Get the username from the Medium url for user profile.
Usually, webpages for user profile pages on social networking websites have the following form:

https://<domainName>/<route>/<username>

What we want is the username at the end. SincedomainName and route could be arbitrarily long, we can’t use slice to solve our problem. What we can do is this:

const getUsername = url => {
  return url.split(‘/’).pop().slice(1);
};
getUsername('https://medium.com/@xiaoyunyang') //> xiaoyunyang

getUsername function has a one-liner solution but there are few things going on:

  1. split('/') splits the url string into an array of substrings using the slash (/) as delimiter. The output of the split('/') operated on our example url becomes [ 'https:', '', 'medium.com', '@xiaoyunyang' ], which gets piped into the next operation pop().
  2. pop() is a built-in function for arrays we will discuss later. What it does is it returns the last element of the array and in the process, mutating the original array. pop() could get us in hot water (we will discuss later in the arrays section) because it’s mutating the original array but in this case, it’s okay because the array we got from split is an intermediate throw-away data structure that we are only using for deriving the final result. The pop() operation gives us @xiaoyunyang, which we pipe into the next operation.
  3. slice(1), as discussed above, returns the substring starting from index 1 until the end of the array. This effectively chops off the @ and gives us xiaoyunyang, which is the username.

Working with Arrays

When we work with arrays in JavaScript, we have a whole suite of built-in functions we can use. This section discusses those functions that returns arrays or mutates the original array. A later section will discuss how to use JavaScript built-in functions for arrays to transform the array to other data types.

Add things to an array and combine arrays

Mutable

  • array.push(elem) — adds elem to the end of array
  • array.unshift(elem) — adds elem to the beginning of array

Example:

const mutatingAdd = [1, 2, 3];
mutatingAdd.push(4); //> [1, 2, 3, 4]
mutatingAdd.unshift(0); //> [0, 1, 2, 3, 4]
console.log(mutatingArr); //> [0, 1, 2, 3, 4]

Immutable

  • array.concat(elem) — adds elem to the front or back of an array without mutating the original array
  • [...arr1, …arr2] — ES6 Spread operator to merge two arrays
  • [elem, ...arr2] — ES6 add elem to head of the array
  • [...arr1, elem] — ES6 add elem to tail of the array

Example with concat:

const arr0 = [0];
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = arr1.concat(arr2); //> [1, 2, 3, 4]
const arr4 = arr0.concat(arr3); //> [0, 1, 2]
const arr5 = arr0.concat(arr1, arr2) //> [0, 1, 2, 3, 4]

Example with spread operator

const arr0 = [0];
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [...arr1, ...arr2]; //> [1, 2, 3, 4]
const arr4 = [...arr0, ...arr1]; //> [0, 1, 2]
const arr4_altern = [0, ...arr1]; //> [0, 1, 2]
const arr5 = [...arr0, ...arr1, ...arr2]; //> [0, 1, 2, 3, 4]

Extract and remove things from an array

We can access elements in the array using the index. This pattern is commonly used in many other programming elements. This section goes into more details about how to take advantage of JavaScript-specific built-in function to speed up problem solving.

A common thing we need to do with arrays is to remove the last thing in the array. Since the goal is to mutate the original array, one convenient function helps us do exactly that:

array.splice(-1) — return the tail of array as an array and mutates array.

Example:

const arr = [0, 1, 2];
const tailArr = arr.splice(-1);
console.log(tailArr) //> [2]
console.log(arr) //> [0, 1]

One gotcha with using splice in this way is arr.splice(-1) returns the tail element of arr wrapped in an array. If you just want elem, you can use ES6 destructuring:

const [tail] = tailArr;
console.log(tail); //> 2

Unfortunately, ES6 destructuring does not support extraction of last element of an array. However, ES6 destructuring and rest operator is very useful for returning the head of the array as elem instead of an array containing an elem without mutating the rest of the array:

const arr = [0, 1, 2];
const [head, ...rest] = arr;
console.log(head); //> 0
console.log(rest); //> [1, 2]
console.log(arr); //> [0, 1, 2]

In fact, you can use ES6 destructuring to get extract more than one elements from the array starting from the head of the array:

const arr = [0, 1, 2, 3, 4, 5];
const [first, second, third, ...rest] = arr;

If you just want to return the last element of the array without mutating the original array, we can use arr.slice(-1):

const arr = [0, 1, 2];
const tailArr = arr.slice(-1);
console.log(tailArr); //> [2]
console.log(arr); //> [0, 1, 2]

slice and splice are useful for extracting any part of the array, not just the tail. The general way you use these functions is arr.slice(from, until) and arr.splice(from, until) where from and until are indices. The sub-array returned from these operations includes the element at index from until the element that precedes index until. For example:

const numbers = [0, 1, 2, 3, 4];
const lessThanThree = numbers.slice(0, 3); //> [0, 1, 2]
const moreThanTwo = numbers.splice(2, numbers.length); //> [2, 3, 4]
console.log(numbers); //> [0, 1]

Beware! If you reversed the order in which you use slice and splice, in the code above, the code will not have any run-time errors but you’re going to have some nasty logic bugs:

const numbers = [0, 1, 2, 3, 4];
const moreThanTwo = numbers.splice(2, numbers.length); //> [2, 3, 4]
const lessThanThree = numbers.slice(0, 3); //> [0, 1]
console.log(lessThanThree); //> [0, 1] …not [0, 1, 2] as we expect

Therefore, when you are trying to quickly solve a programming problem correctly, be absolutely disciplined about using immutable functions like slice and ES6 destructuring so you’re not spending 10 minutes of your 30 minute coding challenge time debugging this bug.

Sorting things in Array

Suppose we have the following numbers we would like to sort:

const nums = [3, 2, 7, 1, 2, 0];

Sort in ascending order:

nums.sort((a,b) => {
  return a-b
});
console.log(nums); //> [ 0, 1, 2, 2, 3, 7 ]

Sort in descending order

nums.sort((a,b) => {
  return b-a
})
console.log(nums); //> [ 7, 3, 2, 2, 1, 0 ]

It’s important note that the sort function mutates the original array!

If you don’t pass in a function, sort will by default give you the mutated array in ascending order.

const letters = ['c', 'r', 'a', 'b', 'a', 't']
letters.sort()
letters //> [ 'a', 'a', 'b', 'c', 'r', 't' ]

Working with Objects

JavaScript Objects are used to store key-value pairs and can nest other objects as deep as you want. In JavaScript, arrays are actually objects where the keys are numbers. I can make an array using an object notation:

const arr1 = {
  0: 0,
  1: 1,
  2: 2
}
const arr2 = [0, 1, 2];

The syntax I use to access the elements from the object and array are indistinguishable:

arr1[1] //> 1
arr2[1] //> 1

This is how I remember the rules for accessing the value of an object using the key — it looks just like the way you access the element of an array at a given index!

const basket = {
  'apple': 1,
  'pear': 2
};
const numApple = basket['apple']; //> 1
const numPear = basket['pear']; //> 2

Size of object

Object.keys(dict).length gives you the number of entries in the object called dict (short for dictionary).

For example:

let basket = {};
Object.keys(basket).length; // 0
basket = {apple: 2}
Object.keys(basket).length; // 1

Merging two objects

Use spread operator.

There’s a more verbose way of doing it but we are using ES6’s spread operator here:

const foo = {a: 'a', b: 'b'}
const bar = {c: 'c', d: 'd'}
const foobar = {...foo, ...bar} //> {a: 'a', b: 'b', c: 'c', d: 'd'}

you can also use the spread operator to make a deep copy of the object.

const foobarCpy = {...foobar} //> {a: 'a', b: 'b', c: 'c', d: 'd'}

Consistent with the tip above for preferring slice over splice for array operations, we want to err on the side of immutability. We want to make deep copies of things before we start changing things in arrays and objects to avoid nasty bugs and side effects. Assigning objects to another variable does not make a copy of the object, rather, it creates a new reference to the original object:

const basket = {
  apple: 1,
  pear: 2
};
basket2 = basket;
basketCpy = {...basket};
console.log(basket === basket2); //> true
console.log(basket === basketCpy); //> false

Add and remove things from object

Add to object (functional way):

const addToDict = (dict, newKey, newVal) => {
  if (dict[newKey]) return dict;
  const newDict = {...dict};
  newDict[newKey] = newVal;
  return newDict;
};

Delete from object (functional way):

const deleteFromDict = (dict, newKey, newVal) => {
  if (!dict[key]) return dict;
  const newDict = {…dict};
  newDict[key] = newVal;
  return newDict;
};

Sometimes for performance reasons, it’s desirable to add/delete from object by mutating the object:

const foobar = {'foo': 'foo', 'bar': 'bar'};
delete foobar['bar'];
foobar['baz'] = 'baz';
console.log(foobar); //> { foo: 'foo', baz: 'baz' }

Compare two objects

What if you have two dictionaries and you want to see if they are equal? The trick is to use JSON.stringify.

let dict1 = {};
dict1['a'] = 1;
dict1['b'] = 2;
let dict2 = {};
dict2['a'] = 1;
dict2[“b”] = 2;
JSON.stringify(dict1) === JSON.stringify(dict2); //> true
dict1['a'] = 2;
JSON.stringify(dict1) === JSON.stringify(dict2); //> false

Making A Deep Copy of Object

Once again the trick is to use JSON.stringify along with JSON.parse.

const makeDeepCopy = obj => {
  return JSON.parse(JSON.stringify(obj))
}

# Conversion Between Data Types

We can use functions to transform between these data types as depicted in the graph below:

Generating a Random Number

The following function returns a random number between min (inclusive) and max (exclusive):

function getRandomNumber(min, max) {
  return Math.random() * (max — min) + min;
}

If we want to generate a random integer between min (inclusive) and max (exclusive):

function getRandomInteger(min, max) {
  return Math.floor(Math.random() * (max — min)) + min;
}

Shortcuts

Initialize Array

let arr = Array(10);
console.log(arr); //> [ <10 empty items> ]

Find Max

const arr = [1, 2, 3];
Math.max(...arr)

There’s a few gotchas associated with Math.max. Consider if you have an array in which contains null or undefined:

console.log(Math.max(...[null, null])); //> 0
console.log(Math.max(...[null, 1])); //> 1
console.log(Math.max(...[undefined, undefined])); //> NaN
console.log(Math.max(...[undefined, null, 1])); //> NaN

Empty elements in the array is the same as undefined:

const foo = Array(3);
foo[0] = 2;
console.log(Math.max(...foo)) //> NaN

Generating a sequence

const indices = Array.from(Array(10).keys());
console.log(indices); //> (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Use Splice to insert into array

Let’s write a function that insert a new element into a sorted array. splice is very handy in this situation.

function insertIntoSorted(newItem, sortedItems) {
  let arr = sortedItems
  for(let i in arr) {
    let curr = arr[i];
    if(newItem<curr) {
      arr.splice(i, 0, newItem);
      return arr;
    }
}

Optional Parameter

ES6 shortcut using default value:

function foo(fruit='apple') {
  let toPrint = fruit
  console.log('word:', toPrint)
}

As opposed to the old way of doing it using ternary operator:

function foo(fruit) {
  let toPrint = fruit ? fruit : 'apple'
  console.log('word:', toPrint)
}

Quickly convert string to number

Prepending + to the string is a shorthand for converting the string to a number.

const [a, b, c] = [+'1', +'1.5', +'foo']
console.log(a); //> 1
console.log(b); //> 1.5
console.log(c); //> NaN

Different kinds of loop

Suppose we have the following data we want to loop through:

let colors = ['red', 'blue', 'green', 'purple', 'yellow'];

We could do a simple for-loop:

for(let i=0; i<colors.length; i++) {
  console.log(colors[i]);
}

There’s a less verbose way of achieving the same thing:

for(let i in colors) {
  console.log(colors[i]);
}

If we don’t are about the index but just the value, we could use forEach:

colors.forEach(color => {
  console.log(color)
});

For some algorithms, we may need to use the while-loop:

while(colors.length > 0) {
  let color = colors.shift();
  console.log(color);
}

Note, the while-loop operation above mutates the original array!

To loop through an object, we could do the following:

let keycodeMapping = {
  65: 'a',
  66: 'b',
  187: '=',
  191: '/'
};
Object.keys(keycodeMapping).forEach(key => {
  console.log('keycode, value:', key, keycodeMapping[key]);
});

More Study material for JavaScript interviews

  • Coding Challenges and Solutions — GitHub repo updated frequently with algorithm problems from Cracking the Coding Interview, Leetcode, and actual coding interviews.

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20

How to Retrieve full Profile of LinkedIn User using Javascript

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Here we are fetching LinkedIn data like Username, Email and other fields using JavaScript SDK.

Here we have 2 workarounds.

  1. Configuration of linkedIn developer api
  2. Javascript Code to fetch records

Configuration of linkedIn developer api

In order to fetch records, first we need to create developer api in linkedin which will act as token/identity while fetching data from other linkedin accounts.

So to create api, navigate to https://linkedin.com/developer/apps and click on 'Create Application'.

After navigating, fill in details like name, description and other required fields and then submit.

As we submit, it will create Client ID and Client Secret shown below, which we will be using in our code while communicating to fetch records from other LinkedIn account.

Note: We need to provide localhost Url here under Oauth 2.0. I am using my localhost, but you can probably use other production URLs under Oauth 2.0 where your app is configured. It will make your api  consider the Url as trusted which fetching records.

Javascript Code to fetch records

For getting user details like first name, last name,User image can be written as,

<script type="text/javascript" src="https://platform.linkedin.com/in.js">  
    api_key: XXXXXXX //Client ID  
    onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
    authorize: true  
</script>  
<script type="text/javascript">  
    function OnLinkedInFrameworkLoad() {  
        IN.Event.on(IN, "auth", OnLinkedInAuth);  
    }  
  
    function OnLinkedInAuth() {  
        IN.API.Profile("me").result(ShowProfileData);  
    }  
  
    function ShowProfileData(profiles) {  
        var member = profiles.values[0];  
        var id = member.id;  
        var firstName = member.firstName;  
        var lastName = member.lastName;  
        var photo = member.pictureUrl;  
        var headline = member.headline;  
        //use information captured above  
        var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: " + lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline + "<p/>"  
        document.getElementById('profiles').innerHTML = stringToBind;  
    }  
</script>    

Kindly note we need to include 'https://platform.linkedin.com/in.js' as src under script type as it will act on this Javascript SDK provided by Linkedin.

In the same way we can also fetch records of any organization with the companyid as keyword.

<head>  
    <script type="text/javascript" src="https://platform.linkedin.com/in.js">  
        api_key: XXXXXXX ////Client ID  
        onLoad: onLinkedInLoad  
        authorize: true  
    </script>  
</head>  
  
<body>  
    <div id="displayUpdates"></div>  
    <script type="text/javascript">  
        function onLinkedInLoad() {  
            IN.Event.on(IN, "auth", onLinkedInAuth);  
            console.log("On auth");  
        }  
  
        function onLinkedInAuth() {  
            var cpnyID = XXXXX; //the Company ID for which we want updates  
            IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=10&format=json").result(displayCompanyUpdates);  
            console.log("After auth");  
        }  
  
        function displayCompanyUpdates(result) {  
            var div = document.getElementById("displayUpdates");  
            var el = "<ul>";  
            var resValues = result.values;  
            for (var i in resValues) {  
                var share = resValues[i].updateContent.companyStatusUpdate.share;  
                var isContent = share.content;  
                var isTitled = isContent,  
                    isLinked = isContent,  
                    isDescription = isContent,  
                    isThumbnail = isContent,  
                    isComment = isContent;  
                if (isTitled) {  
                    var title = isContent.title;  
                } else {  
                    var title = "News headline";  
                }  
                var comment = share.comment;  
                if (isLinked) {  
                    var link = isContent.shortenedUrl;  
                } else {  
                    var link = "#";  
                }  
                if (isDescription) {  
                    var description = isContent.description;  
                } else {  
                    var description = "No description";  
                }  
                /* 
                if (isThumbnailz) { 
                var thumbnailUrl = isContent.thumbnailUrl; 
                } else { 
                var thumbnailUrl = "http://placehold.it/60x60"; 
                } 
                */  
                if (share) {  
                    var content = "<a target='_blank' href=" + link + ">" + comment + "</a><br>";  
                    //el += "<li><img src='" + thumbnailUrl + "' alt=''>" + content + "</li>";  
                    el += "<li><div>" + content + "</div></li>";  
                }  
                console.log(share);  
            }  
            el += "</ul>";  
            document.getElementById("displayUpdates").innerHTML = el;  
        }  
    </script>  
</body>  

We can get multiple metadata while fetching records for any any organization. We can get company updates as shown below.

Conclusion

We can also fetch any company specific data like company job updates/post, total likes, comments, and number of views along with a lot of metadata we can fetch which I have shown below.

Thank you for reading !

7 Best Javascript Iframe Libraries

7 Best Javascript Iframe Libraries

Iframes let you build user experiences into embeddable ‘cross-domain components’, which let users interact with other sites without being redirected. I have compiled 7 best Javascript iframe libraries.

Iframes let you build user experiences into embeddable ‘cross-domain components’, which let users interact with other sites without being redirected. I have compiled 7 best Javascript iframe libraries.

1. Zoid

A cross-domain component toolkit, supporting:

  • Render an iframe or popup on a different domain, and pass down props, including objects and functions
  • Call callbacks natively from the child window without worrying about post-messaging or cross-domain restrictions
  • Create and expose components to share functionality from your site to others!
  • Render your component directly as a React, Vue or Angular component!
    It's 'data-down, actions up' style components, but 100% cross-domain using iframes and popups!

Download


2. Postmate

Postmate is a promise-based API built on postMessage. It allows a parent page to speak with a child iFrame across origins with minimal effort.

Download


3. Iframe Resizer

Keep same and cross domain iFrames sized to their content with support for window/content resizing, in page links, nesting and multiple iFrames

Demo

Download


4. Iframely

Embed proxy. Supports over 1800 domains via custom parsers, oEmbed, Twitter Cards and Open Graph

Demo

Download


5. React Frame component

This component allows you to encapsulate your entire React application or per component in an iFrame.

Demo

Download


6. Seamless.js

A seamless iframe makes it so that visitors are unable to distinguish between content within the iframe and content beside the iframe. Seamless.js is a JavaScript library (with no dependencies) that makes working with iframes easy by doing all the seamless stuff for you automatically.

Demo

Download


7. Porthole

A proxy to safely communicate to cross-domain iframes in javascript

Demo

Download


Thank for read!