Build WAI-ARIA compliant React autocomplete components

Build WAI-ARIA compliant React autocomplete components

Primitives to build simple, flexible, WAI-ARIA compliant React autocomplete/dropdown/select/combobox components

downshift

Primitives to build simple, flexible, WAI-ARIA compliant React autocomplete/dropdown/select/combobox components

The problem

You need an autocomplete/dropdown/select experience in your application and you want it to be accessible. You also want it to be simple and flexible to account for your use cases.

This solution

This is a component that controls user interactions and state for you so you can create autocomplete/dropdown/select/etc. components. It uses a render prop which gives you maximum flexibility with a minimal API because you are responsible for the rendering of everything and you simply apply props to what you're rendering.

This differs from other solutions which render things for their use case and then expose many options to allow for extensibility resulting in a bigger API that is less flexible as well as making the implementation more complicated and harder to contribute to.

Installation
This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install --save downshift

Usage
import Downshift from 'downshift'

function BasicAutocomplete({items, onChange}) {
  return (
    <Downshift
      onChange={onChange}
      render={({
        getInputProps,
        getItemProps,
        isOpen,
        inputValue,
        selectedItem,
        highlightedIndex,
      }) => (
        <div>
          <input {...getInputProps({placeholder: 'Favorite fruit ?'})} />
          {isOpen ? (
            <div style={{border: '1px solid #ccc'}}>
              {items
                .filter(
                  i =>
                    !inputValue ||
                    i.toLowerCase().includes(inputValue.toLowerCase()),
                )
                .map((item, index) => (
                  <div
                    {...getItemProps({item})}
                    key={item}
                    style={{
                      backgroundColor:
                        highlightedIndex === index ? 'gray' : 'white',
                      fontWeight: selectedItem === item ? 'bold' : 'normal',
                    }}
                  >
                    {item}
                  </div>
                ))}
            </div>
          ) : null}
        </div>
      )}
    />
  )
}

function App() {
  return (
    <BasicAutocomplete
      items={['apple', 'orange', 'carrot']}
      onChange={selectedItem => console.log(selectedItem)}
    />
  )
}

