14 Feature and Syntax in Javascript You Might Not Have Heard Of

14 Feature and Syntax in Javascript You Might Not Have Heard Of

I’ve been working with JavaScript for years now and to date, every now and then, I still stumble upon some hidden syntax or tricks that I never knew existed. Read more "14 Feature and Syntax in Javascript You Might Not Have Heard Of"

I’ve been working with JavaScript for years now and to date, every now and then, I still stumble upon some hidden syntax or tricks that I never knew existed.

I’ve tried to list down some of the lesser known features of JavaScript. While some of these features are invalid in the strict mode, they are still perfectly valid JavaScript code. However please note, I do not suggest that you start using all of these features. While they are definitely cool, there is a good chance you might start getting angry looks from your teammates, if you start using them.

1. Comma operator

JavaScript has a comma operator. It allows us to write multiple expressions separated by comma in a single line and return the result of last expression

// syntax
let result = expression1, expression2,... expressionN

Here, all the expressions will get evaluated and the result variable will be assigned the value returned by expressionN.

You might have already used Comma operator in a for loop

for (var a = 0, b = 10; a <= 10; a++, b--)

Sometimes it helps when writing multiple statements in a single line

function getNextValue() {
    return counter++, console.log(counter), counter
}

or writing short lamda functions

const getSquare = x => (console.log (x), x * x)
2. Getters & Setters

For the most parts, JavaScript Objects are simple. Let’s say if we have a user object and we try to access age property on it using user.age we get the value of age property if its defined or we get undefined if it’s not. Simple.

But, it doesn’t have to be this simple. JavaScript Objects have the concept of Getters and Setters. Instead of directly returning the value on object we can write our custom Getter function to return whatever we want. Same thing about setting a value.

This allows us to have powerful concepts like **virtual fields, field validations, side-effects**while getting or setting a field

ES5 Getters & Setters

Getters & Setters are not new addition by ES5; they have always been there. ES5 simply adds a convenient syntax to an existing feature. To learn more about Getters & Setters refer this nice article

3. !! Bang Bang Operator

Okay, technically its not a separate JavaScript operator. It’s just the JavaScript negation operator used twice.

But Bang Bang sounds so cool! Bang Bang or Double Bang is a neat trick to convert any expression to a Boolean value.

If the expression is a truthy value, it return true; otherwise it returns false.

Bang Bang operator

4. Tagged Template Literals

Unless you’ve been living under a rock, you would have heard about the Template literals. Template literals are one of the many cool additions by ES6. However, do you know about Tagged Template literals?

Template literals

Tagged Template literals allow you to have more control over parsing the template literals to a string, by adding a custom tag to the template literals. Tag is simply a parser function which gets array of all the strings and values interpreted by the string template. The tag function is expected to return the final string.

In following example, our custom tag — highlight, interprets the values for template literal and also wraps the interpreted values in the result string with a element, for highlighting.

highlight tagged template literal

5. ~ Tilde Operator

Let’s face it — Nobody cares about the Bitwise operators.
When are we ever gonna use it!

Well, there is an everyday use case for the Tilde or Bitwise NOT operator.

Turns out when used with a number, the Tilde operator effective does
~N => -(N+1) . This expression evaluates to “0” only when N == -1

We can leverage this by putting ~ in front of theindexOf(...) function to do a boolean check if an item exists in a String or an Array.

indexOf with Tilde operator

Note: ES6 & ES7 added a new .includes() method in String & Array, respectively. Definitely, it’s a more cleaner way than tilde operator to check if an item exists in an Array or a String.

6. Void Operator

JavaScript has a unary void operator. You might have seen it used as void(0) or void 0 . It has a single purpose in life — Evaluate the expression to its right and return undefined. Using ‘0’ is just a convention. You don’t necessarily have to use ‘0’, it can be any valid expression like void and it still returns undefined.

void operator

7. Constructor Brackets are optional

Yes, the parentheses we add after class name while invoking a constructor — completely optional! (Provided that you don’t need to pass any arguments to the Constructor)

Both the code styles below are considered to be valid JS syntax, and will give you exact same results!

Constructor brackets are optional

8. IIFE Brackets can be skipped

The syntax for IIFE (Immediately Invoked Functional Expression) was always a bit odd for me.
What’s up will all the brackets?

