paint-brush
Javascript Basics For React Beginnersby@pbteja1998
807 reads
807 reads

Javascript Basics For React Beginners

by Bhanu Teja PachipulusuNovember 30th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

React is a new ES6 way to create strings. It's better to know these before you deep dive into learning React before learning the basic concepts of javascript. This will be used quite a lot while using React. It's important to know the basic javascript concepts to understand better which part of the puzzle is React solving. This is best explained using an example of an example that you want to create the following type of strings: '3 blog posts were written by Bhanu Teja in a span of 2 weeks'

Coin Mentioned

Mention Thumbnail
featured image - Javascript Basics For React Beginners
Bhanu Teja Pachipulusu HackerNoon profile picture

I am one of those persons who learned React before properly learning the basic concepts of javascript. Because of this, in the early days of my React journey, I didn't know which part of the code is React and which part is the vanilla js. It's important to know the basic javascript concepts to understand better which part of the puzzle is React solving.

In this blog post, I will be writing about different concepts of javascript that you see yourself using very often while working with React. It's better to know these before you deep dive into learning React.

Logical AND (&&) and Logical OR (||) Operators

Logical AND (&&) Operator

Let's say we have the following expression - where

b
and
c
are expressions.

b && c

This will be evaluated to the value of

c
only if
b
is truthy, otherwise, it will be evaluated to the value of
b

Notes:

  • If
    b
    is falsy, then the expression
    c
    is not even going to be evaluated.
  • This is called
    shortcut evaluation
    .
  • This will be used quite a lot while using React.

Logical OR (||) Operator

Let's say we have the following expression - where

b
and
c
are expressions

b || c

This will be evaluated to the value of

b
if b is truthy, otherwise, it will be evaluated to the value of
c
.