downshift is the only component. It doesn't render anything itself, it just
calls the render function and renders that. ["Use a render
prop!"][use-a-render-prop]! <Downshift render={/* your JSX here! */} />.

Props

defaultSelectedItem

any | defaults to null

Pass an item or an array of items that should be selected by default.

defaultHighlightedIndex

number/null | defaults to null

This is the initial index to highlight when the menu first opens.

defaultInputValue

string | defaults to ''

This is the initial input value.

defaultIsOpen

boolean | defaults to false

This is the initial isOpen value.

itemToString

function(item: any) | defaults to: i => (i == null ? '' : String(i))

Used to determine the string value for the selected item (which is used to
compute the inputValue).

selectedItemChanged

function(prevItem: any, item: any) | defaults to: (prevItem, item) => (prevItem !== item)

Used to determine if the new selectedItem has changed compared to the previous
selectedItem and properly update Downshift's internal state.

getA11yStatusMessage

function({/* see below */}) | default messages provided in English

This function is passed as props to a Status component nested within and
allows you to create your own assertive ARIA statuses.

A default getA11yStatusMessage function is provided that will check
resultCount and return "No results." or if there are results but no item is
highlighted, "resultCount results are available, use up and down arrow keys to
navigate." If an item is highlighted it will run itemToString(highlightedItem)
and display the value of the highlightedItem.

The object you are passed to generate your status message has the following
properties:

property type description
highlightedIndex number/null The currently highlighted index
highlightedItem any The value of the highlighted item
inputValue string The current input value
isOpen boolean The isOpen state
itemToString function(any) The itemToString function (see props) for getting the string value from one of the options
previousResultCount number The total items showing in the dropdown the last time the status was updated
resultCount number The total items showing in the dropdown
selectedItem any The value of the currently selected item

onChange

function(selectedItem: any, stateAndHelpers: object) | optional, no useful
default

Called when the user selects an item and the selected item has changed. Called
with the item that was selected and the new state of downshift. (see
onStateChange for more info on stateAndHelpers).

  • selectedItem: The item that was just selected
  • stateAndHelpers: This is the same thing your render prop function is
    called with (see Render Prop Function)

onSelect

function(selectedItem: any, stateAndHelpers: object) | optional, no useful
default

Called when the user selects an item, regardless of the previous selected item.
Called with the item that was selected and the new state of downshift. (see
onStateChange for more info on stateAndHelpers).

  • selectedItem: The item that was just selected
  • stateAndHelpers: This is the same thing your render prop function is
    called with (see Render Prop Function)

onStateChange

function(changes: object, stateAndHelpers: object) | optional, no useful
default

This function is called anytime the internal state changes. This can be useful
if you're using downshift as a "controlled" component, where you manage some or
all of the state (e.g. isOpen, selectedItem, highlightedIndex, etc) and then
pass it as props, rather than letting downshift control all its state itself.
The parameters both take the shape of internal state ({highlightedIndex: number, inputValue: string, isOpen: boolean, selectedItem: any}) but differ
slightly.

  • changes: These are the properties that actually have changed since the last
    state change. This also has a type property which you can learn more about
    in the stateChangeTypes section.
  • stateAndHelpers: This is the exact same thing your render prop function is
    called with (see Render Prop Function)

Tip: This function will be called any time any state is changed. The best
way to determine whether any particular state was changed, you can use
changes.hasOwnProperty('propName').

stateReducer

function(state: object, changes: object) | optional

🚨 This is a really handy power feature 🚨

This function will be called each time downshift sets its internal state
(or calls your onStateChange handler for control props). It allows you to
modify the state change that will take place which can give you fine grain
control over how the component interacts with user updates without having to
use Control Props. It gives you the current state and the
state that will be set, and you return the state that you want to set.

  • state: The full current state of downshift.
  • changes: These are the properties that are about to change. This also has a
    type property which you can learn more about in the
    stateChangeTypes section.
const ui = (
  <Downshift stateReducer={stateReducer}>{/* your callback */}</Downshift>
)

function stateReducer(state, changes) {
  // this prevents the menu from being closed when the user
  // selects an item with a keyboard or mouse
  switch (changes.type) {
    case Downshift.stateChangeTypes.keyDownEnter:
    case Downshift.stateChangeTypes.clickItem:
      return {
        ...changes,
        isOpen: state.isOpen,
        highlightedIndex: state.highlightedIndex,
      }
    default:
      return changes
  }
}

onInputValueChange

function(inputValue: string, stateAndHelpers: object) | optional, no useful
default

Called whenever the input value changes. Useful to use instead or in combination
of onStateChange when inputValue is a controlled prop to
avoid issues with cursor positions.

  • inputValue: The current value of the input
  • stateAndHelpers: This is the same thing your render prop function is
    called with (see Render Prop Function)

itemCount

number | optional, defaults the number of times you call getItemProps

This is useful if you're using some kind of virtual listing component for
"windowing" (like
react-virtualized).

highlightedIndex

number | control prop (read more about this in the "Control Props"
section below)

The index that should be highlighted

inputValue

string | control prop (read more about this in the "Control Props"
section below)

The value the input should have

isOpen

boolean | control prop (read more about this in the "Control Props"
section below)

Whether the menu should be considered open or closed. Some aspects of the
downshift component respond differently based on this value (for example, if
isOpen is true when the user hits "Enter" on the input field, then the item at
the highlightedIndex item is selected).

selectedItem

any/Array(any) | control prop (read more about this in the "Control
Props" section below)

The currently selected item.

render

function({}) | required

This is called with an object. Read more about the properties of this object in
the section "Render Prop Function".

id

string | defaults to a generated ID

You should not normally need to set this prop. It's only useful if you're server
rendering items (which each have an id prop generated based on the downshift
id). For more information see the FAQ below.

environment

window | defaults to window

You should not normally need to set this prop. It's only useful if you're
rendering into a different window context from where your JavaScript is
running, for example an iframe.

onOuterClick

function | optional

A helper callback to help control internal state of downshift like isOpen as
mentioned in this issue. The
same behavior can be achieved using onStateChange, but this prop is provided
as a helper because it's a fairly common use-case if you're controlling the
isOpen state:

const ui = (
  <Downshift
    isOpen={this.state.menuIsOpen}
    onOuterClick={() => this.setState({menuIsOpen: false})}
  >
    {/* your callback */}
  </Downshift>
)

This callback will only be called if isOpen is true.

stateChangeTypes

There are a few props that expose changes to state
(onStateChange and stateReducer).
For you to make the most of these APIs, it's important for you to understand
why state is being changed. To accomplish this, there's a type property on the
changes object you get. This type corresponds to a
Downshift.stateChangeTypes property. If you want to see what change types
are available, run this in your app:

console.log(Object.keys(Downshift.stateChangeTypes))

Control Props

downshift manages its own state internally and calls your onChange and
onStateChange handlers with any relevant changes. The state that downshift
manages includes: isOpen, selectedItem, inputValue, and
highlightedIndex. Your render prop function (read more below) can be used to
manipulate this state from within the render function and can likely support
many of your use cases.

However, if more control is needed, you can pass any of these pieces of state as
a prop (as indicated above) and that state becomes controlled. As soon as
this.props[statePropKey] !== undefined, internally, downshift will determine
its state based on your prop's value rather than its own internal state. You
will be required to keep the state up to date (this is where onStateChange
comes in really handy), but you can also control the state from anywhere, be
that state from other components, redux, react-router, or anywhere else.

Note: This is very similar to how normal controlled components work elsewhere
in react (like <input />). If you want to learn more about this concept, you
can learn about that from this the ["Controlled Components"
lecture][controlled-components-lecture] and exercises from [React
Training's][react-training] [Advanced React][advanced-react] course.

Render Prop Function

This is where you render whatever you want to based on the state of downshift.
It's a regular prop called render: <Downshift render={/* right here*/} />.

You can also pass it as the children prop if you prefer to do things that way
<Downshift>{/* right here*/}</Downshift>

The properties of this object can be split into three categories as indicated
below:

prop getters

See
the blog post about prop getters

These functions are used to apply props to the elements that you render. This
gives you maximum flexibility to render what, when, and wherever you like. You
call these on the element in question (for example: <input {...getInputProps()})). It's advisable to pass all your props to that function
rather than applying them on the element yourself to avoid your props being
overridden (or overriding the props returned). For example:
getInputProps({onKeyUp(event) {console.log(event)}}).

property type description
getToggleButtonProps function({}) returns the props you should apply to any menu toggle button element you render.
getInputProps function({}) returns the props you should apply to the input element that you render.
getItemProps function({}) returns the props you should apply to any menu item elements you render.
getLabelProps function({}) returns the props you should apply to the label element that you render.
getRootProps function({},{}) returns the props you should apply to the root element that you render. It can be optional.

getRootProps

Most of the time, you can just render a div yourself and Downshift will
apply the props it needs to do its job (and you don't need to call this
function). However, if you're rendering a composite component (custom component)
as the root element, then you'll need to call getRootProps and apply that to
your root element.

Required properties:

  • refKey: if you're rendering a composite component, that component will need
    to accept a prop which it forwards to the root DOM element. Commonly, folks
    call this innerRef. So you'd call: getRootProps({refKey: 'innerRef'}) and
    your composite component would forward like: <div ref={props.innerRef} />

If you're rendering a composite component, Downshift checks that
getRootProps is called and that refKey is a prop of the returned composite
component. This is done to catch common causes of errors but, in some cases, the
check could fail even if the ref is correctly forwarded to the root DOM
component. In these cases, you can provide the object {suppressRefError : true} as the second argument to getRootProps to completely bypass the check.
Please use it with extreme care and only if you are absolutely sure that the ref
is correctly forwarded otherwise Downshift will unexpectedly fail.

See #235 for the discussion that lead to this.

getInputProps

This method should be applied to the input you render. It is recommended that
you pass all props as an object to this method which will compose together any
of the event handlers you need to apply to the input while preserving the ones
that downshift needs to apply to make the input behave.

There are no required properties for this method.

Optional properties:

  • disabled: If this is set to true, then no event handlers will be returned from getInputProps and a disabled prop will be returned (effectively disabling the input).

getLabelProps

This method should be applied to the label you render. It is useful for
ensuring that the for attribute on the <label> (htmlFor as a react prop)
is the same as the id that appears on the input. If no htmlFor is provided
then an ID will be generated and used for the input and the label for
attribute.

There are no required properties for this method.

Note: You can definitely get by without using this (just provide an id to
your input and the same htmlFor to your label and you'll be good with
accessibility). However, we include this so you don't forget and it makes
things a little nicer for you. You're welcome 😀

getItemProps

The props returned from calling this function should be applied to any menu
items you render.

This is an impure function, so it should only be called when you will
actually be applying the props to an item.

details summaryWhat do you mean by impure function?

Basically just don't do this:

items.map(item => {
  const props = getItemProps({item}) // we're calling it here
  if (!shouldRenderItem(item)) {
    return null // but we're not using props, and downshift thinks we are...
  }
  return <div {...props} />
})

Instead, you could do this:

items.filter(shouldRenderItem).map(item => <div {...getItemProps({item})} />)

Required properties:

  • item: this is the item data that will be selected when the user selects a
    particular item.

Optional properties:

  • index: This is how downshift keeps track of your item when updating the
    highlightedIndex as the user keys around. By default, downshift will
    assume the index is the order in which you're calling getItemProps. This
    is often good enough, but if you find odd behavior, try setting this
    explicitly. It's probably best to be explicit about index when using a
    windowing library like react-virtualized.
  • disabled: If this is set to true, then all of the downshift item event
    handlers will be omitted. Items will not be highlighted when hovered,
    and items will not be selected when clicked.

getToggleButtonProps

Call this and apply the returned props to a button. It allows you to toggle
the Menu component. You can definitely build something like this yourself (all
of the available APIs are exposed to you), but this is nice because it will also
apply all of the proper ARIA attributes.

Optional properties:

  • disabled: If this is set to true, then all of the downshift button event
    handlers will be omitted (it wont toggle the menu when clicked).
  • aria-label: The aria-label prop is in English. You should probably override
    this yourself so you can provide translations:
const myButton = (
  <button
    {...getToggleButtonProps({
      'aria-label': translateWithId(isOpen ? 'close.menu' : 'open.menu'),
    })}
  />
)

actions

These are functions you can call to change the state of the downshift component.

property type description
clearSelection function(cb: Function) clears the selection
clearItems function() Clears downshift's record of all the items. Only really useful if you render your items asynchronously within downshift. See #186
closeMenu function(cb: Function) closes the menu
openMenu function(cb: Function) opens the menu
selectHighlightedItem function(otherStateToSet: object, cb: Function) selects the item that is currently highlighted
selectItem function(item: any, otherStateToSet: object, cb: Function) selects the given item
selectItemAtIndex function(index: number, otherStateToSet: object, cb: Function) selects the item at the given index
setHighlightedIndex function(index: number, otherStateToSet: object, cb: Function) call to set a new highlighted index
toggleMenu function(otherStateToSet: object, cb: Function) toggle the menu open state
reset function(otherStateToSet: object, cb: Function) this resets downshift's state to a reasonable default
setItemCount function(count: number) this sets the itemCount. Handy in situations where you're using windowing and the items are loaded asynchronously from within downshift (so you can't use the itemCount prop.
unsetItemCount function() this unsets the itemCount which means the item count will be calculated instead by the itemCount prop or based on how many times you call getItemProps.
setState function(stateToSet: object, cb: Function) This is a general setState function. It uses downshift's internalSetState function which works with control props and calls your onSelect, onChange, etc. (Note, you can specify a type which you can reference in some other APIs like the stateReducer).

otherStateToSet refers to an object to set other internal state. It is
recommended to avoid abusing this, but is available if you need it.

state

These are values that represent the current state of the downshift component.

property type description
highlightedIndex number / null the currently highlighted item
inputValue string / null the current value of the getInputProps input
isOpen boolean the menu open state
selectedItem any the currently selected item input

props

As a convenience, the id and itemToString props which you pass to
<Downshift /> are available here as well.

Event Handlers

Downshift has a few events for which it provides implicit handlers. Several of
these handlers call event.preventDefault(). Their additional functionality is
described below.

default handlers

  • ArrowDown: moves the highlighted index down by 1. If this shift key is held
    when this event fires, the highlighted index will jump down 5 indices instead of 1.
    NOTE: if the current highlighed index is within the bottom 5 indices, the top-most
    index will be highlighted.)

  • ArrowUp: moves the highlighted index up by 1. If this shift key is held when
    this event fires, the highlighted index will jump up 5 indices instead of 1. NOTE:
    if the current highlighed index is within the top 5 indices, the bottom-most index
    will be highlighted.)

  • Enter: if the menu is open, select the currently highlighted item. If the menu
    is open, the usual 'Enter' event is prevented by Downshift's default implicit enter
    handler; so, for example, a form submission event will not work as one might expect
    (though if the menu is closed the form submission will work normally). See below
    for customizing the handlers.

  • Escape: will reset downshift's state. This means that highlightedIndex will be
    set to the defaultHighlightedIndex, the inputValue will be set to the itemToString
    value of the selectedItem, and the isOpen state will be set to false.

