The Set Data Structure in Javascript

Learn about how to use and when to use Set in JavaScript.


The Set object allows you to create a collection of unique values(each value can occur only once).

Set can contain any type of value (primitives or object reference).

Set stores elements in the insertion order.

The Set doesn’t contain’s keys 🔑 like a Map object.

The uniqueness of elements of the Set are checked using the SameValueZero algorithm. This algorithm is similar to === (strict equal) except in one case where NaN === NaN evaluates to true, so that multiple NaN is not inserted in the Set.

Creating a Set

Syntax: new Set([iterable]) → returns a Set object.

var set1 = new Set([1, 2, 1, 3, 4, 5]);
set1; // Set(5) {1, 2, 3, 4, 5} ; duplicate values are removed.
Creating an empty set
var set2 = new Set();

Properties

size → Returns the number of elements in the Set

var number = new Set([1,2,3,4,5])
number.size ; 

Methods

add()

The add() method appends the element passed to the end of a Set object and returns the Set object.

var fruits = new Set(['🍇', '🍉', '🍊', '🍈' ]);
fruits.add('🍋');
fruits; // Set(5) {'🍇', '🍉', '🍊', '🍈', '🍋'};

When we try to add duplicate values it is not inserted.

fruits.add('🍊'); // already present in the set
fruits; // Set(5) {'🍇', '🍉', '🍊', '🍈', '🍋'};

The add method is chain-able

fruits
.add('🍌')
.add('🍓')
.add('🍎');
fruits; // Set(8) {"🍇", "🍉", "🍊", "🍈", "🍋", …}

Adding objects to Set

var set = new Set();
set.add({i : 10});
set.add({i : 10});
set; //Set(2) {{…}, {…}}
// Even-though objects look same, each object has different reference, so they are not ===
//
An object reference means that it compares the memory address of the object and not the actual key/value pairs contained in the object.
--------------------------------------------------------------------
var obj = {i :100};
set.add(obj);
set.add(obj);
// Now the obj points to same object reference so it is not inserted
--------------------------------------------------------------------
obj.i =1000;
// the value in the set is changed because we are storing the address.

has()

The has() method returns true if an element with the specified value exists in a Set object, and false if the value is not present in the Set .

Syntax: has(valueToBeChecked) → returns either true or false.

var fruits = new Set(['🍇', '🍉', '🍊', '🍈' ]);
fruits.has('🍇'); //true
fruits.has('🍌'); //false

has method with object

var set = new Set();
var obj = {i :100};
set.add(obj);
set.has(obj); // true
set.has({i : 100}); //false, because they are different object  reference.

values()

The values() method returns a new Iterator object that contains the values for each element in the Set object in insertion order.

var fruits = new Set(['🍇', '🍉', '🍊', '🍈' ]);
fruits.values();  // SetIterator {"🍇", "🍉", "🍊", "🍈", "🍋", …}
--------------------------------------------------------------------
//use destructor to print only the values
console.log(...fruits.values())
or 
var fruitsArray = ([...fruits.values]);

entries()

The entries() method returns a new Iterator object that contains an array of [value, value] in insertion order.

There is no key in a Set so it returns in the format of [value, value] .

var fruits = new Set(['🍇', '🍉']);
fruits.entries();  SetIterator {"🍇" => "🍇", "🍉" => "🍉"}
--------------------------------------------------------------------
// you can use for...of 
for(var [key ,value] of fruits.entries()) {
console.log(key, value);
}

delete()

The delete() method removes the specified element from a Set object.

Syntax : delete(valueToBeDeleted)

Returns true if an element in the Set is deleted, otherwise it returns false.

var fruits = new Set(['🍇', '🍉']);
fruits.delete('🍇'); //true
fruits; //Set(1) {"🍉"}
fruits.delete('🍌'); false.

clear()

The clear()method empties theSet object.

var fruits = new Set(['🍇', '🍉']);
fruits.size; // 2
fruits.clear(); 
fruits.size; // 0

Using forEach on a Set object:

let print= function(key , value, set) {
   console.log(value);
}
var fruits = new Set(['🍇', '🍉']);
fruits.forEach(print)
//output
🍇
🍉

Tips and Tricks

  1. When we pass a string as an argument when creating a Set, then it creates a set with all characters as separate elements.
var text = 'LEARN';
var mySet = new Set(text);  
//Set(5) {"L", "E", "A", "R", "N"}

2. Removing duplicate elements from an array

var names= [ 'John', 'Brandi', 'Tony', 'John'];
var uniqueNames = [...new Set(names)]
uniqueNames = [ 'John', 'Brandi', 'Tony'];

3. How array and set are different

  • Set objects store unique values, whereas array can have duplicate values
  • In an array, we need to use the indexOf method to check the availability of element in the array, but in a set we can use the has method, which is compared to be faster than indexOf method.


  • The value NaN cannot be found with indexOf in an array.
  • Set objects let you delete elements by their value. With an array, you would have to splice based on an element’s index.

You can read about map 🗺 in details here.

If you find this helpful surprise 🎁 me here.

Share if you feel happy 😃 😆 🙂 .

Follow Javascript Jeep🚙 if you feel worthy.


https://gitconnected.com/learn/javascript

Best Resources to find select the beautiful gradient for front-end developers.

List of websites where you can select gradient for your websites.

Gradient for frontend developers.
  1. UIGradient

UIGradient is a community contributed collection of beautiful multi-color gradients. You can easily generate gradients , rotate and download the gradient as image . They also provide some open source libraries for iOS, react, etc., .Link to their repo is here

2.ColorSpace

This is a great website which allows us to select the color , direction . This website also generate 3 coloured gradients . It has color selector and we can easily select colours from there.

3.CSSGRADIENT.IO

This is more powerful than above two because you can add any number of colours to the gradient , it generates both the linear and radial gradient color , with the css code. This website also have a detailed explanation about the gradients on their page itself.

4.CSS-GRADIENT.COM

This website has a clean and neat design , even a person who doesn’t know what is gradient can easily generate gradients , because the design is so simple and understandable . It also generate random gradient colours.But we can’t create a rotated gradient in this website.

5.GRADIENTHUNT.COM

This is a website that has a huge list of linear , radial gradients, it also list most popular gradient list . It is not the website for creating gradient colours.We can use the color listed. They also provide an chrome extension

6. WEBGRADIENTS.COM

This website is similar to the gradienthunt.com , But its design is more attractive .It allows us to download the gradient as Png file.This website also offers us a .sketch and .psd file which contains gradient colours as free 😎 .

If you find this helpful surprise 🎁 me here.

Share if you feel happy.

A Simple Introduction to the ES6 Map Data Structure in JavaScript


A Map is a collection of key🔑 — value pairs, similar to an object. It stores the key🔑 — value pairs in the insertion order.

We can create a Map by passing an iterable object whose elements are in the form of key🔑 — value (Eg. [ [1,”one”], [2,”two”] ] ), or you can create an empty Map, then insert entries.

Why we need Map if we have Object s

  1. A Map is similar to Object, but any value can be used as key in maps, but keys in objects are only Strings and Symbols


2. The key🔑 — value pairs in Map maintains the insertion order, whereas Object don’t.

3. You can get the size of the Map, but we don’t have a built-in method to get size in Object (but we can do it manually).