Well turns out those extra brackets are needed just to tell the JavaScript parser, that the upcoming code is a Functional Expression and not a Function. Knowing this, one can imagine, there are many ways to skip those extra brackets & still make a valid IIFE.

IIFE (without return)

The void operator tells parser that the code is functional expression. Hence, we can skip brackets around function definition. And guess what? We can use any unary operators (void, +, !, -, etc.) and this still works!

This is so cool!

However, if you are a keen observer, you may wonder,

Won’t the unary operator affect any result returned from the IIFE ?

Well, it will affect the result. But the good news is, if you care about the result and say you are storing it in some variable, then you don’t need the extra brackets in the first place.

That’s true!

IIFE with return

We add those brackets just for better human readability.

For a deeper dive on IIFE checkout this cool article by Chandra Gundamaraju

9. With Statement

Did you know, JavaScript has a with statementblock? with is actually a keyword in JS. The syntax to write a with block is as follows

with (object)
   statement 
// for multiple statements add a block
with (object) {
   statement
   statement
   ...
}

with adds all the properties of the “object” passed, in the scope chain used for evaluating the statements.

with block example

10. The Function constructor

The function statement is not the only way to define a new function; you can define your function dynamically using Function() constructor along with the new operator.

Dynamic function with Function constructor

The last constructor param is the stringified code of the function and other parameters before that are the function arguments.

11. Function Properties

We all know Functions are first class objects in JavaScript. Hence, no one is stopping us from adding custom properties to a Function. It is perfectly valid JS thing to do. Yet, it is rarely used.

So when would we want to do this?

Well, there are a few good use cases for this. For example,

Configurable Functions

Let’s say we have a function called greet. We want our function to print a different greeting message based on different locales. This locale should also be configurable. We can maintain a global locale variable somewhere or we can implement the function using functional properties as shown below

greet function with locale property

Function with Static Variables

Another similar example. Let’s say, you want to implement a Number Generator that generates a sequence of ordered numbers. Normally, you’ll use Class or IIFE with a static counter variable to keep track of last value. This way we restrict access to the counter and also avoid polluting the global space with extra variables.

But what if we want the flexibility to read or even modify the counter & yet not pollute the global space?

Well we could still create a Class, with a counter variable and some extra methods to read it; or we can be lazy and just use properties on a function.

generateNumber function with counter property

Phew!! This is a long list & we are just about halfway there. If you wanna take a break, now will be a good time. If not, you are a brave warrior & I salute you.

Let’s continue!

12. Arguments Properties

I’m sure most of you are aware of arguments object inside a function. It’s an array like object available inside all the functions. It has the list of arguments passed to the function while it was invoked. But it also has some other interesting properties on it,

  • arguments.callee: Refers to the function currently invoked
  • arguments.callee.caller: Refers to the function that has invoked the current function

callee & caller

13. + Plus Operator

Ever wanted to quickly convert a string to a number?

Just prefix the string with + operator.
Plus operator also works for negative, octal, hexadecimal, exponential values. What’s more, it even converts a Date or Moment.js object to the timestamp!

Plus operator

14. Labelled statements

JavaScript has the concept of label statements. It allows us to name loops and blocks in JavaScript. We can then use these labels to refer back to the code later while using break or continue .

Labelled statements are particularly handy in nested loops. But we can also use them to simply organize code into blocks or create a breakable block

labelled statements

Note: Unlike some other languages, JavaScript doesn’t have goto construct. Hence, we can only use labels with break and continue.

You may also like: 10 More Useful Angular Features You Might Not Have Heard Of

If you know any more of such JavaScript quirks or have found interesting use-cases to leverage these features, please share your experiences below. I would love to hear about it!

All the source code used is available here.

Happy Coding!!!!!!!!!

20 Things to Learn and Effective tips to becoming JavaScript Master

20 Things to Learn and Effective tips to becoming JavaScript Master

Do you want to get into web development? Or perhaps you’re fascinated with code and software? If so then JavaScript is a good choice for you. In this post, we will for you 20 things to learn and Simple Effective tips on the way to becoming a JavaScript Master

10 THINGS TO LEARN

I guess you are a web developer. Hopefully you are doing fine and you have a great job, maybe you are even self-employed or working as a freelancer. Maybe you are just starting out as a web developer, maybe you have been working as a programmer for a longer period already.

However comfortable you are with JavaScript, it is always good to get a refresher on some topics to read up about or get them on the radar in the first place. Here are 10 things you definitely have to learn before you can call yourself a master in JavaScript.