customizing handlers

You can provide your own event handlers to Downshift which will be called before the default handlers:

const ui = (
  <Downshift>
    {({getInputProps}) => (
      <input
        {...getInputProps({
          onKeyDown: event => {
            // your handler code
          },
        })}
      />
    )}
  </Downshift>
)

If you would like to prevent the default handler behavior in some cases, you can set the event's preventDownshiftDefault property to true:

const ui = (
  <Downshift>
    {({getInputProps}) => (
      <input
        {...getInputProps({
          onKeyDown: event => {
            if (event.key === 'Enter') {
              // Prevent Downshift's default 'Enter' behavior.
              event.preventDownshiftDefault = true

              // your handler code
            }
          },
        })}
      />
    )}
  </Downshift>
)

If you would like to completely override Downshift's behavior for a handler, in favor of your own, you can bypass prop getters:

const ui = (
  <Downshift>
    {({getInputProps}) => (
      <input
        {...getInputProps()}
        onKeyDown={event => {
          // your handler code
        }}
      />
    )}
  </Downshift>
)

Utilities

resetIdCounter

Allows reseting the internal id counter which is used to generate unique ids for Downshift component.

You should never need to use this in the browser. Only if you are running an universal React app that is rendered on the server you should call resetIdCounter before every render so that the ids that get generated on the server match the ids generated in the browser.