4. Maps are iterable, whereas an Object is not iterable by-default.

5. Maps have additional methods not available to normal objects

Methods in Maps

Map cheatsheet

Example:

  1. Different Ways to create maps


2. Map methods

Let’s create simple Map:

// creating a map 
var fruits = new Map();
fruits.set('🍎', "Apple");
fruits.set('🍋', "Mango");
fruits; //{"🍎" => "Apple", "🍋" => "Mango"}

Map has a property size which returns the current Map size (total number of entries).

// size
fruits.size; // 2

set(🔑, value) → Set the value for the key in the Map and returns the Map. If the key is already present in the map, then the value is overwritten.

// set(key , value) method
fruits.set( '🍇', "Grapes");
fruits; // {"🍎" => "Apple", "🍋" => "Mango", "🍇" => "Grapes"}

get(🔑) → Returns the value associated to the key, or returns undefined if there is no key on the Map that matches the passed key.

// get(key)
fruits.get('🍇'); // GRAPES.
fruits.get('🍊'); //undefined.

delete(🔑) → Delete the entry matching the key and returns true. If the key is not found in the map, then it returns false.

// delete(key)
fruits.delete('🍊') //false
fruits.delete('🍇'); // true

has(🔑) → Returns true if the map has the key provided, else return false.

//HAS(key)
fruits.has('🍇'); // true
fruits.has('🍊'); //false

keys() → Returns a new iterator that contains the keys in insertion order.

//keys
fruits.keys() // MapIterator {"🍎", "🍋"}

values() → Returns a new iterator that contains the values in insertion order.

// values
fruits.values() // MapIterator {"Apple", "Mango"}

entries() → Returns an iterator which has an array of [🔑-value] pair in insertion order.

//entries --> returns key value pair
fruits.entries() // MapIterator {"🍎" => "Apple", "🍋" => "Mango"}

clear() → Delete all key🔑-value pairs from the Map.

// clear
fruits.clear(); // deletes all element
fruits; // Map(0) {}

Things you should know about Map

You can use any value (object or function or primitive ) as a key in the Map . Map uses the SameValueZero algorithm. It is similar to strict equality (===) but the difference is that NaN is considered equal to NaN (i.e, NaN === NaN → true. In normal JS, this is not true. In this case NaN can be used as key and we don’t have any duplicate NaN).

var map = new Map()
var obj = {};
var arr = [];
var nan = NaN;
var fun = function() {}
map.set(obj, "object");
map.set(arr , "array");
map.set(fun, "function");
map.set(nan, "Wrong number");
map.keys(); // MapIterator {{…}, Array(0), ƒ, NaN}
map.values(); // MapIterator {"object", "array", "function","Wrong number"}

Iterating through Map

Using for…of

// creating a map 
var fruits = new Map();
fruits.set('🍎', "Apple");
fruits.set('🍋', "Mango");
fruits; //{"🍎" => "Apple", "🍋" => "Mango"}
--------------------------------------------------------------------
//Method 1:
for(var [key, val] of fruits) {
    console.log(key, value);
}
🍎 Apple
🍋 Mango
--------------------------------------------------------------------
Method 4 --> using entries
for (var [key, val] of fruits.entries()) {
  console.log(key , val);
}
🍎 Apple
🍋 Mango
--------------------------------------------------------------------
// Method 2 --> using keys
for(var key of fruits.keys()) {
   console.log(key, fruits.get(key));
}
🍎 Apple
🍋 Mango
--------------------------------------------------------------------
Method 3 --> using values
for(var val of fruits.values()) {
   console.log(val);
}
Apple 
Mango

If you find this helpful surprise 🎁 me here.

Share if you feel happy.

Follow Javascript Jeep🚙 if you feel worthy.

Javascript Date and Time in Detail

Learn about date and time in Javascript by creating some cool 😎 stuffs


Javascript has a built-in Date object to handle all the time and date related operations. For example, you can display the current date/time, create a calendar, build a Pomodoro timer, code out a 🛑 stop-watch, and much more.

Creating a Date Object

We can create a Date object using the new operator.


This method returns the current date with the time and timezone.


There are 3 other ways to create a Date when using the new keyword:

  1. Creating a Date object with milliseconds

We can create a date object by passing the Date object a timestamp number in milliseconds. For example, new Date(1572840117245).

When we create a date object by passing it 0 milliseconds, it will return the date object for Jan 01 1970 05:30:00. This is the Linux Epoch date/time.

Computers’ time are based on Linux Epoch(Jan 01 1970 05:30:00).

Since zero milliseconds corresponds to this starting point, any value larger is the number of milliseconds since the Linux Epoch.

Note: If the concept of the Linux Epoch is confusing, then keep reading. We’ll see further in the article how we can get the current timestamp from the epoch in JS. Using the Linux Epoch time is a very common technique in programming because it gives us an exact reference point for comparison.

Let’s extend this demonstration further. There are 31 days in January and 24 hours for each day and 60 mins for each hour and 60 sec for each minute and 1000 milliseconds for each second.

So, let’s pass 31 * 24 * 60 * 60 * 1000 = 2678400000 to the Date object. As expected, the result is Feb 1 of 1970 which is a month after the Linux Epoch.


2. Creating a Date object by passing each value


3. Creating Date object using dateString

We can create a Date object by passing the string representation of the date. The string representation is accepted if it is able to be parsed using Date.parse().


The allowed format is YYYY-MM-DDTHH:mm:ss.sssZ

YYYY → year

MM → month

DD → day

T → date and time separator

HH → hours

mm → minutes

ss →seconds

sss → milliseconds

Z → Timezone


Using the Date Object Methods to Get and Update a Date

The Date object that we created in the last section provides many methods to get and update (set) dates.

First, let’s learn the get methods:


Examples


We can change the date by using the set methods on the Date object.

Examples


Tricks for the Date Object

  1. To get the current time in milliseconds, we can use the Date.now method which will return the total milliseconds since the Linux Epoch.
Date.now(); // 1572840117245

Using that time, you can call new Date(1572840117245) and you will see that it corresponds to the current date.

2. To get a formatted string, use the toDateString method:

var dt = new Date(22,5,1997);
dt.toDateString() // Sun Jun 22 1997

3. Find the total number of days in a month in Javascript.

We need to create a function that takes month (months are indexed as 0–11 in JS) and a year as an argument, and we need to return the number of days in that month.

When we create a Date object with year and month, the day of the month is set to 1.

So if we pass new Date(5,2019) then it returns a date object for 1st June 2019.

There can be no month which can have more that 31 days. So if we set the date as 32, then

  • If the current month has 31 days → it points to next month first day,
  • If the current month has 30 days → it points to next month second day,
  • If the current month has 29 days → it points to next month third day,
  • If the current month has 28 days → it points to next month fourth day,

Example:

var d = new Date(2019, 0, 32); // Feb 01 2019
d.getDate(); // 1 (because Jan 2019 has 31 days)
var d = new Date(2019, 1, 32); Mar 04 2019
d.getDate(); // 4 (because Feb 2019 has 28 days)

If we again subtract the current date from 32 then we get the number of days in the month provided.

So let’s create a function that returns the number of days when we pass the year and month:


And those are the key features of the Date object in JavaScript!

If you find this helpful surprise 🎁 me here.