1. Control Flow

Probably the most basic topic on the list. One of the most important, maybe the most important one. If you do not know how to proceed with your code, you will have a hard time. Knowing the ins and outs of basic control flow is definitely a must.

  • if else — If you don’t know these, how did you write code before?
  • switch — is basically if else in a more eloquent way, use it as soon as you have multiple of different cases.
  • for — Do not repeat yourself, this is what loops are for. Besides the normalfor -loop for of and for in come in very handy. The big advantage of for -loops is that they are blocking, so you can use async await in them.
  • Advanced conditionals — Using the ternary and logical operators can make your life a lot easier, especially when you try to do things inline, meaning that you don’t want to save values to use them later. Example:
// ternary
console.log(new Date().getHours() < 12 ? 'Good Morning!' : 'Time for a siesta')
// logical operators
const isJsMaster = prompt('Are you a JavaScript master?') === 'true'
console.log(isJsMaster && 'proficient coder')

2. Frontend Framework

The big three are React.js, Angular and Vue.js. If you are looking for a job nowadays, you will almost always have one of those listed as a prerequisite. Even if they change quite quickly, it is important to grasp the general concept of those to understand how applications work. Also, it is just easier to write apps that way. If you haven’t decided which train you want to jump on, my suggestions is React.js. I have been working with it for the last couple of years and did not regret my decision.

3. Asynchronity

This is a very important aspect of JavaScript, Either you are fetching data from the backend or you are processing requests asynchronously in the backend itself. In pretty much all usecases, you will encounter asynchronity and its caveats. If you have no idea what that is, you will probably get a weird error, which you will try to fix for a couple of hours. If you know what it is, but you don’t really know what to do about it, you will end up in callback-hell. The better approach is to use promises and/or async await in your apps.

4. Node.js / Express

Even as a frontend developer, you should know the basics of node.js. Ideally, you would also know how to spin up a simple express server and add some routes or change existing ones. JavaScript is great for writing scripts to help you automate a lot of tasks. Therefore, knowing how to read files, work with filepaths or buffers gives you a good toolset to build anything.

You may also like: Best Design Patterns for writing JavaScript Web applications

5. Error handling

This took a while for me. It does not matter if you are working on frontend or backend, the first year or so, you will probably default to console.log or maybe console.error for ‘handling’ errors. To write good applications, you definitely have to change that and replace your lazy logs with nicely handled errors. You may want to check out how to build your own Error constructor and how to catch them correctly, as well as showing the user what the actual problem is.

6. Data Models

Similar to moving through your application continuously, you have to decide where to group specific information chunks and where to keep them separate. This does not only apply to building database models, but also function parameters and objects or variables. Example:

const calcShape = (width, height, depth, color, angle) => {...}
const calcShape = ({width, height, depth, color, angle}) => {...}

7. DOM Manipulation

This is an interesting topic. Normally it is somewhat left out in the day today life as a developer. Maybe you learned jQuery and never felt the need to pick up some native DOM manipulation skills, maybe you are just using a frontend framework, where there is rarely a need for custom DOM manipulation. However, I think this is a crucial part of understanding JavaScript, at least in the frontend. Knowing how the DOM works and how to access elements gives you a deep understanding of how websites work. In addition, there will be the point where you have to do some custom DOM manipulation, even when you use modern frontend frameworks, and you definitely do not want to put jQuery in your package.json just to access an element.

8. Functional Approach

There is an everlasting debate about functional vs. object-oriented programming. You probably can achieve the same thing with both of the approaches. In JavaScript, it is even easier, you have both of the approaches available. Libraries like lodash give you a really nice collection of tools for building applications with a functional approach. Nowadays, it is not even necessary to use external libraries any more. A lot of the most important functions have been implemented in the official JavaScript specification. You definitely should know how to use map reduce filter forEach and find.

9. Object Oriented Approach

Similar to the functional approach, you also have to get familiar with object oriented JavaScript, if you want to master it. I neglected that part for a long time in my career and just worked my way through with a workaround, but sometimes it is definitely better to use objects/classes and instances to implement specific functionality. Classes are widely used in React, MobX or custom constructors.

10. Bundling / Transpilation