import Downshift from 'downshift';

Downshift.resetIdCounter();
ReactDOMServer.renderToString(...);

React Native

Since Downshift renders it's UI using render props, Downshift supports rendering on React Native with ease. Use components like <View>, <Text>, <TouchableOpacity> and others inside of your render method to generate awesome autocomplete, dropdown, or selection components.

Gotchas

  • Your root view will need to either pass a ref to getRootProps or call getRootProps with { suppressRefError: true }. This ref is used to catch a common set of errors around composite components. Learn more in getRootProps.
  • When using a <FlatList> or <ScrollView>, be sure to supply the keyboardShouldPersistTaps prop to ensure that your text input stays focus, while allowing for taps on the touchables rendered for your items.
Download Details:

Author: downshift

Live Demo: http://downshift.netlify.com/

GitHub: https://github.com/downshift-js/downshift

What is JavaScript – All You Need To Know About JavaScript

What is JavaScript – All You Need To Know About JavaScript

In this article on what is JavaScript, we will learn the basic concepts of JavaScript.

After decades of improvement, JavaScript has become one of the most popular programming languages of all time. It all started in the year 1995 when Brendan Eich created JavaScript in a span of 10 days. Since then, it has seen multiple versions, updates and has grown to the next level.

Here’s a list of topics that I’ll be covering in this blog:

  1. What is JavaScript
  2. What can JavaScript do?
  3. JavaScript Frameworks
  4. The Big Picture: HTML, CSS & JavaScript
  5. Benefits of JavaScript
  6. Fundamentals of JavaScript
    VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case