Share if you feel happy.

Follow Javascript Jeep🚙 if you feel worthy.

WebAssembly Part 3 : Different ways to call the exported function in WebAssembly.

How to use ccall, cwrap in emscripten to call the exported function like Javascript functions.

This is Part-3 of WebAssembly Tutorial , You can read Part 1 and Part 2 , which gives you the picture of what is webAssembly.

Let’s write a simple C++ program with some functions

// test.cpp
#include<iostream>
using namespace std;
extern "C" {
    int square(int n) {
       return n * n;
}

}

Compile the above program with the emccc


Once it is compiled load the test.js file generated in your html file.

Now we can call the exported functions in 3 ways

  1. Using Module object
  2. Using ccall emscripten in-built function
  3. Using cwrap emscripten in-built function

Calling the Exported function using Module Object

Module._square(💯);
//10000

Calling the Exported function using ccall & cwrap

ccall & cwrapare in-built function in emscripten, The ccall & cwrap function will be exported ,by-default by the emscripten , if you don’t set any optimization while compiling . If there is any optimation option is set during the compilation , this functions is not exported to our Module object by-default. In those cases, ccall & cwrap functions are not exported, we can manually tell emscripten to export the ccall & cwrap function during compilation by setting the option -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap']” .

1.Command to compile the code


Now in your html file inside the script tag you can call the exported function using the ccall.

When you are using we don’t need to add _ in front of the function name.

ccall(func_Name_In_Srting, returnType, [argument types ], [arguments]))

<script>
    Module['onRuntimeInitialized'] = function() {

console.log("wasm loaded ");
        // call the square function by
        Module.ccall('square', 'number',['number'],[10])
    }
</script>

Don’t forget to add [] to argument types & arguments .