Unfortunately, this is a big part of web development. On the one hand I should not say unfortunate, because it is great to be able to write code with all the newest features. On the other hand, the reason why I’m saying that is that we always have to keep in mind that there’s older browsers around that may not support these features, therefore we have to transpile our code into something else that the old browsers understand. If you work with node.js, you will probably have less exposure to transpiling your code. The de-facto standard for transpilation is babel.js, so get familiar with it. As for bundling your code and tying everything together, you have a couple of options. Webpack was the dominant player for a long time. Some time ago, parcel popped up out of nowhere and is now my preferred solution, since it is so performant and easy to configure, although not perfect.

This is not specific to JavaScript, but incredibly helpful in a lot of use cases. Just as confusing as well. Getting to know the syntax of Regular Expressions definitely takes some time and remembering all of the different options is impossible.

10 SIMPLE and EFECTIVE TIPS

Do you want to get into web development? Or perhaps you’re fascinated with code and software? If so then JavaScript is a good choice for you.

Why JavaScript?

Javascript is the scripting language of the internet and one of the most essential web technologies along with HTML and CSS. It’s a high-level, interpreted programming language that conforms to the ECMAScript specification. In more simplistic terms, it’s what allows you to implement and display complex things on your webpage, to create content, to animate images and tons of other amazing possibilities with just a few lines of code.

There’re plenty of reasons to learn this wonderful programming language. The most important one is the fact that JavaScript runs everything and everywhere. Most of the prominent websites are built on the backbone of JavaScript while currently there are more than 3 billion devices be it Smartphones or desktops. JavaScript went through a massive surge of popularity and quickly become the most dominant language in the world of software. In light of this, it’s obvious that Javascript skills are in high demand by companies everywhere. For all these reasons and more, it’s lucrative to have JavaScript skills on your resume.

Why is it challenging?

Learning JavaScript is easier said than done. Newcomers often run into similar kinds of problems such as difficulties in understanding confusing concepts. Not only that, but JavaScript also has an ever-changing tooling landscape one that makes it even far more grueling to understand. It’s hard to find the motivation to complete a demanding task such as this. JavaScript is also a vigorously un-typed language which means that the same thing in one code can easily mean something different depending on the context and medium. It also is extremely hard to debug due to a non-existent support system for different classes.

Tips for JavaScript Beginner

So the question is how to learn JavaScript? Similar to every complicated thing in life, you can learn JavaScript coding through constant practice and by never giving up. To help you in this task, we have written down the best way of learning this skill just for you! Try to follow these tips to enhance your learning experience.

1. Keep experimenting & Interact with veterans

Find and make your own way to solve problems related to JavaScript. Keep experimenting with the problems and what you have learned so far. Also, do interact with the veterans as the large community lead to more support and help you’ll be able to receive. Fortunately, JavaScript has one of the largest internet communities that is all about giving and receiving help and exploring the world of JavaScript. Take advantage of that! Meet up with the experts to not only motivate yourself to study but to learn as well. You might even be offered a mentorship! By being a part of a community, you’ll also be able to keep up to date with new, innovative tools!

2. Do not rush! Go step by step

I know it’s tempting to move on immediately once you understand a concept, but don’t! Instead, play with what you have learned, get comfortable and even combine it with the previous lessons. Start from beginner’s level and cover all the topics from tutorials, check resources, implement what you have learned and when you are finally confident of your beginner level skills, then move on to the intermediate level and after that, to advance level. By limiting the learning content and keeping in touch with the previous lessons, you’ll be able to retain the material in your head and find it easier to remember key concepts. The process seems long for sure but it actually takes far less time since you don’t have to keep revising and is actually quite fun. There’s really nothing that you cannot do with JavaScript in regards to web development.

3. Look out for JavaScript Resources

The internet has millions of sources available for you to use. Take “JavaScript: The Definitive Guide” by David Flanagan. It’s a book that has been forever considered a bible for JavaScript programmers across the world. In it is a comprehensive guide that is well-organized and detailed for new programmers to learn and old programmers to revise. Another book that you can read is “You Don’t Know JS: Up and Going” by Kyle Simpson which provides the necessary background for those with limited knowledge about programming. The entire series introduces more complex and harder parts of the JavaScript language as you read on one book at a time. Furthermore, there are tons of articles, blog posts and even YouTube videos available for reference. Don’t waste these valuable resources!

You may also like: Keeping your JavaScript code clean forever and scalable

4. Right attitude