What is JavaScript?

JavaScript is a high level, interpreted, programming language used to make web pages more interactive.

Have you ever thought that your website is missing something? Maybe it’s not engaging enough or it’s not as creative as you want it to be. JavaScript is that missing piece which can be used to enhance web pages, applications, etc to provide a more user-friendly experience.

What is JavaScript?

JavaScript is the language of the web, it is used to make the web look alive by adding motion to it. To be more precise, it’s a programming language that let’s you implement complex and beautiful things/design on web pages. When you notice a web page doing more than just sit there and gawk at you, you can bet that the web page is using JavaScript.

Feature of JavaScript

Scripting language and not Java: In fact, JavaScript has nothing to do with Java. Then why is it called “Java” Script? When JavaScript was first released it was called Mocha, it was later renamed to LiveScript and then to JavaScript when Netscape (founded JavaScript) and Sun did a license agreement. Object-based scripting language which supports polymorphism, encapsulation and to some extent inheritance as well.**Interpreted language: **It doesn’t have to be compiled like Java and C which require a compiler.JavaScript runs in a browser: You can run it on Google Chrome, Internet Explorer, Safari, etc. JavaScript can execute not only in the browser but also on the server and any device which has a JavaScript Engine.

What is JavaScript – Stackoverflow stats

Currently, we have 100s of programming languages and every day new languages are being created. Among these are few powerful languages that bring about big changes in the market and JavaScript is one of them.

