DEV Community

Cover image for Absolute Beginner's Guide to Learn JavaScript, Part-2
Afroza Nowshin
Afroza Nowshin

Posted on • Edited on

Absolute Beginner's Guide to Learn JavaScript, Part-2

In the previous post, we learned some of the basics of JavaScript that are heavily used in front-end web development. The topics that I'll cover today are some of the cores that are not only essential in JavaScript but also in any JavaScript-based framework and libraries (e.g. React JS, Next JS, React Native, etc).

I will be summing up the topics that you can find in W3Schools, Free Code Camp and Wes Bos. You can google each of the following topics or even watch on YouTube as I narrowed these down for you.

4. Array manipulation - length, forEach, map, push, spread

There are times when you need to handle a list of data with JavaScript. JavaScript Arrays can have various types of data just like a Python list. There are a lot of operations that you can do in arrays. Even there are a number of ways to loop through an array. However, if you can master the following operations and functions you can write any web application either with Vanilla JavaScript or with frameworks or libraries.

  • Length property

The length property of an array gives the number of items in an array. Following is a basic for loop in JavaScript where you are writing a list of numbers within an unordered HTML element.

<!DOCTYPE html>
<html>

<body>

    <h1>Array and Objects</h1>
    <h3>Push() method returns the length of the array after pushing the item in the end of the array</h5>
        <ul id="list1">

        </ul>
</body>
<script>
    const numbers = [1, 2, 5, 7, 8, 10]

    let n = ""

    for (var i = 0; i < numbers.length; i++) {

        n += "<li>" + numbers[i] + "</li>"

    }

    document.getElementById("list1").innerHTML = n;
</script>

</html>


Enter fullscreen mode Exit fullscreen mode

Output will look like :

Output 1

  • forEach method

The forEach() method is applied on each item of an array which is non-empty . Here's an example:

<script>
    const numbers = [1, 2, 5, 7, 8, 10]

    numbers.forEach(my)

    document.getElementById("list1").innerHTML = n;

    function my(item, index){
        n += "<li>" + index + "th:" + "  "+item + "</li>"
    }

</script>

Enter fullscreen mode Exit fullscreen mode

Output:

Output 2

Function my is applied on each item of the array numbers. ForEach() method return nothing and the source array will be changed after applying.

Let's write a code with a callback. Callback is a crucial concept in JavaScript, and later you will see also in ES6. Essentially it's a function that is passed as an argument to another function so that it can be executed in that other function. A callback is written using an *arrow => * notation like the following:

<script>

        let numbers = [1, 2, 3, 4, 5, 6]

    let result = numbers.forEach((item) => {
        console.log(item * 2)
    })


    console.log("original array",numbers)
    console.log("after forEach", result)
</script>

Enter fullscreen mode Exit fullscreen mode

Output is:

Output 3

As you can see, the forEach() method is applying on each item of the array, and is not returning anything. Therefore the result array is undefined.

  • Map method

Like the Spy x Family there is an even elegant solution to loop through an array in JavaScript, with map function. A map method is just like forEach method, with an exception that it returns a new array while keeping the original intact.

Consider the code below:

<script>

let numbers = [1, 2, 3, 4, 5, 6];

let result = numbers.map((item) => item * 2)

console.log("original", numbers);
console.log("after map", result);
</script>

Enter fullscreen mode Exit fullscreen mode

You can see here how the map method returned a new array:

Output 5

Note that, if you want to keep your original array unchanged, go for map method. Also, you can chain this method as many as you can, such as :


arra1.map(item1 => {
        item1.map(item2 => {
            console.log(item2)
        })
    })

// and so on

Enter fullscreen mode Exit fullscreen mode

But you can not do it with forEach() because it returns undefined. Personally I use map almost all the time in my Vanilla and React JS codes.

  • Push method

Push method is like the push operation in a stack; any item(s) passed as the argument of this method is appended at the end of the array. This method returns the new length of the array.


<!DOCTYPE html>
<html>

<body>

      <p id="list1">

      </p>
</body>
<script>

let numbers = [1, 2, 3, 4, 5, 6];

numbers.push(2, 4, 0, 100)

document.getElementById("list1").innerHTML = numbers
console.log("after push", numbers)
</script>

</html>
Enter fullscreen mode Exit fullscreen mode

You can see the array numbers with the new values here:

Output 6

  • Spread Operation