`onRuntimeInitialized is an event that is triggered when the wasm is loaded. By using this method , we can confirm that all C function are executed only after the wasm is loaded.

We can also pass string and return string using ccall.

Consider the c program

// test.cpp
#include<iostream>
#include<string.h>
using namespace std;
extern "C" {
    char* toUpperCaser(char* input) { 
       return strupr(input);
}

}

Compile the method as


Call the methods as

Module.ccall('toUpperCase', 'string',['string'],["javascript jeep"])

This will return JAVASCRIPT JEEP as result.

You can also pass ‘array’ with ‘array’ as argument type.But I don’t know 🤔 how to do that , if someone reading knows , post in comment.

Using cwrap to call exported function

It will wrap the c function inside the javascript function and return the javascript function .

cwrap(func_name, return_type,[‘argument_type’])

var square = Module.cwrap('square','number',['number'])
square(10); //100

Don’t forgot to add the cwrap in EXTRA_EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap']

If you find this helpful surprise 🎁 me here.

Share if you feel happy.

Follow Javascript Jeep🚙 if you feel worthy.

WebAssembly Part 2 : Writing our first calculator program

In this tutorial we will learn how to create a calculator in WebAssembly.


If you aren’t aware of WebAssembly then you can learn here .

First let’s write our C program.

// calculator.cpp
#include<stdio.h>
extern "C" {
   double calculate(double num1, double num2, int operation) {
      double result = 0;
      switch(operation) {

case 1 :
result = num1 + num2;
break;
         case 2:
result = num1 -num2;
break;
         case 3:
result = num1 *num2;
break;
         case 4:
result = num1 /num2;
break;
       }
       return result;
  }
}

To compile this program using emscripten you can use the command


calculator.cpp is the file which we are going to compile ,

-ooutput file , we are requesting emcc to give output as calculator.js

-s WASM =1, →We are requesting emscripten to generate .wasm file, If we want to request emscripten anything, you need to use -s before the option.

-s “EXPORTED_FUNCTIONS=[‘_calculate’]”We are saying emscripten to export the calculate function to the Module object. We need to add _ before the function_name .

Now it will generate two files calculator.js and calculator.wasm .

The emscipten will bind all the function under the Module object. You can access your function using the Module object . eg : Module._calculate(10,10,3);

Now create need to create a html file to load the .js file.

// index.html
<html>
<body>
      http://calculator.js
</body>
</html>

The calculator.js file will load the calculator.wasm file. Keep the js and wasm file in the same folder.

Now we have all the files , inside the calculator.js the calculator.wasm .file is is loaded using fetch api. So now we need to create a server to serve the wasm file to the fetch call.

You can use live server plugin in your IDE to serve the files.

Or

You can use npm with express to create a server,

Steps to create server

install node 
// now create a node project
npm init

//then install express by
npm install express@latest // this install latest version of express

Create a server file

const express = require('express');
   const app = express();
    app.use(express.static('public', {
          setHeaders : function (res, path, stat) {
            if(path.endsWith(".wasm")) {
                res.set('Content-Type','application/wasm');
             }
      }
}));
app.listen(8080, () => console.log("Server 🏃‍ ️@  8080"));

The above code will tells the server to serve the wasm files.

In the server file we are telling the server to look inside the public folder ,if there is any static file is requested.

Now inside your project folder create a folder with the name public . Copy the index.html & calculator.wasm & calculator.js to the public folder.

Start the express server by node server.js

In the browser visit localhost:8080/index.html

Now you can check your function by calling Module._calulate(10,10,3) in the console.


Note

You can create the wasm file without saying -s WASM=1 , when you request a .js file.

Emscripten also generate .html file , with the current wasm and js file loaded.


When compiling like this you don’t need to provide -s WASM=1 , emcc automatically generate js and wasm file and load in the calculator.html file.

If you find this helpful surprise 🎁 me here.

Share if you feel happy.

Follow Javascript Jeep🚙 if you feel worthy.

WebAssembly → Part 1 :Introduction to WebAssembly.

WebAssembly satisfies every developers desire 🤩 of writing ✍️ efficient code.

If you’re a frontend developer👨 , definitely you spend more time with javascript 👨🏾‍💻 than your wife 👰.

We always try to write high performance ⚡️code . But Javascript doesn’t allow us to do that in some cases, where the performance can still be improved.

One of that case is dynamic typing . We don’t have data types in javascript.If you ask a javascript developer about data types , He/she will say "We treat everyone the same way 😜". Javascript, will always interpret the data type on runtime . But not in all cases , V8 engine will solve this problem in some cases.

For performance improvement we need a new technology .WebAssembly is going to be the new technology.

It allows developers to write code on compiled languages like (C/C++/Rust) and compile it into low-level assembly-like language with a compact binary format(.wasm file) that runs with near-native performance on the web.

For compiling C/C++ code we can use Emscripten . A compiler toolchain to convert C/C++ to assembly-like language.

Let’s understand

  • how javascript executed on the web and
  • how emscripten convert C/C++ languages to assembly-like language

after that we deep dive 🏊‍♂️ into WebAssembly.

HISTORY OF JAVASCRIPT

If you don't believe in history then skip this section , and read about the future(WebAssembly) , below this section.

Introduced in 1995 .

Designed in 10 days 😳.

We know how the things will be, If we need to design a system in 10 days 🤓.So the point is it is not designed to be fast.

One of the reason for its slowness is dynamic typing and interpreted language.

After a decade Javascript is not satisfying for developers to meet the requirement of the web users.

So there is a need for new technology to speed up Javascript.

So developers at google developed the V8 engine .

Others also started designing the same .

  • Google → V8 engine -> for chrome
  • Apple → Nitro → Safari
  • Mozilla → SpiderMonkey →Firefox.
  • Opera → Carakan.

V8 compiles JavaScript directly to native machine code before executing it, instead of more traditional techniques such as interpreting bytecode or compiling the whole program to machine code.(source : Wikipedia )

The best part of V8 is, it has JIT(Just in time compiler in it ) , which will increase the performance of the code by monitoring the code.

HOW JIT INCREASES PERFORMANCE .

Js is an interpreted language which means every line is translated to machine code only when it is about to be executed.

What if, there is a huge operation is present inside a loop , then the same line is translated as many time as the loop runs .

The browser need to do something to speed up the execution on this case.

This is where the Profiler is introduced , which will note down 📝 which part of code is executed repeatedly and denotes with some tags 🏷 ,

  • warm (same lines of code are run a few times) → Send to JIT and create a compiled version of code.
  • hot (runs a lot)→ the code is replaced with the compiled version
  • very hot → it is again sent to optimising compiler and get even faster version of the code.

Let’s have deeper look 🕵️‍♂️into JIT,

Consider that, if a part of code is getting warm, then it is send to the JIT and the JIT will compile each line of the function and store in a table with stub(reference of compiled version of code) , then the code is replaced with the stub in the table.

The stubs (reference to compiled version of javascript code ) are indexed based on the line number and variable type . (Consider there is an array which has two types of data , we are looping the data and performing some operation when the code gets warm the JIT will compile the code and for two types there will be separate compiled version of code stored in different index in the table).

If the code is very hot then it is sent to optimising compiler , it will give a blazing fast version of the code.

During creation of the high optimised code the compiler will assume something like the code is only for numbers or string or particular type. This condition is checked each time. If the condition is passed then, it runs compiled version. If the condition fails then it will execute based on the baseline compiled version or sent to interpreter.

If the bailing out process is performed many times then performance improvement is not performed for certain functions, so whenever we develop a javascript application it is better to keep out data and object properties in same format , so that the code will be optimised and will not bail-out more .

LET’S LOOK INTO HOW EMSCRIPTEN WORK.

If we know how High level languages are converted to machine code then we can easily understand how emscrripten works.

We write programs in High level languages(Javascript) , but how machine understands it ?

There comes the translator which converts the HLL to Machine code.But there are different machine architecture are available like x86 , ARM, so we need to translate our HLL code to machine code for each architecture.But we don’t want that , because we need to write separate translator for each architecture.

So how we can solve this problem is, we can convert the HLL to some specific format that format is called Intermediate Representation(IR).

The compiler’s frontend will take the HLL and convert it into IR and the backend will convert the IR to machine code .

The backend of the compiler will generate code according to the architecture of the compiler.

By this way most of the compiler’s backend remains the same , and whenever there is new language created , we are required to write only the frontend for translation .

For converting C to IR we need frontend , that we can use clang , which compile C to LLVM Intermediate representation.

Once the C is converted to LLVM IR format , LLVM will makes some optimisation on the code . From this point we need a backend to convert the IR to webAssembly code(assembly code).

But we don’t need to do this separately , because we have a tool called Emscripten, which will compile the C code to webassembly code.

What makes webbassembly more efficient ?

To understand this we need to know how the javascript code executed by javascript engine.


Steps on Executing the Javascript code.

  1. Parser → parse the source code into something (AST and scope)that the interpreter can run .
  2. Compiling & optimizing → Optimizes the code.
  3. Re-optimizing → JIT optimization.
  4. Execution → Execute the code.
  5. Garbage collection → clean uo 🧹 up unwanted memory.

So let’s look 👀 how webassembly code executes.


In webassembly(wasm)

  1. We fetch the .wasm file from the web mostly it takes few seconds, If the program is compiled with optimization then the size of the file will be less.
  2. Decode and parses the wasm code to Abstract Syntax Tree(AST) .
  3. Compile and Optimize the code , it takes only less time because it is already in the format of assembly code.
  4. There is no re-optimization.
  5. No garbage collection , garbage Collection should be handled manually.

Now, let’s make our hands 🖐 🤚 dirty with webassembly.

How to install webassembly .?

REQUIREMENTS FOR INSTALLING EMSCRIPTEN.

1. First install Git in your system .

MAC

In mac git is pre-installed. To test that you can check the in terminal by using the command

git --version

If you get an error , then your system doesn’t have git . You can install it in two steps.

1.Install mac-command-line tool.
xcode-select --install
//if you have already have mac-command-line-tool then it will throw error as 
xcode-select: error: command line tools are already installed, use "Software Update" to install updates

So now we need to install git in your system.For that visit this link. Download the git installer and install it . Alternatively you can use homebrew .

WINDOWS

In windows you can install git by downloading git installer from here. Then install the .exe file downloaded. Then open a new terminal then check for git --version.

LINUX

Install using apt

sudo apt-get install git

2.Install Python

MAC

On Mac python 🐍 comes pre-installed. You need the python version ≥ 2.7 . To check the python version you can use

python -V

If you don’t have the version required . You can install it by downloading python package from here.

Emscripten requires version 2.7 , so install that or greater version.

WINDOWS

You can download the python from here. Install it, it is straight forward installation. Once you have installed add the python installed PATH to your environment variable.

LINUX

For installing python you need to install build-essential then install python.

sudo apt-get install build-essential
sudo apt-get install python

3 . Install CMake

MAC

In mac you have cmake pre-installed you can verify the version by checking

cmake --version

WINDOWS

In windows you can install CMake by downloading the CMake from here. You can download the CMake under the binary version listed in the website.

Install the downloaded CMake. Then open a new terminal and test

cmake --version // displays the version of the cmake installed.

LINUX

In most of the linux system the cmake is already installed if not then run

sudo apt-get install build-essential(if not previously done ✅ )
sudo apt-get install cmake

4. Install nodeJS

In windows and mac it comes with emscripten.

If you want to install yourself you can download node here. Install it.

In Linux

sudo apt-get install node

5.Install Emscripten

Installing emscripten is so simple and cool 😎

clone emscripten into your system.

git clone https://github.com/juj/emsdk.git

It will download into your system under the folder emsdk.

cd emsdk

There is an executable file name emsdk(emscripten sdk) available in the emsdk folder , which will be used for updating and handling the emscripten packages 📦 .

First update the emsdk

emsdk upadte // you can also do this by git pull for updating emsdk

To install latest emsdk package use

emsdk install latest (On mac 💻 use : ./emsdk install latest )

It will take some time .

Once installed now activate the latest emsdk

emsdk activate latest (On mac 💻 use : ./emsdk activate latest )

If you are on mac run

./emsdk_env.sh // to set environment path for emscripten

If you are on windows run

emsdk_env.bat // to set environment path for emscripten

Now all done ✅ .

Test emscripten by executing the command

emcc --version //displays current version 

You have successfully installed Emscripten in your system.

If can have a more detailed explanation here for installing emscripten.

Let’s have a look at emscripten structure


So let’s write our first program.

  1. Write a C++ Program that returns sum of numbers
// test.cpp
extern "C" {
    int main() {
       return 0;
    }
    int add(int a, int b) {
        return a+b;
    }
}

Write inside the scope of “C” to avoid name mangling in C++.

Now let’s compile our C code to get the wasm file ,

emcc test.cpp  
-S WASM=1 
"EXTRA"
-o test.js 
--std=c++11 

emcc → emscripten compiler that will compile c/c++ program to wasm.

-S → is used to set compiling options.

-S WASM=1 → will tell the compiler to produce wasm file while compiling .

-o test.js → It denotes the output file expected from the compiler.

--std=c++11 → tell the compiler to compile the program with c++11 standard.

Let’s have a look at how our C code is compiled by emscripten .


Emscripten is bundled with both front end and back end .

In front-end the C code is converted to Intermediate Representation(LLVM bitcode).

In back-end the IR code is converted into wasm code.

If we want the javaScript glue code , emscripten also handles that too . For that emscripten uses Fastcomp.

The wasm code generated can be changed to respective machine architecture code(x86, ARM) by browser.

When the compilation is done ✅ , emscipten will generate two files test.js and test.wasm . Load the test.js .

If you found helpful , surprise 🎁 me here.

I referred from , cartoon introduction to web-assembly by link clack . Lin Clark

Different ways and correct way to delete an array .

Learn about what is the right way to delete an array in Javascript.


Let’s create an Array

let array = [1,2,3,4,5];

First way to delete an array is , referencing to a new empty array

array = [];

Let’s look an example

var array1 = [1,2,3,4,5];
var array2 = array1;
array1[0] = 100;
array2[0]; //100 because array1 & array2 points to same reference.
// empty the  array 
array1 = []; 
print the array
array1 ; //[]
array2 ; //[100,2,3,4,5]

So if we empty the array1 by setting the reference to an empty array , will change the reference of array1 to new empty array but the second array points to the old reference. In some cases you need both the array need to deleted for that case use second way.

Second way is to set the length of the array to 0. So it alters the array reference itself.

array.length = 0;

Example

var array1 = [1,2,3,4,5]
var array2 = array1;
array1[0] = 100;
array2[0]; //100 because array1 & array to points to same reference.
// empty the  array
array1.length = 0; //alters array reference so both array is removed
console.log( array1 ) ; //[]
console.log( array2 ) ; //[]
Now if we set ,
array1[0] = "Javascript Jeep 🚙💨 ";
console.log( array2[0] ); //"Javascript Jeep 🚙💨" 
// because still both array points to same array.

You can choose , which way suits you.

If you want to copy an array by value and not by reference then you can use Array.from() .

var array = [1,2,3,4,5]
var copyArrayByReference = array;
var copyArrayByValues = Array.from(array);
array[0] = 100;
console.log(copyArrayByReference[0]); // 100
console.log(copyArrayByValues[0]); // 1

For more detailed and complete reference to Arrays in javascript read here.

If you know more ways to delete an array please mention it . Follow Javascript Jeep🚙.

Creating a toggle switch in CSS.

Awesome people build awesome 😎 things using css.

Let’s create an input checkbox with label, so that we can change the label as switch and turn on the switch when the checkbox is checked and turn off when it is unchecked.

<input type="checkbox" id="toggle" class="checkbox" />
<label for="toggle" class="switch"></label>

The label is placed below the input so that we can select the label using the adjacent selector(+) .

Now the checkbox is created.


Now we need to change the label position as relative , so that we can make use of label::after and style that to appear like a switch.Also set the display : inline-block; so that we can apply width and height for the label.

.switch { 
   position : relative ;
   display : inline-block;
   width : 40px;
   height : 20px;
   background-color: #eee;
   border-radius: 20px;
 }

Now the toggle switch looks like ,


Let’s add the circle ⭕️ to the toggle switch using ::after pseudo class.

.switch::after {
  content: '';
  position: absolute;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background-color: white;
  top: 1px; // TO GIVE AN EFFECT OF CIRCLE INSIDE SWITCH.
  left: 1px;
  transition: all 0.3s;
}

Now the switch looks like


Now we need to change the background color and position of circle when the checkbox is selected , for that let’s use :checked property on input. if the input box is checked then change the background color of label and change the position of the circle.

.checkbox:checked + .switch::after {
  left : 20px; 
}
.checkbox:checked + .switch {
  background-color: #7983ff;
}

Now when the checkbox is checked the input looks like

Final output.

Let’s hide the checkbox

.checkbox { 
   display : none;
}

Follow Javascript Jeep🚙🥶

The Complete Reference for JavaScript Arrays

Learn all the methods available to Arrays in Javascript.


Different ways of creating an array

var array = [];
var array = Array();
var array = Array(3); // array of length 3
var array = new Array()
var array = new Array(3)  // array of length 3

1. Array.from()

The Array.from method creates a new shallow copy from an array-like or iterable object.

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

Syntax : Array.from(sourceArray [, mapFn [, thisArg] ])

Example 1: Array from a string

var str = "123"; //String is iterable
Array.from(str); //['1','2','3']

Example 2: Duplicating an array

var array = [1,2,3,4,5];
var newArray = Array.from(array); //[1,2,3,4,5]

Example 3: Copying array with reference.

var array = [{name : 'john'}];
var newArray = Array.from(array);
   newArray[0].name; //john
   array[0].name = "Sam";
   newArray[0].name ; //Sam 
The value is change to Sam in the copied array because it is shallow copied.

This also behave the same for, array inside an array:

var array = [[1,2]]
var newArray = Array.from(array);
array[0][0] = 5;
newArray ; [[5,2]]

Example 4: Creating a new array of unique values from the array with duplicate values.

var array = [1,2,3,4,5,5,4,3,2,1];
var set = new Set(array); // removes duplicate elements
var uniqueArray = Array.from(set) // [1,2,3,4,5]

Example 5: Using the map function.

var array = [1,2,3,4,5]
var doubledArray = Array.from(array, (value, index) => value+value);
doubledArray; [2,4,6,8,10];

In example 5, we can also create an Array from the object if the object has the property of length. If an object has a property of length Array.from methods thinks it is an iterable object and creates an array of that length and sets the value as undefined.

var obj = {length : 3}
var array = Array.from(obj);
console.log(array); // [undefined, undefined, undefined]

We can use the map function with the above code to create a function that will generate an array with numbers.

function fillArray(length) {

var obj = {length};
    return Array.from(obj, (val, index) => index);
}
fillArray(10); [0,1,2,3,4,5,6,7,8,9]

You can pass the this argument as the third parameter and use it inside the map function.

If we pass undefined or null then it throws a cannot convert undefined or null to object error.

If a non-iterable object is passed, then it returns an empty-array.

2. Array.isArray()

This method checks whether the passed argument is an array.

Syntax: Array.isArray(value)

Returns true if it is an array, otherwise returns false.

Example value which returns true:

Array.isArray([]); //true
Array.isArray([1]); //true
Array.isArray(new Array());//true
// Array.prototype is an array of functions
Array.isArray(Array.prototype); 

Values which return false:

// the result of all statement below evaluates to false
Array.isArray();  
Array.isArray({});   
Array.isArray(null);  
Array.isArray(undefined);
Array.isArray(100);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray(new Uint8Array(32));
Array.isArray({ __proto__: Array.prototype });

3.Array.of()

The Array.of method creates a new array from the arguments passed.

Array.of(1) .  // [1]
Array.of(1,"str",[1,2],{n:10}) // [1, "string", Array(3), {…}]

4.Array.concat

This method merges the array or value passed and creates a new array. The array returned is the shallow copy of the arguments passed.

array1.concat[array2, arr3, arr4, .... arrN]

Example 1: Concat two arrays

var array = [1,2,3]
var newArr = array.concat([7,8,9],[4,5,6]); //[1,2,3,7,8,9,4,5,6]

Example 2: We can also pass the primitive values or object as arguments

var array = [1]
var newArr = array.concat("str",100,{obj:100})//[1,"str", {...}].

Example 3: Concatenation of array of arrays

var arr = [1,2];
var arr2 = [[1,2], [3,4]]
var newArr = arr.concat(arr2) // [1,2,[1,2],[3,4]]
The new Array is the shallow copy of the arguments so if we change the source it affects the copied object.
arr2[0][1] = 9; //[1,2,[1,9],[3,4]]

5. Array.keys

The keys() method returns a new Array Iterator object that contains the indexes of the array.

var arr= [1,2,3];
var keys= arr.keys(); // it returns an Array iterator 

console.log(...keys)

The difference between Object.keys() and Array.keys() is that Array.keys() also take holes as an index;

var arr = [1,,3];
Object.keys(arr); // [0,2]
console.log(...arr.keys()) // 0,1,2

// undefined is not a hole
var arr = [1, undefined, 2]
Object.keys(arr); // [0,1,2]
console.log(...arr.keys()) // 0,1,2

6. Array.values()

Array.values() method returns an Array iterator object that contains the values of the array. By using the iterator we can iterate through all the values of the array.

var array = ['🚒', '🚐', '🚚', '🚲'];
var arrayIterator = array.values(); // Array iterator
console.log(...arrayIterator) // 🚒,🚐,🚚,🚲
// or we can iterate through iterator using for ... of
for (let vehicle of arrayIterator) {
    console.log(vehicle);
}
output : 🚒,🚐,🚚,🚲

7. Array.entries()

The entries method returns return an Array Iterator which contains the index-value pair of the array.

The key is the index of the array and the value is the value at that index.

var array = ['a', 'b', 'c'];
var iterator = array.entries();
console.log(...iterator)
// [0, "a"]  [1, "b"] [2, "c"]
or we can use for..of
for (let entry of iterator) {
console.log(entry);
}
//  output
[0, "a"]
[1, "b"]
[2, "c"]
or We can  use destructing
for (const [index, element] of iterator )
console.log(index, element);
// output
0 "a"
1 "b"
2 "c"

8. Array.push()

The push method adds elements to the end of the array. It mutates the original array.

The push method returns the new length of the array after the item is pushed.

Syntax: array.push(n1, n2,...n)

var array = ['😀', '😃', '😎', '🤪', '🤩']
var newLen = array.push('😳'); //6
// [😀,😃,😎,🤪,🤩, 😳]
newLen = array.push("hi","javascript jeep 🚙", 100); //9
// [😀, 😃, 😎, 🤪, 🤩, 😳,"hi", "javascript jeep 🚙", 100].

9. Array.unshift()

The unshift() method is the same as the push method, but the only difference is that it adds elements to the beginning of the array. It mutates the original array.

The unshift method returns the new length of the array after the item is added.

var array = ['😀', '😃', '😎', '🤪', '🤩']
var newLen = array.unshift('😳'); //6
// [😳, 😀,😃,😎,🤪,🤩]
newLen = array.unshift("hi","javascript jeep 🚙", 100); //9
// ["hi", "javascript jeep 🚙", 😳, 😀,😃,😎,🤪,🤩]

10. Array.pop()

The pop() method removes the last element from the array. It mutates the original array.

The pop method returns the removed/popped element.

var array = ['🚒', '🚐', '🚚', '🚲'];
array.pop(); // 🚲

11. Array.shift()

The unshift() method removes the first element from an array. It mutates the original array.

unshift returns the removed element.

var array = ['🚒', '🚐', '🚚', '🚲'];
array.shift(); // 🚒

12. Array.toString()

The toString() methods convert the array to string and returns the string.

var array = [1, 2, '3', 'hi'];
array.toString(); //1,2,3,hi"

If there is any object in it then it is converted as [object Object]

var array = [1, "string", {}, {name: "Javascript Jeep🚙"}]
array.toString()
// "1,string,[object Object],[object Object]"

If there is an array inside array then the array is flattened.

var array = [1, "string", [1,2,3]]
array.toString(); // 1,string,1,2,3
var array = [1, "string", [1,2,3,[1,2]]]
array.toString() // 1,string,1,2,3,1,2

13. Array.join()

This method creates a string by concatenating all the elements of the array.

Syntax: join(separator) here the separator is an optional string argument.

The strings are joined and each element is separated by the separator provided. If the separator is not passed then by default it is joined with , .

This method returns the joined string.

var array = ["Javascript", " Jeep", " 🚙"];
array.join(); // "Javascript, Jeep, 🚙"
array.join("***"); // "Javascript*** Jeep*** 🚙"

If an array has one element, then the element is returned as a string without the separator.

var array = [" 🚙"];
array.join("-"); // "🚙"

If the array length is empty then it returns an empty string.

[].join(); //""

14 . Array.indexOf()

This method takes an input value and returns the first index of the value in the array.

If the element is not found then it returns -1.

We can also specify the index from which we need to start searching.

This method search the element by using strict equality (===) checking.

Syntax : indexOf(elementToSearch, fromIndex)

fromIndex specifies from which index to start search.

var array = ['🚒', '🚐', '🚚', '🚲'];

The index can be denoted as

The array index is 🚒 → 0 , 🚐 → 1, 🚚 → 2, 🚲 → 3

We can also give fromIndex elements based on negative values

The array negative index is 🚒 → -4, 🚐 → -3, 🚚 → -2, 🚲 → -1

If the fromIndex is positive and greater than the array length then it returns -1 without searching.

If the fromIndex is negative and we need to calculate the computed index that can be calculated by (arrayLength + negativeIndex)

If the computed index is less or equal than -1 * array.length, the entire array will be searched.

Consider an array with length 4

Case 1: If the user provides fromIndex as -2, then the search starts from 4-2=2.

Case 2: If the user provides fromIndex as -10, then the search starts 4–10=-6. In this case the entire array is searched.

Example:

var array = ['🚒', '🚐', '🚚', '🚲'];
array.indexOf('🚲'); // 3
-------------------------------------------------------------------
// search an element from index 3
array.indexOf('🚲', 3); //3; because the 🚲 present in index 3
-------------------------------------------------------------------
//search an element from negative index -1  towards right.
array.indexOf('🚲', -1);//3 because -1 th index is where 🚲present 
-------------------------------------------------------------------
array.indexOf('🚲', -2); // 3
-------------------------------------------------------------------
array.indexOf('🚒', -1) ;
// this method search for 🚒 form index -1(1 in positive index)  towards right , but the 🚒 present in 0 index so it returns -1
------------------------------------------------------------------
array.indexOf('🚒', 10) ;
fromIndex is positive and greater than the array length then it returns -1 without searching.
------------------------------------------------------------------

The indexOf method tests only for values and it doesn’t work for reference.

var a = [[1,2,3],3,4,5];
a.indexOf([1,2,3]); // -1
var a= [{},1,2,3];
a.indexOf({}); // -1

15. Array.lastIndexOf()

This method is similar to the indexOf method, but instead of returning the first index of the element passed, this method returns last index of the element in the array.

This method takes an input value and returns the last index of the passed value in the array.

If the element is not found then it returns -1.

We can also specify the index from which we need to start searching.

This method search the element by using strict equality (===) checking.

Syntax: lastIndexOf(elementToSearch, fromIndex) .

Here the fromIndex specifies the index from which the search takes place in backward. When the index is negative, the array is still searched from back to front.

If we pass -1 then it starts the search from the last element of the array towards the first element.

var array= [1, 2, 3, 4];
array.lastIndexOf(2);     // 1
array.lastIndexOf(7);     // -1
array.lastIndexOf(4, 3);  // 3
array.lastIndexOf(2, 2);  // 1
array.lastIndexOf(2, -2); // 1
array.lastIndexOf(2, -1); // 1
array.lastIndexOf(2,-5); //-1

16. Array.findIndex()

This method returns the first element that satisfies the passed testing function.

If no element satisfies the condition then it returns -1.

Syntax :

array.findIndex( 
testingfunction,
thisArg(optional)

);
// syntax of texting function
testingfunc(
value,
index(optional),
array(optional)
)

Example: Find if an array contains even an number.

var array = [1,3,5,7,10];
function containsEven(value)  {
return value % 2 === 0;
}
array.findIndex(containsEven); // 4
// we can simplify the above function as
array.findIndex(val => val%2===0 )

17. Array.includes()

This method test whether an element is present in the array. If it is in the array then it returns true else returns false.

This method follows same concept of Array.indexOf method.

Syntax: includes(elementToSearch, fromIndex)

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 2);  // true
[1, 2, 3].includes(3, -1); // true
[1, 2, 3].includes(3, 3); // false
[1, 2, undefined].includes(undefined); // true
[1, 2, NaN].includes(NaN); // true

18. Array.reverse()

This method reverse the array. This function mutates/reverses the original array.

This method returns the reversed array.

const array = [1, 2, 3];

console.log(array); // [1, 2, 3]

array.reverse();

console.log(array); // [3, 2, 1]

19. Array.flat()

This method flattens a multidimensional array and returns the flattened array.

We can specify the depth value which denotes how deep the flatten should happen. The default depth value is one. ☝

This method returns a new array with the sub-array elements concatenated into it.

Example 1:

var array = [1,2,3,4,[1,2]]
var newArray = array.flat(); //[1,2,3,4,1,2]

Example 2 :

var array = [1, 2, 3, 4, [1, 2, [5, 6]] ]

// here the depth is 1 , so the [5,6] is not flattened
var newArray = array.flat(); //[1,2,3,4,1,2, [5,6] ]
// when we set depth to 2 , it also flatten the [5,6] element
newArray = array.flat(2); // [1,2,3,4,1,2,5,6]

Example 3:

When we flat an array with holes, the holes are removed.

var arr = [1,,2,3]
var newArray = arr.flat(); //[1,2,3]

20.Array.flatMap()

This method is similar to flat(), but the difference is that before flattening the array, each element of the array is mapped with the mapping function then it is flattened.

Another difference is that flatMap compared to flat only flattens to a depth of 1. We can’t specify how deep the flatten should happen.

Syntax:

var new_array = arr.flatMap(
mapFunc,
this(optional)
);
// Syntax for the map function
mapFunction(
val,
index (optional),
array (optional)

)

Example: Convert all the numbers on the array into even then flatten the array

var array = [1,2,3,4,5,10];
function mapFunc(val) {
  // logic: if val = 3 => 3%2=1 then 3+1-> returns 4
  return (val % 2) ? val +1 : val; 
}
var newArray = array.flatMap(mapFunc);

In flatMap only the first level is flattened.

21. Array.some()

The array.some method checks whether any one of the elements in an array return true for the test function provided.

some returns true if any element passes the test, otherwise it returns false.

array.some(testFunction , thisArg(optional));

Example :

function isOdd(value, index, array) {
return value %2;
}

[2, 6, 8, 0, 4].some(isOdd); // false
[12, 5, 8, 1, 4].some(isOdd); // true

If the array.some method is executed against an empty array, it returns false.

[].some(isOdd); //false

If we didn’t pass the testingFunction, then it will throw an error.

22. Array.every()

The array.every method checks whether all elements of the array returns true for the test function provided.

It returns true if all elements pass the test, otherwise it returns false if any one of the elements fails.

array.every(testFunction , thisArg(optional));

Example :

function isOdd(value, index, array) {
return value %2;
}
[1, 7, 8, 1, 5].every(isOdd);  // false
[11, 5, 9, 1, 7].every(isOdd); // true

If the array.every method is executed against empty array , it returns false

[].every(isOdd); //true

If we didn’t pass the testingFunction, then it will throws an error.

23. Array.sort()

The sort method sorts the elements of the array and returns the sorted array.

We can pass compareFunction to implement custom sorting of the array.

Syntax : sort(compareFunction)

Here the compareFunction passed as an argument is optional.

Example: Without passing a compareFunction. The default sorting of the array is based on the string representation. Read the description in the example if this doesn’t make sense.

Example of default sorting.
var arr = [1, 2, 3, 200, 100];
arr.sort()
arr ; // [1, 100, 2, 200, 3]
The reason for the above result is, by default, sorting is based on strings. It first it converts the value to the string, then values are compared by their sequences of UTF-16 code units values.

Example: Passing a compareFunction

The compare function should return (0, >0, <0).

If the compare function returns:

  • 0 or less than 0 → leave a and b unchanged
  • greater than 0 → swap position
function ascendingOrder(num1, num2) {
if(num1 === num2) return 0;
if(num1 < num2) return -1;
if(num1 > num2) return 1;
}
var arr = [1, 2, 3, 200, 100];
arr.sort(ascendingOrder)

// the above function can be simplified by
/* logic : 
if a > b → (a-b) returns >0, then there is a swap
     if a === b → (a-b) returns 0 , so no swap 
     if a < b; (a- b) returns <0 , no swap */
arr.sort((a, b) => a-b );
To sort an array in descending order do it in reverse
arr.sort( (b, a) => a - b )

24. Array.fill()

This method replaces (mutates) the values of the array with the given value for the given range.

Syntax : array.fill(value, startIndex(optional), endIndex(optional))

It returns the modified array and also changes the source array.

If the startIndex (default value: 0) and endIndex (default value: array.length) is not passed, the entire array is replaced.

var array = [1,2,3,4,5]
array.fill(3, 2, 4) // [1, 2, 3, 3, 5]
array.fill(8,1,2) // [1, 8, 3, 3, 5]
if the start and end index is same then there is no fill takes place
array.fill(9,1,1) // [1, 8, 3, 3, 5]
we can also pass negative index for start and end index argument
array.fill(9,-3,-2) // [1, 8, 9, 3, 5]

if we pass start index < end index then no fill
array.fill(19,4,3) // [1, 8, 9, 3, 5]

Creating an Array of elements with default values:

var array = new Array(5).fill(0); // [0,0,0,0,0]

If we try to fill the element with objects object, then the references are copied.

var array = [1,2,3];
var obj = {name : "Javascript heap"};
array.fill(obj);
obj.name = "Javascript Jeep 🥶";
array //
[ {name: “Javascript Jeep 🥶”}
{name: “Javascript Jeep 🥶”}
{name: “Javascript Jeep 🥶”} ]
array[0].name = "JAVASCRIPT JEEP 🥶";
array //
[ {name: “JAVASCRIPT JEEP 🥶”}
{name: “JAVASCRIPT JEEP 🥶”}
{name: “JAVASCRIPT JEEP 🥶”} ];

25. Array.reduce()

The reduce function executes a reducer function on each element of the array, resulting in a single value output.

This method returns the value that is returned from the reducer function (accumulator value).

syntax: 
Array.reduce(reducerFunction, initialAccumulatorValue(opt));
reducerFunction syntax:
reducerFunction(accumulator, value, index(opt), srcArray(opt)) ;

The accumulator is the final output returned by the reducer function.

Example sum of array elements:

var array = [1,2,3,4,5]
function reducerFunction(accumulator, value) {
   return accumulator + value;
}
var sum = array.reduce(reducerFunction) ; //15
// the above function can be simplified as
array.reduce( (acc, val) => acc+val )

If the initialAccumulatorValue is not provided, the reducer function execution starts from first index.


In the above example, every element of the array is passed to the reducer function. In that function, each value is added to the accumulator (final result).

Example with initialAccumulatorValue:

var array = [1,2,3,4,5]
function reducerFunction(accumulator, value) {
    return accumulator + value;
}
var sum = array.reduce(reducerFunction, 100)
sum ;// 115
// the above function can be simplified as 
array.reduce( (acc, val) => acc+val ), 100) 

If the initial value is provided then the reducer function execution starts from the 0th index.


26. Array.reduceRight()

This method is same as the reduce method, except the reducer function is executed against the element of array from right to left.

Example:

var array = [ " hi ", " from", " Javascript Jeep 🚙 "]
array.reduce( (acc, val) => acc + val );
output : hi from Javascript Jeep 🚙
array.reduceRight( (acc, val) => acc * val );
output : Javascript Jeep 🚙 from hi.

27 . Array.filter()

This method filter the array elements based on the function provided.

The filter method executes the testingFunction against all elements of the array and returns a new array with elements which return true on the testing function. If the testing function returns false for an element, it does not appear in the new array. This method doesn’t alter/mutate the source array.

Syntax:

syntax : filter
----------------
Array.filter(testingFunction, thisArg(optional))
syntax :testingFunction 
----------------------
testingFunction(value, index(optional), array(optional))

Example:

function filterEvenNumbers(value) {
  return value % 2 === 0;
}
var array = [2, 15, 8, 10, 44];
var evenNumbers = array.filter(filterEvenNumbers);
evenNumbers // [2,8,10,44]

// it can be simplified as
even = array.filter( (val) => val %2 ===0 )

28. Array.map()

The map function executes a function provided against all the elements of the array and produce a new array and returns that array.

Syntax:

syntax : map
--------------
var new_array = array.map(mappingFunction ,thisArg(optional))

// syntax : mappingFunction
----------------------------
mappingFunction(val, index(optional), srcArray(optional)) ;

Example:

function square(val) {

return val * val;
}
var array = [1,2,3,4,5];
var squaredNumbers = array.map(square); //1,4,9,16,25
//using arrow function
array.map(v => v * v);

Example 2: Mapping an array of objects and getting the value of the object as an array.

var array = [{name : "brandi love"}, {name : "julia ann"} ];
var upperCaseNames = array.map( (obj) => obj.name.toUpperCase() );
//["BRANDI LOVE", "JULIA ANN"]

29. Array.forEach()

The forEach method executes a method that is provided as an argument against every element of the array once.

Syntax: forEach(callback, thisArg(optional))

It is a replacement for the traditional for loop.

const numbers = [1,2,3,4,5];
const copy = [];

// old way
----------
for (let i=0; i<numbers.length; i++) {
  copy.push(items[i]);
}

// cool way
------------
items.forEach(function(item){
  copy.push(item);
});

Example 2:

var names = ["ironman", "superman", "batman"]
names.forEach( (ele) => {
     console.log( ele.toUpperCase() )
});
// IRONMAN
//SUPERMAN
//BATMAN

30. Array.slice()

The slice method returns a new array with a portion of the source array — it returns sub-arrays.

Syntax : arr.slice(beginIndex(optional), endIndex(optional))

The default value of beginIndex is 0.

If the beginIndex is greater than array length, then an empty array [] is returned.

We can also use a negative index for beginIndex and endIndex.

If the endIndex is not passed or endIndex is greater than array length, then slice all elements from the beginIndex to the end of the array.

It returns a shallow copy of the array, the original array is not modified.

var numbers = [1,2,3,4,5,6];
var greaterThan3= numbers.slice(3); [4,5,6]
greaterThan3= numbers.slice(3,5); [4,5]
greaterThan3= numbers.slice(3,6); [4, 5, 6]

If the endIndex is smaller than startIndex then an empty array is returned.

If the source array contains an object, then the reference is copied.

var array = [ {name: "john"}, {name : "stephen"} ];
var newArray = array.slice();
//if we don't provide start&end index then whole array is copied
array[0].name = "JOHN";
// newArray has an reference of array[0] so the value at newArray is also changed
newArray[0].name ; //JOHN

31 . Array.splice()

The splice() method alters or removes or replaces or add elements to the source array. It is a mutating action on the original array.

Syntax:

var DeletedItemsArray = 
           array.splice(start, deleteCount, item1, item2,...itemN);
startIndex
    index from which the delete or add should take place.
deleteCount 
   number of elements to be deleted
   If deleteCount is omitted, or if its value is equal-to or larger than array.length - start,  then all the elements from start to the end of the array will be deleted.

item1,...--> . elements to be added from the startIndex provided

here deleteCount, items value are optional.

This method returns the array containing deleted items.

Example:

var array = [1,2,3,4,5]
var deletedItems = array.splice(0,0)
//doesn't delete any element because delCount-->0
-------------------------------------------------------------------
var array = [1,2,3,4,5]
var deletedItems = array.splice(0,1); //[1] 
deletes 1 element from 0th index
-------------------------------------------------------------------
var array = [1,2,3,4,5]
var deletedItems = array.splice(0, 1, 2, 4); //[1]
deletes 1 element from 0th index and insert 2, 4
array; //[2, 4, 2, 3, 4, 5]
-------------------------------------------------------------------
var array = [1,2,3,4,5]
var deletedItems = array.splice(2); //[3,4,5]
deletes from index:3 to last element 
because default delCount : arrayLength
array; //[1,2]
-------------------------------------------------------------------
var array = [1,2,3,4,5]
var deletedItems = array.splice(-3, 1, 2, 4); //[3]
deletes 1 element from -3rd index and insert 2, 4
array; // [1, 2, 2, 4, 4, 5]
-------------------------------------------------------------------
var deletedItemsArray = array.splice(); //[]
deletedItemsArray = array.splice(undefined); // [1,2,3,4,5]

Follow Javascript Jeep🚙 🥶.

Design a site like this with WordPress.com
Get started