JavaScript has always been on the list of popular programming languages. According to StackOverflow, for the 6th year in a row, JavaScript has remained the most popular and commonly used programming language.

What can JavaScript do?

JavaScript is mainly known for creating beautiful web pages & applications. An example of this is Google Maps. If you want to explore a specific map, all you have to do is click and drag with the mouse. And what sort of language could do that? You guessed it! It’s JavaScript.JavaScript can also be used in smart watches. An example of this is the popular smartwatch maker called Pebble. Pebble has created Pebble.js which is a small JavaScript Framework that allows a developer to create an application for the Pebble line of watches in JavaScript.

What is JavaScript – Applications of JavaScript
Most popular websites like Google, Facebook, Netflix, Amazon, etc make use of JavaScript to build their websites.Among things like mobile applications, digital art, web servers and server applications, JavaScript is also used to make Games. A lot of developers are building small-scale games and apps using JavaScript.## JavaScript Frameworks

One major reason for the popularity of JavaScript is the JavaScript Frameworks. Here’s a brief introduction of the most trending JavaScript frameworks :

  1. AngularJS is Google’s web development framework which provides a set of modern development and design features for rapid application development.

  2. ReactJS is another top JavaScript framework mainly maintained by Facebook and it’s behind the User Interface of Facebook and Instagram, showing off its efficiency in maintaining such high traffic applications.

What is JavaScript – JavaScript Frameworks

  1. MeteorJS is mainly used for providing back-end development. Using JavaScript on the back-end to save time and build expertise is one of the major ideas behind Meteor.

  2. jQuery can be used when you want to extend your website and make it more interactive. Companies like Google, WordPress and IBM rely on jQuery.

The Big Picture: HTML, CSS & JavaScript

Anyone familiar with JavaScript knows that it has something to do with HTML and CSS. But what is the relationship between these three? Let me explain this with an analogy.

What is JavaScript – HTML, CSS and JavaScript

Think of HTML (HyperText Markup Language) as the skeleton of the web. It is used for displaying the web.

On the other hand, CSS is like our clothes. We put on fashionable clothes to look better. Similarly, the web is quite stylish as well. It uses CSS which stands for Cascading Style Sheets for styling purpose.

Then there is JavaScript which puts life into a web page. Just like how kids move around using the skateboard, the web also motions with the help of JavaScript.

Benefits of JavaScript