The first thing you need to do is to go with the right attitude to learn JavaScript. Learning JavaScript is going to become needlessly more bothersome if you approach it with the wrong mindset. Trying to learn it with an “I need to get this over” mindset is not going to take you anywhere. It’s a huge struggle to face and you truly have to be passionate about code to learn it. Not only that, you need to remind yourself to have fun with what you’re learning as JavaScript code is capable of astonishing things once you get the hang of it.

5. Start Slowly

A mistake many beginners make is that they directly start working on frameworks such as jQuery, AngularJS, Backbone, etc. You should never do it. Instead, you should start working on DataTypes and in-built methods. After getting enough of the fundamentals, you can try NodeJS. Trust me, NodeJS is very simple, just a JavaScript code backed up with inbuilt libraries. Then, you can try frameworks.

6. Find the perfect editor for JavaScript

You can’t code without a text editor. Fortunately, you have tons of options to choose from. To write JavaScript code, you can either use your Windows notepad or even download programs such as Notepad++ or Visual Studio Code. Either way, after going through all possible editors, choose the one that you’re most comfortable to work on as this is where you’ll be spending most of your time. Also when you’re starting out, it’s essential to choose an editor that has a simplistic interface and will support you as a beginner.

7. JavaScript Tutorials!

If you search the web for JavaScript tutorials, there are a vast number of tutorials available online on sites such as CodeAcademy, FreeCodeCamp, etc. If you’re a beginner then you should start from beginner level JavaScript tutorials and then move on to intermediate and advanced level. Tutorials are like doing grammar exercises and the sites with JavaScript tutorials are ideal for learning the basics and getting used to the syntax. Learning JavaScript is no different than learning French or Spanish. It takes time.

8. Start Ajax and Async after getting a hang of the basics

After you have spent quite a lot of time on JavaScript, start working on Ajax and Async concepts. Learn how to use different functions on JavaScript and use classes as well. All of these things take quite a lot of time to master but trust me; all your hard work will surely be rewarded.

9. Challenge yourself! Explore JavaScript and learn

When it comes to learning JavaScript, there is always something you can learn as it is a never-ending process. A lot of people end up never improving their JavaScript coding by spending too much time only doing what they are confident about. Make sure that you’re not one of them. Every time you finish a lesson, ask yourself if you have learned something you didn’t know before. That is the key to success. Be mindful of what you want to learn or improve your knowledge of. Make sure that you’re challenging yourself and growing as a developer instead of conforming to a single comfort zone.

10. Keep yourself up to date and be prepared

JavaScript isn’t an easy skill to learn. If it was, it wouldn’t be held with the same reverence as it is in the labor market now. You need to understand the fact that learning JavaScript would require a huge amount of time and dedication. It’s not going to be an easy road. Not only is JavaScript already a complex and intricate skill to master, but it is also a growing field which would require you to stay updated with the new web development practices. Prepare yourself that it’s going to consume a majority of your time. Be patient too. You’re not going to learn JavaScript in a month and maybe not even in a year. All the time spent is going to be grilling, demanding but remember that it will also be completely worth the trouble.

BONUS

Learning JavaScript is constant work and quite difficult but with the right attitude and determination, learning it can be an extremely satisfying experience. All you need is passion and a hunger to learn. Hopefully, with the above-mentioned tips, as well as the other brilliant and detailed materials available online, you’ll be able to grasp JavaScript as quickly as possible while also having a great enjoyable ride.

Hopefully you know all of the topics listed above already. If not, put in the work and try to become a master in JavaScript! It is definitely worth it. Remember that practicing is everything when it comes to coding, so even if you are not familiar with these concepts or know them but you don’t really know how to apply them, it will come in the future.

What do you think about the list? Is something missing? Do you think other topics are more important when coding? Let me know in the comments!

Thank for visiting and reading this post! I'm highly appreciate your actions! Please share if you liked it!

Block any Event of Browser using Javascript codes

Block any Event of Browser using Javascript codes

In this article, we will go through possible ways to block any event using Javascript codes

In most browsers there are three possible kinds of events triggered when a keyboard key is pressed or released,

  1. keydown
  2. keypress
  3. keyup

You can check which key was pressed or released whenever KeyboardEvent is triggered because that event contains information and based on that event information you can write you custom logic to handle that event.

Note

The implementation will fail if the user disables JavaScript.

Base Code to trace any javascript event,