Note:

  • Shortcut evaluation happens here too.
  • If
    b
    is truthy, then the expression
    c
    is not even going to be evaluated.
  • You will be using this also quite often while using React.

    Template Literals

    This is a new ES6 way to create strings.

    Let's see an example.

    Assume that you want to create the following type of strings:

    • 3 blog posts were written by Bhanu Teja in a span of 2 weeks.

    You will be given

    count
    (number of blogs),
    name
    (name of the user),
    span
    (time span it took) as variables.

    Without using template literals

    const count = 3
    const user = 'Bhanu Teja'
    const span = 2
    
    const result = count + ' blog posts were written by ' 
                         + name + ' in a span of ' + span 
                         + ' weeks.'
    

    Using template literals

    const count = 3
    const name = 'Bhanu Teja'
    const span = 2
    
    const result = `${count} blog posts were written by ${name} in a span of ${span} weeks.`
    

    Template literals start and end with a

    backtick(`)
    and you can write strings of text inside them and you have to wrap the javascript expressions around with
    ${
    and
    }

    Let's add another use-case to the above example.

    • If we have just 1 blog post you have to use
      blog post
      instead of
      blog posts
    • If the time span is just 1 week, you have to use
      week
      instead of
      weeks
      .

    Without using template literals

    function pluralize(text, count) {
        if (count === 1) {
            return text
        }
        return text + 's'
    }
    
    const result = count + ' ' + pluralize('blog post', count)  
                         + ' were written by ' + name
                         + ' in a span of ' + span 
                         + ' ' + pluralize('week', span) + '.'
    

    Using template literals

    function pluralize(text, count) {
        if (count === 1) {
            return text
        }
        return text + 's'
    }
    
    const result = `${count} ${pluralize('blog post', count)} were written by ${name} in a span of ${span} ${pluralize('week', span)}.`
    

    Ternary Operator

    This is a shorthand representation of the if-else statements.

    This is best explained using an example.

    if (condition) {
        doSomething()
    } else {
        doSomethingElse()
    }
    

    The above example when written using ternary operator

    condition ? doSomething() : doSomethingElse()

    Syntax

    condition ? expressionIfTrue : expressionIfFalse

    Shorthand Property Names

    const id = 2
    const name = 'Bhanu'
    const count = 2
    
    // This is the normal way
    const user = {
        id: id,
        blogs: count,
        name: name,
    }
    
    // Using shorthand property names
    const user = {
        id,
        blogs: count,
        name,
    }
    

    If the name of the

    variable
    and the name of the
    property
    of the object are the same, then you can just write the variable name and omit the rest.

    This is one of the things that I did not know when I was initially learning React, and you usually see this being used a lot in code and documentation.

    Object Destructuring

    This is a short-hand way to get the properties of an object into variables.

    // we have a `user` variable that looks like this
    const user = {
        name: 'Bhanu Teja',
        blogs: 3,
        timeSpan: 2.
    }
    
    // without using object destructuring
    const name = user.name
    const blogs = user.blogs
    const timeSpan = user.timeSpan
    
    // using object destructuring
    const { name, blogs, timeSpan } = user
    

    Note:

    The name of the destructured variables should be same as the name of the object properties.

    Array Destructuring

    This is a short-hand way to get the elements of an array into variables.

    // we have a `name` variable that looks like this
    const name = [ 'Bhanu Teja', 'P']
    
    // without using array destructuring
    const firstName = name[0]
    const lastName = name[1]
    
    // using array destructuring
    const [firstName, lastName] = name
    

    Default Parameters

    You often want the function parameters to take some default values if that is not passed while calling the function.

    Let's see an example

    function sum(a = 2, b = 5) {
        return a + b
    }
    
    sum(5, 7) // a = 5, b = 7, result = 12
    sum(4) // a = 4, b = 5(default value of b), result = 9
    sum() // a = 2(default a), b = 5(default b), result = 7
    

    So, whenever you want a parameter to take a default value, simply add a

    =
    sign after the parameter and add your default value there.

    Optional Chaining

    This is a relatively new feature of javascript.

    The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. - Taken from MDN Docs

    Consider the expression

    a?.b

    This expression evaluates to

    a.b
    if
    a
    is
    not null
    and
    not undefined
    , otherwise, it evaluates to
    undefined
    .

    You can even chain this multiple times like

    a?.b?.c

    • If
      a
      is
      undefined
      or
      null
      , then this expression evaluates to
      undefined
    • Else if
      b
      is undefined or
      null
      , then this expression evaluates to
      undefined
    • Else this evaluates to
      a.b.c

    Syntax:

    obj.val?.prop
    obj.val?.[expr]
    obj.arr?.[index]
    obj.func?.(args)
    

    Nullish Coalescing Operator

    The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is
    null
    or
    undefined
    , and otherwise returns its left-hand side operand. - Taken from MDN Docs

    Consider the expression

    a ?? b

    This evaluates to

    b
    if
    a
    is
    null
    or
    undefined
    , otherwise, it evaluates to
    a

    Spread Operator

    This operator spreads the values of an iterable object.

    Array Spread

    const a = [1, 2, 3]
    const b = [5, 6]
    
    console.log(...a) // 1 2 3
    
    // Now, if you want to have an array with values 0, 1, 2, 3, 4, 5, 6
    const c = [0, ...a, 4, ...b]
    
    console.log(c) // 0 1 2 3 4 5 6
    

    Object Spread

    const first = {a: 1, b: 2}
    const second = {c: 3}
    
    
    // Now to create an object {a: 1, b: 2, c: 3, d: 4}
    const result = {...first, ...second, d: 4}
    
    console.log(result) // {a: 1, b: 2, c: 3, d: 4}
    

    Rest Operator

    The rest parameter syntax allows us to represent an indefinite number of arguments as an array. - Taken from MDN Docs

    Function Arguments

    function sum(a, b, ...rest) {
        // ...
    }
    
    sum(1, 2, 3, 4, 5, 6) // a = 1, b = 2, rest = [3, 4, 5, 6]
    

    Usage with objects

    const user = {
        name: 'Bhanu Teja',
        blogs: 3,
        span: 2,
    }
    const {name, ...rest} = user
    console.log(name) // Bhanu Teja
    console.log(rest) // { blogs: 3, span: 2}
    

    Arrow Functions

    This is a new ES6 way to write functions.

    // without using arrow functions
    const sum = function (a, b) {
        return a + b
    }
    
    // (or)
    
    function sum (a, b) {
        return a + b
    }
    
    // Using arrow functions
    const sum = (a, b) => {
        return a + b
    }
    
    // (or)
    
    const sum = (a, b) => a+ b
    
    const multiplyBy2 = (a) => a * 2
    
    (or)
    
    const multiplyBy2 = a => a * 2
    

    As you can see from the above example, converting the normal function to arrow functions can be done as follows:

    • Remove the
      function
      keyword.
    • Add an
      =>
      after the parameters.

    Note

    • If the body of the function is a simple expression you can even omit the
      return
      keyword and also need not wrap it between
      {
      and
      }
    • If there is only one argument, you have the option to remove parenthesis around the arguments.
    • There are still some more differences between arrow functions and normal functions, Checkout the following amazing articles to know more.
    • A Simple Guide To Arrow Functions
    • ES6 => Arrow Functions

    Array Methods

    There are so many array methods, but we frequently use some of these. I will be covering the following array methods.

    • map
    • filter
    • reduce
    • sort
    • includes
    • slice
    • splice

    Array map() Method

    This method creates a new array from an existing array by calling a function for every element of the array.

    I always remember this as

    mapping the values in an array to some other values
    .

    Let's see an example.

    const names = [
        { firstName: 'Bhanu Teja', lastName: 'P' },
        { firstName: 'Florin', lastName: 'Pop'},
        { firstName: 'Brad', lastName: 'Traversy'},
    ]
    
    // Let's say we have to create a new array with full names.
    
    // First let's write a callback function which takes an array element as an argument.
    function callback(name) {
        return name.firstName + ' ' + name.lastName
    }
    
    // Now let's call .map() method on the array
    console.log(names.map(callback)) // ["Bhanu Teja P", "Florin Pop", "Brad Traversy"]
    
    // You can even inline the callback function which is how most of the people write this.
    names.map(function(name) { return name.firstName + ' ' + name.lastName })
    
    // Let's write the same using arrow functions and template literals that we just learned earlier
    names.map((name) => `${name.firstName} ${name.lastName}`)
    
    // You can even omit the parenthesis around name
    names.map(name => `${name.firstName} ${name.lastName}`)
    
    // Let's use object destructuring
    names.map(({firstName, lastName}) => `${firstName} ${lastName}`)
    

    Syntax:

    // callback takes a single array element as an argument.
    // values is an array
    values.map(callback)
    

    Note:

    • Calling this method will not change the original array

    Array filter() Method

    Now that we know the

    Array map
    method, it's easy to understand other array methods. They all have a similar syntax.

    The array filter method creates a new array with elements that satisfy some given criteria.

    I always remember this as the

    filter
    method filters out elements that do not satisfy the criteria.

    // consider the following array of users
    const users = [
        {id: 1, posts: 2},
        {id: 2, posts: 1},
        {id: 3, posts: 5},
        {id: 4, posts: 4},
        {id: 5, posts: 3},
    ]
    
    // Let's say we want to have all users who have at least 3 posts.
    users.filter((user) => user.posts >= 3) // [{id: 3, posts: 5}, {id: 4, posts: 4}, {id: 5, posts: 3}]
    

    Syntax:

    // callback takes a single array element as an argument.
    // values is an array
    values.filter(callback)
    

    Note:

    • Calling this method will not change the original array

    Array reduce() method

    The array reduce method reduces the array of values into a single value. It executes the callback function for each value of the array.

    Lets see the syntax of the reduce method before seeing an example.

    array.reduce(function(totalValue, currentValue, currentIndex, arr), initialValue)
    
    const values = [2, 4, 6, 7, 8]
    
    // Let's say that we want to have a sum of all these values.
    // Let's see how we do it using a traditional for loop
    let total = 0
    for(let i = 0; i < values.length; i++) {
        const value = values[i]
        total = total + value
    }
    console.log(total)
    
    
    // Let's use reduce method now
    const initialValue = 0
    values.reduce((total, currentValue) => total + currentValue, initialValue)
    

    Notes:

    • initialValue
      is an optional parameter.
    • Calling this method will not change the original array

    Array sort() method

    The callback function takes two different values as arguments. Based on the return value of the callback function, the two elements' positions are decided.

    • If the return value is negative, then the first value is considered to be before the second value.
    • If the return value is zero, then there will be no change in the order of the values.
    • If the return value is positive, then the first value is considered to be after the second value.
    const values = [4, 10, 2, 1, 55]
    
    // Let's say we want to sort this array in descending order
    // so if a and b are given
    // a should be before b if a > b
    // a should be after b if a < b
    // a and b can be at their own places if a === b
    
    values.sort((a, b) => {
        if(a > b) {
            return -1
        }
        if(a < b) {
            return 1
        }
        return 0
    }) // [55, 10, 4, 2, 1]
    
    
    // You can also do this as follows
    values.sort((a, b) => b - a)
    

    Note:

    • The return value of the function is the sorted array
    • This changes the original array
    • If you do not pass any callback function, this sorts the values as strings and in ascending order.

    Array includes() Method

    This returns

    true
    if the element is included in the array, otherwise returns
    false
    .

    Syntax:

    array.includes(element)
    const values = [2, 3, 4]
    values.includes(1) // false
    values.includes(2) // true
    

    Note:

    • You can pass an optional parameter specifying the start index to start the search from.
      array.includes(element, startIndex)

    Array slice() method

    Syntax

    array.slice(start, end)

    Array slice will return the elements in the given range.

    start

    • starting index to select the elements from
    • This is an optional parameter and by default, it takes the value of 0
    • You can even pass a negative number.
    • Negative number represents the position from the end.
    • -1
      refers to the last element of the array,
      -2
      refers to last but one element, and so on.

    end

    • ending index up to where to select the elements
    • This is an optional parameter. If this is not passed, then all elements up to the end of the array will be selected.
    • The element at
      end
      will not be selected
    • This also accepts a negative number as an argument and the meaning is the same as before.
    const numbers = [0, 1, 2, 3, 4, 5, 6, 7]
    console.log(numbers.slice())  // [0, 1, 2, 3, 4, 5, 6, 7]
    console.log(numbers.slice(2)) // [2, 3, 4, 5, 6, 7]
    console.log(numbers.slice(2, 6)) // [2, 3, 4, 5]
    console.log(numbers.slice(-1)) // [7]
    console.log(numbers.slice(-3)) // [5, 6, 7]
    console.log(numbers.slice(-3, -1)) // [5, 6]
    

    Note:

    • This doesn't change the original array

    Array splice() method

    Syntax:

    array.splice(index, count, item1, ....., itemX)

    This method is used to add or remove elements in an array.

    index

    • The index at which the elements need to be added or removed. Can be a negative value too.

    count

    • The number of elements to remove.

    item1, ....., itemX

    • Items that will be added at
      index
    const numbers = [0, 1, 2, 100, 6, 7]
    // let's say we have to convert this array to [0, 1, 2, 3, 4, 5, 6, 7]
    numbers.splice(3, 1, 3, 4, 5) 
    console.log(numbers) // [0, 1, 2, 3, 4, 5, 6, 7]
    

    Note:

    • The return value of the splice method is the array of items removed.
    • This changes the original array

    To know more about different array methods, check out the amazing series Javascript Array Methods

    Default Exports vs Named Exports

    You often see yourself using ES Modules imports and exports while working with React. It's important to know how to import them when they are exported as default exports vs when they are exported as named exports.

    Check out the following amazing articles to read about these.

    Promises

    You also need to have a basic knowledge of what promises are and how to work them. They will be used quite often in React.

    Check out this article to know more about them.

    Basic DOM Document APIs

    It is also good to be familiar with basic Document Apis like

    createElement
    ,
    getElementById
    etc. If you know these, you will appreciate the similarity and differences between React APIs and Document APIs.

    If you are working with javascript for a while now, it is most likely that you already know basic Document APIs.

    MDN Docs are the best place to read up on these.

    You might also like the following React articles that I wrote:

    Previously published at https://blog.bhanuteja.dev/epic-react-javascript-you-need-to-know-for-react