There has to be a reason why so many developers love working on JavaScript. Well, there are several benefits of using JavaScript for developing web applications, here’s a few benefits:

It’s easy to learn and simple to implement. It is a weak-type programming language unlike the strong-type programming languages like Java and C++, which have strict rules for coding.

It’s all about being fast in today’s world and since JavaScript is mainly a client-side programming language, it is very fast because any code can run immediately instead of having to contact the server and wait for an answer.

Rich set of frameworks like AngularJS, ReactJS are used to build web applications and perform different tasks.

**Builds interactive websites: **We all get attracted to beautifully designed websites and JavaScript is the reason behind such attractive websites and applications.

JavaScript is an interpreted language that does not require a compiler because the web interprets JavaScript. All you need is a browser like Google Chrome or Internet Explorer and you can do all sorts of stuff in the browser.

JavaScript is platform independent and it is supported by all major browsers like Internet Explorer, Google Chrome, Mozilla Firefox, Safari, etc.

JavaScript Fundamentals

In this What is JavaScript blog, we’ll cover the following basic fundamentals of JavaScript
VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case## Variables

Variable is a name given to a memory location which acts as a container for storing data temporarily. They are nothing but reserved memory locations to store values.

What is JavaScript – Variables

To declare a variable in JavaScript use the ‘let’ keyword. For example:

let age;
age=22;

In the above example, I’ve declared a variable ‘age’ by using the ‘let’ keyword and then I’ve stored a value (22) in it. So here a memory location is assigned to the ‘age’ variable and it contains a value i.e. ’22’.

Constants

Constants are fixed values that don’t change during execution time.

To declare a constant in JavaScript use the ‘const’ keyword. For example:

const mybirthday;
mybirthday='3rd August'; 

Data types

You can assign different types of values to a variable such as a number or a string. In JavaScript, there are two categories of data types :

What is JavaScript – Data Types

Objects

An object is a standalone entity with properties and types and it is a lot like an object in real life. For example, consider a girl, whose name is Emily, age is 22 and eye-color is brown. In this example the object is the girl and her name, age and eye-color are her properties.

What is JavaScript – Objects example

Objects are variables too, but they contain many values, so instead of declaring different variables for each property, you can declare an object which stores all these properties.

To declare an object in JavaScript use the ‘let’ keyword and make sure to use curly brackets in such a way that all property-value pairs are defined within the curly brackets. For example:

let girl= {
name: 'Emily',
age: 22,
eyeColour: 'Brown'
};

In the above example, I’ve declared an object called ‘girl’ and it has 3 properties (name, age, eye colour) with values (Emily, 22, Brown).

Arrays

An array is a data structure that contains a list of elements which store multiple values in a single variable.

For example, let’s consider a scenario where you went shopping to buy art supplies. The list of items you bought can be put into an array.

What is JavaScript – Arrays example

To declare an array in JavaScript use the ‘let’ keyword with square brackets and all the array elements must be enclosed within them. For example:

let shopping=[];
shopping=['paintBrush','sprayPaint','waterColours','canvas'];

In the above example I’ve declared an array called ‘shopping’ and I’ve added four elements in it.

Also, array elements are numbered from zero. For example this is how you access the first array element:

shopping[0];		

Functions

A function is a block of organised, reusable code that is used to perform single, related action.

Let’s create a function that calculates the product of two numbers.

To declare a function in JavaScript use the ‘function’ keyword. For example:

function product(a, b) {
return a*b;
}

In the above example, I’ve declared a function called ‘product’ and I’ve passed 2 parameters to this function, ‘a’ and ‘b’ which are variables whose product is returned by this function. Now, in order to call a function and pass a value to these parameters you’ll have to follow the below syntax:

product(8,2);

In the above code snippet I’m calling the product function with a set of values (8 & 2). These are values of the variables ‘a’ and ‘b’ and they’re called as arguments to the function.

Conditional statements – if

Conditional statement is a set of rules performed if a certain condition is met. The ‘if’ statement is used to execute a block of code, only if the condition specified holds true.

What is JavaScript – if flowchart

To declare an if statement in JavaScript use the ‘if’ keyword. The syntax is:

if(condition) {
statement;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[2]) {
console.log('Correct!');
}

In the above example I’ve defined an array of numbers and then I’ve defined an if block. Within this block is a condition and a statement. The condition is ‘(numbers[0]==numbers[2])’ and the statement is ‘console.log(‘Correct!’)’. If the condition is met, only then the statement will be executed.

Conditional statements- Else if

Else statement is used to execute a block of code if the same condition is false.

What is JavaScript – Else-if flowchart

The syntax is:

if(condition) {
statement a;
}
else (condition) {
statement b;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[4] {
console.log("Correct!");
}
else {
console.log("Wrong, please try again");
}

In the above example, I’ve defined an if block as well as an else block. So if the conditions within the if block holds false then the else block gets executed. Try this for yourself and see what you get!

**Loops **

Loops are used to repeat a specific block until some end condition is met. There are three categories of loops in JavaScript :

  1. while loop
  2. do while loop
  3. for loop
While loop

While the condition is true, the code within the loop is executed.

What is JavaScript – while loop flowchart

The syntax is:

while(condition) {
loop code;
}

Now let’s look at an example:

let i=0;
while(i < 5) {
console.log("The number is " +i);
i++;
}

In the above example, I’ve defined a while loop wherein I’ve set a condition. As long as the condition holds true, the while loop is executed. Try this for yourself and see what you get!

Do while loop

This loop will first execute the code, then check the condition and while the condition holds true, execute repeatedly.

What is JavaScript – Do while loop flowchart

Refer the syntax to better understand it:

do {
loop code;
} while(condition);

This loop executes the code block once before checking if the condition is true, then it will repeat the loop as long as the condition holds true.

Now let’s look at an example:

do {
console.log("The number is " +i);
i++;
}
while(i > 5);

The above code is similar to the while loop code except, the code block within the do loop is first executed and only then the condition within the while loop is checked. If the condition holds true then the do loop is executed again.

For loop

The for loop repeatedly executes the loop code while a given condition is TRUE. It tests the condition before executing the loop body.

What is JavaScript – for loop flowchart

The syntax is:

for(begin; condition; step) {
loop code;
}

In the above syntax:

  • begin statement is executed one time before the execution of the loop code
  • condition defines the condition for executing the loop code
  • step statement is executed every time after the code block has been executed

For example:

for (i=0;i<5;i++) {
console.log("The number is " +i);
}

In the above example, I’ve defined a for loop within which I’ve defined the begin, condition and step statements. The begin statement is that ‘i=0’. After executing the begin statement the code within the for loop is executed one time. Next, the condition is checked, if ‘i<5’ then, the code within the loop is executed. After this, the last step statement (i++) is executed. Try this and see what you get!

Switch Case

The switch statement is used to perform different actions based on different conditions.

What is JavaScript – Switch case flowchart

Let’s look at the syntax for switch case:

switch(expression) {
case 1:
code block 1
break;
case 2:
code block 2
break;
default:
code block 3
break;
}

How does it work?

  • Switch expression gets evaluated once
  • Value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed

Let’s try this with an example:

let games='football';
switch(games) {
case "throwball":
console.log("I dislike throwball!");
break;
case "football":
console.log("I love football!");
break;
case "cricket":
console.log("I'm a huge cricket fan!");
break;
default:
console.log("I like other games");
break;
}

In the above example the switch expression is ‘games’ and the value of games is ‘football’. The value of ‘games’ is compared with the value of each case. In this example it is compared to ‘throwball’, ‘cricket’ and ‘football’. The value of ‘games’ matches with the case ‘football’, therefore the code within the ‘football’ case is executed. Try this for yourself and see what you get!

With this, we come to the end of this blog. I hope you found this blog informative and I hope you have a basic understanding of JavaScript. In my next blog on JavaScript I’ll be covering in-depth concepts, so stay tuned.

Also, check out our video on JavaScript Fundamentals if you want to get started as soon as possible and don’t forget to leave a comment if you have any doubt and also, let us know whether you’d want us to create more content on JavaScript. We are listening!

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 !