document.addEventListener("keydown", function(event)  
{  
   console.log(event.which);  
   console.log(event.keyCode);  
   console.log(event.shiftKey);  
   console.log(event.altKey);  
   console.log(event.ctrlKey);  
   console.log(event.metaKey);  
}   

List of Avaibale Javascript Code

We can use the below code to prevent opening of context menu, copy cut paste, or view source code on any page.

Many times we want to disable some existing functionality on a webpage for any security reason.

Eg: prevent images from being downloaded, copy the content, etc...,

Disable context menu on right click,

$("body").on("contextmenu", function (e)
   {
      return false;
   });
});

Or,

document.oncontextmenu = function() {
   return false;
}

Disable right click menu on particular section on page,

$(document).ready(function(){
   $("#youDivSectionId").bind("contextmenu", function(e) {
      return false;
   });
});

Disable Cut, copy, paste,

$(document).ready(function(){
   $('body').bind('cut copy paste', function (e)
   {
      e.preventDefault();
   });
});

Let's Block the same cut, copy, paste events with javascript codes,

$(document).ready(function(){
$(document).keydown(function(event) {
   //event.ctrlKey = check ctrl key is press or not
   //event.which = check for F7
   // event.which =check for v key
   if (event.ctrlKey==true && (event.which == '118' || event.which == '86')) {
      event.preventDefault();
      }
   });
});

Prevent browser Debugger console example,

$(document).keydown(function (event) {
// Prevent F12 -
if (event.keyCode == 123) {
   return false;
}
// Prevent Ctrl+a = disable select all
// Prevent Ctrl+u = disable view page source
// Prevent Ctrl+s = disable save
if (event.ctrlKey && (event.keyCode === 85 || event.keyCode === 83 || event.keyCode ===65 )) {
   return false;
}
// Prevent Ctrl+Shift+I = disabled debugger console using keys open
else if (event.ctrlKey && event.shiftKey && event.keyCode === 73)
{
   return false;
}
});

Thank you for reading ! I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.

20 Fastest Methods to Easily identify Array's Operation in JavaScript

20 Fastest Methods to Easily identify Array's Operation in JavaScript

In this post, I'll show you 20 Methods to Get to Know JavaScript Array Operations

Methods to Get to Know JavaScript Array Operations

For example, Let’s create an Array.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];
1. Filter

The filter() method creates a new array with elements that return true from the callback function.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

var vegFoods = foods.filter( (food) => isVeg(food) );

vegFoods; ["🍎", "🍊", "🍕"];
2. lastIndexOf

First last index of a given element in the Array, if it is not present, it returns -1.

var foods = ["🍎", "🍊", "🍗", "🍕", "🥩", "🍎"];

foods.lastIndexOf('🍎'); // 5

foods.lastIndexOf('🍔'); // -1
3. Length

Returns the number of an element of the Array.

foods.length; // 5

Tip: We can change the length property to delete elements.

foods.length = 0;

foods; // []
4. Push

Add an element to the end of an Array.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

foods.push('🍇');

foods; // ["🍎", "🍊", "🍗", "🍕", "🥩", "🍇"]

Tip: Use push with the spread operator () as an alternative to the concat method.

var numbers = [1,2,3,4,5];

var num2 = [6,7,8,9,10];

numbers.push(...num2);
5. Unshift

Add an element to the beginning of an Array.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

foods.unshift('🍇');

foods; // ["🍇", "🍎", "🍊", "🍗", "🍕", "🥩"]

Tip: Use unshift with the spread operator () to concat elements at the beginning.

var numbers = [1,2,3,4,5];

var num2 = [6,7,8,9,10];

numbers.unshift(...num2);
6. Pop

Removes the last element of the array.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

foods.pop();  // "🥩"

foods; // ["🍎", "🍊", "🍗", "🍕"]

Tip: We can use the pop method in stack implementation.

7. Shift

Remove the first element of the array.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

foods.shift();  // "🍎"

foods; // ["🍊", "🍗", "🍕", "🥩"]

Tip: We can use the shift method in dequeue operations on Queue implementation.

8. Join

Joins the elements of Array to String.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

var joinedFood = foods.join(); // "🍎,🍊,🍗,🍕,🥩";

var joinedFood1 = foods.join('--'); // "🍎--🍊--🍗--🍕--🥩"

Tip: Use as an alternative to string concatenation.