Array spreading is an essential operation. The concept is straightforward. When you "spread" an array or any iterables (data types that can be iterated - string, objects, arrays etc.), you are copying all or some of the items, into another array or iterables, and expanding.


<script>

let arr1 = ['one', 'two', 'three']
let arr2 = [1 , 2, 3]

let combined = [...arr1, ...arr2]

console.log(combined)
</script>

Enter fullscreen mode Exit fullscreen mode

Output of this code is:

Output 7

Let's look at another example. We want to sum the squares of an array; what we can do is:


<script>

function sqSum(x, y, z) {
  return x * x + y * y + z * z;
}

const numbers = [1, 2, 3];

console.log(sqSum(...numbers));

</script>

Enter fullscreen mode Exit fullscreen mode

In the console, you will see that the output is 14. What happened here is, we spread the numbers array by copying all the items, then took all the items to square and finally summed the squares.

5. Object Handling

As a JavaScript and front-end developer, it's essential to know how to manipulate objects. An object is a non-primitive data type in JavaScript, because if you break it down you will get some primitive data. It's a key-value pair - {key:value}.


<script>

let obj = {
    "one": 1,
    "two": 2,
    "three": [3,4,5]
}

console.log(obj)

</script>

Enter fullscreen mode Exit fullscreen mode

Output 9

If you want to access, say the array, all you have to do is write obj["three"] in the console.

Object is a kind of iterables. As a front-end developer you will be required to parse and show data from the back-end that you get as some form of requests. These requests will be a collection of JSON objects or "JavaScript Object Notation". JSON is a text-based format for representing structured data based on JavaScript object syntax source-MDN. A JSON can be just one object or a collection of a lot of objects, but with map method discussed earlier and the upcoming methods, you will be able to parse any JSON object.

The methods and operation that I discussed on JavaScript array, can also be used with objects. Here I wrote a code to spread an object:


let obj = {
    "one": 1,
    "two": 2,
    "three": [3,4,5]
}
let anotherObj = {...obj}
console.log(anotherObj)

Enter fullscreen mode Exit fullscreen mode

Object anotherObject will contain the object obj.

Now I will discuss some of the methods that I use extensively while I parse various and complicated objects:

  • JSON.stringigy() and JSON.parse():

JSON.stringify() method converts the JavaScript object into a JSON string.


let obj = {
    "one": 1,
    "two": 2,
    "three": [3,4,5]
}

console.log(obj)

const myObjStr = JSON.stringify(obj);

console.log(myObjStr);
Enter fullscreen mode Exit fullscreen mode

Output 11

JSON.parse() method will do the opposite - it will take the JSON string and convert it into a JavaScript object.


let obj = {
    "one": 1,
    "two": 2,
    "three": [3,4,5]
}

const myObjStr = JSON.stringify(obj);

const parsedObj = JSON.parse(myObjStr)

console.log(parsedObj);

Enter fullscreen mode Exit fullscreen mode

parsedObj will look the exact same like the obj.

  • Object.keys(), Object.values(), Object.entries()

Let's say that you have an object like the following:


let obj = {
    "one": 1,
    "two": 2,
    "three": [3,4,5],
    "five": {
        "six" : 6
    }
}
Enter fullscreen mode Exit fullscreen mode

Looks a bit intimidating? Worry not. List all the keys by passing this object in Object.keys() method:


let obj = {
    "one": 1,
    "two": 2,
    "three": [3,4,5],
    "five": {
        "six" : 6
    }
}

console.log(Object.keys(obj))

Enter fullscreen mode Exit fullscreen mode

Output will be an array of all the keys :

Output 12

If you want to see all the values, just pass the object in Object.values() methods:

console.log(Object.values(obj)

Enter fullscreen mode Exit fullscreen mode

Output 13

Say you want to see the value of the inner object, just write the index value outside the parenthesis:


console.log(Object.values(obj)[3])

Enter fullscreen mode Exit fullscreen mode

Bingo!

Output 14

There is another method that can show all the key-value pairs as a list of arrays : Object.entries()


console.log(Object.entries)

Enter fullscreen mode Exit fullscreen mode

All the pairs are converted into an array of size 2 each:

Output 15

We have made it till object manipulation!

Phew!

I wanted to include some more topics such as event handling, ES6 and Promises in JavaScript but I think this post will be voluble with those. I am planning to write about those soon. I hope this post is helpful to learn JavaScript, and of course search W3Schools for the necessary methods and operations for your code. Bye for today.

Top comments (0)