var arr = ['J','a','v', 'a'];

var str = '';

// without join

for(let i = 0, len = arr.length; i < len ; i++) {

     str += arr[i];
		 
}

// with join

str = arr.join(''); // Java
9. Concat

Concat an Array with arguments.

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

var newArray =  array.concat(1,2,3, [12,12,34], undefined, null);

newArray; // [1, 2, 3, 4, 5, 1, 2, 3, 12, 12, 34, undefined, null]
10. Reverse

Reverse the elements of the array.

var foods =  ["🍎", "🍊", "🍗", "🍕", "🥩"];

foods.reverse();

foods; // ["🥩", "🍕", "🍗", "🍊", "🍎"]

Tip: Reversing string.

var str = "Anitha";

var strArray = [...str].reverse().join('');
11. indexOf

First index of a given element in the Array, if it is not present, it returns -1.

var foods = ["🍎", "🍊", "🍗", "🍕", "🥩", "🍎"];

foods.indexOf('🍎'); // 0

foods.indexOf('🍔'); // -1
12. Some

Checks if any of the elements return true from the callback function.

var num = [1,2,3,4,10, 12];

num.some(n => n > 10); // true

num.some(n => n > 100); // false
13. Every

Check if all of the elements return true from the callback function.

var num = [1,2,3,4,10, 12];

num.every(n => n > 10); // false

num.every(n => n > 0); // true
14. Sort

Sort the elements of the array. By default, it sorts based on char code. We can also pass our sort function.

var arr = ['b', 'c', 'd', 'e'];

arr.sort(); // ["b", "c", "d", "e"]

// custom sort

var arr = [1,2,3,4,5, 11 ];

arr.sort( (a, b) => a-b ); // [1, 2, 3, 4, 5, 11]

Be careful using the sort method, because it sorts based on char code, in which “11" < “2”.

var arr = [1,2,3,4,5, 11 ];

arr.sort();  [1, 11, 2, 3, 4, 5]

Tip: Shuffle an Array with sort.

var arr = [1,2,4,1,2,3];

arr.sort( () => Math.random() - 0.5);
15. Reduce

The reduce() method executes a reducer function (which you provide) on each element of the array, resulting in a single output value.

Example one:

var apples = ["🍎", "🍎"];

var juice = 🧃 ;  // think as empty can 

function makeJuice(juice, fruit) {

    let fruitMix = grind(fruit);
		
    return fruitMix + juice;
		
}

apples.reduce( makeJuice , juice);

Example two:

var arr = [1,2,3,4,5];

var result = 0;

function add(res, currentNum) {
   return res + currentNum;
	 
}

arr.reduce(add, result);
16. ReduceRight

Similar to reduce but elements are passed to the callback function from right to left.

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

function sum(result, num) {

   console.log(num);
	 
   return result + num;
	 
}

var result = 0;

array.reduce(sum, result);

// go from left to right i.e., 1,2,3,4,5

array.reduceRight(sum, result);

// go from right to left i.r., 5,4,3,2,1
17. Map

Creates a new Array from the value returned by the callback function, which is executed for every element of the Array.

var numbers = [1,2,3,4,5];

function double(num) {
   return num * num;
}

var doubledNumbers = numbers.map(double) 
18. Splice

The splice() method will remove n number of elements from the specific index and also inserts the elements.

var array = [1,2,4,5];

array.splice(2, 0, 3); //insert 3 at index 2

array;  // [1,2,3,4,5]

array.splice(2, 1, 30);//remove 1 item from index 2 and insert 30

array; // [1, 2, 30, 4, 5]

Tip: Use this method to inset an element at a specific index.

function insertElementAtIndex(array, index, elem) {
   array.splice(index, 0, elem);
}
19. Slice

The slice() method returns a shallow copy of a portion of an Array.

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

array.slice(1); // [2, 3, 4, 5] --> slice starts from index 1 to end

array.slice(1,3); // [2,3]--> slice from index 1 to (3-1)

Tip: Get last element of the array:

// get last n elements

array.slice(-n);

n = 1

array.slice(-1); 5

if n = 3

array.slice(-3); //  [3, 4, 5];
20. forEach

Executes a callback function once for each Array element. We cannot use break and continue in forEach, map functions.

var numbers = [1,2,3,4,5]

numbers.forEach((e) => {

  console.log(e)
	
});

Thank you for reading !