Important JavaScript Concepts for Developers

Introduction

In this article, we will cover some of the important topics of JavaScript. Before we start, Let's understand the objective of this demonstration, which tells what exactly will be covered in this article.

  • Array in Javascript
  • Objects in Javascript
  • Scope in Javascript
  • Woking with Date in Javascript
  • Events in Javascript
  • Async/Await in Javascript
  • Error handling in Javascript

So, Let's get started.

Array in Javascript

Arrays are used to store multiple values in a single variable. Find a detailed article about Array in JavaScript- How to use Array in JavaScript?

Syntax

const array_name = [item1, item2, ...]; 

Example

const mobiles = ['apple', 'samsung', 'motorola', 'oppo', 'vivo', 'xiaomi'];

Array Items

Converts the array to a string

Syntax 

array.toString();

Example

mobiles.toString();

Array to String

Add an element at the end of the array

Syntax 

array.push(item1, item2, ..., itemX);

Example

mobiles.push('pixel');

Add element at the end of the array

Remove the last element of the array

Syntax 

array.pop();

Example

mobiles.pop('pixel');

Remove the last element of the array

Checks if the array contains an element

Syntax

array.includes(element);

array.includes(element, start);

Example

mobiles.includes('oppo'); 

Checks if the array contains an element

Returns the index of the element

Syntax 

array.indexOf(item);

array.indexOf(item, start);

Example

mobiles.indexOf('motorola');

Return indexOf the element

Join the elements of the array with the given separator 

Syntax 

array.join(separator);

Example

mobiles.join('|');

Join the elements of the array with the given separator 

Return a portion of the array

Syntax 

array.slice(start, end);

Example

mobiles.slice(1,4);

Return a portion of the array

Add elements to the array 

Syntax 

array.splice(index, howmany, item1, ....., itemX);

Example

mobiles.splice(2,0,'pixel');

Add elements to the array 

Objects in Javascript

An object is a standalone entity with properties and types. Find a detailed article about Objects in JavaScript- Objects in JavaScript.

Syntax

const object = {
  property1:value1,
  property2:value2.....
  propertyN:valueN
};  

Example

const person = { 
	name: 'vishal',
	age: 32,
	gender: 'male',
};

const jobObject = {
	designation: 'developer',
	salary: 1000,
};

Object in javascript

Get all object keys

Syntax 

Object.keys(object);

Example

Object.keys(person);

Object.keys

Get all object values

Syntax 

Object.values(object);

Example

Object.values(person);

Object.values

Get all object entries

Syntax 

Object.entries(object);

Example

Object.entries(person);

object.entries

Assign an object to another object

Syntax 

Object.assign(target, ...sources);

Example

Object.assign(person, jobObject);

Object.assign

Scope in Javascript

Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. The two types of scope are Local and Global.

  • Global variables are those declared outside of a block.

  • Local variables are those declared inside of a block.

Example

var PIE = 3.14;  // global scope


function foo() {
	console.log(PIE);
	
	// function scope | local scope
	const age = 30;
	let name = 'Vishal Yelve';
	console.log(age); 
	console.log(name);
}

console.log(PIE);
console.log('calling outside of funtion ' + age);
console.log('calling outside of funtion ' + name);

Scope example

Scope example

Date in Javascript

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects using either local time or UTC (universal or GMT) time.

const date = new Date(); 

Date

getDate()- This method returns the day of the month (1 to 31) of a date.

date.getDate();

getDate()

getMonth()- This method returns the month (0 to 11) of a date.

Note. January = 0, February = 1, and so on.

date.getMonth();

getMonth()

getFullYear()- This method returns the full year (4 digits) of a date. 

date.getFullYear();

getFullYear()

getHours()- This method returns the hour (0 to 23) of a date. 

date.getHours();

getHours()

getMinutes()- This method returns the minutes (0 to 59) of a date. 

date.getMinutes();

getMinutes()

getSeconds()- This method returns the seconds (0 to 59) of a date. 

date.getSeconds();

getSeconds()

getMilliseconds()  This method returns the milliseconds (0 to 999) of a date. 

date.getMilliseconds();

getMilliseconds()

getTime()- This method returns the number of milliseconds. 

date.getTime();

getTime()

setDate()- This method sets the day of the month of a date.

date.setDate(15);

setDate();

setMonth()- This method sets the month of the date. 

Note. January is 0, February is 1, and so on.

date.setMonth(11);

setMonth()

setFullYear()- This method sets the year of a date. This method can also be used to set months and days.

date.setFullYear(2025);

setFullYear();

setHours()- This method sets the hour of a date. This method can also be used to set minutes, seconds, and milliseconds.

date.setHours(5);

setHours();

setMinutes()- This method sets the minutes of a date. This method can also be used to set the seconds and milliseconds.

date.setMinutes(20);

setMinutes();

setSeconds()- This method sets the seconds of a date. This method can also be used to set the milliseconds.

date.setSeconds(15);

setSeconds();

setMilliseconds()- This method sets the milliseconds of a date.

date.setMilliseconds(150);

setMilliseconds();

setTime()- This method sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight of January 1, 1970.

date.setTime(1693532307990);

setTime();

Events in Javascript

JavaScript's interaction with HTML is handled through events that occur when the user or the browser manipulates a page. When the page loads, it is called an event. When the user clicks a button, that click too is an event.

Find a detailed article about Events in JavaScript- Events in JavaScript.

When a user clicks. onClick()

<input type="button" onclick="callAlert()"/>
<script>
      function callAlert(){
        alert("Click call")
      }
</script>

When the user double-clicks. ondblclick()

<input type="button" ondblclick="callAlertonDoubleClick()" />
<script type="text/javascript">
     function callAlertonDoubleClick({
        alert("Double click call")
 }
</script>    

When the user moves the mouse over an element, it's called mouse down. onmousedown()

<p onmousedown="mouseDownCall()">This is onmousedown event triggers when a mouse button is pressed</p>
<script type="text/javascript"> 
  function mouseDownCall() {
    alert("Mouse down call.")
    }
</script>

When an element loses focus. onblur()

Enter Name: <input type="text" id="txtName" onblur="texttoUpper()">
<script type="text/javascript">
 function texttoUpper(){
   var x = document.getElementById("txtName");
   x.value = x.value.toUpperCase();
 }
</script>

When an element gets focus onfocus()

Enter Name: <input type="text" id="txtName" onfocus="colorTextBox(this)">
<script type="text/javascript">
 function colorTextBox(x) {
   x.style.background = "yellow";
 }
</script>

When a user moves the mouse over an element. onmouseover() 

<h2 id="demo" onmouseover="mouseOver()"> Perform the mouse over on this header.</h2>
<script type="text/javascript">
function mouseOver() {
  document.getElementById("demo").style.color = "blue";
}
</script>

When a user moves the mouse out of an element. onmouseout()

<h2 id="demo" onmouseover="mouseOver()" onmouseout="mouseOut()> Perform the mouse over and mouse out on this header.</h2>
<script type="text/javascript">
function mouseOver() {
  document.getElementById("demo").style.color = "blue";
}
function mouseOut() {
document.getElementById("demo4").style.color = "black";
}
</script>

When there is a change onchange()

<select id ="ddl" name="ddl" onchange="ddlChange(this.value);">
  <option value='1'>One</option>
  <option value='2'>Two</option>
  <option value='3'>Three</option>
</select>
<script type="text/javascript">
function ddlChange(value)
{
    alert(value);
}
</script>

When a user presses a key onkeydown()

<input type="text" id="demo" onkeydown="keyDownCall()">
<script type="text/javascript">
function keyDownCall() 
{
 alert('key down call');
}
</script>

When a user releases a key onkeyup()

<input type="text" id="demo" onkeyup="keyUpCall()">
<script type="text/javascript">
function keyUpCall() 
{
  alert('Key up call');
}
</script>

When a user presses a key onkeypress()

<input type="text" id="demo" onkeypress="keyPressCall()">
<script type="text/javascript">
function keyPressCall() 
{
  alert('Key press call');
}
</script>

When a user submits a form  onsubmit()

<form action="#" onsubmit="submitCall()">
  Enter name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>
<script type="text/javascript">
function submitCall() {
  alert("The form was submitted");
}
</script>

When a user resets a form onreset()

<form onreset="resetForm()">
  Name <input type="text">
 <input type="reset">
</form>
<script type="text/javascript">
function resetForm() {
  alert("The form was reset");
}
</script>

when a user selects a text onselect()

<input type="text" value="Vishal Yelve" onselect="selectText()">
<script>
function selectText() {
  alert("You selected some text!");
}
</script>

 Async/Await in Javascript

 Async and Await make promises easier to write. async makes a function return a Promise. await makes a function wait for a Promise.

Find a detailed article about  Async/Await in Javascript- Using Async/Await In JavaScript.

async function getDate() {
	try {
		const response = await fetch(`https://jsonplaceholder.typicode.com/posts`); 
		const data = await response.json(); 
		return data;
	}
	catch (err) {
	  console.log(err);	
	}	
}
getDate().then(data => console.log(data));

Async Await

Error Handling in Javascript

Error handling is an essential part of writing robust and maintainable code in JavaScript.  Errors can occur for various reasons during the execution of code, such as invalid input or network issues. 

Types of Errors in JavaScript

  1. Syntax errors- These occur when the code violates the language's syntax rules.

  2. Runtime errors- These occur when the code tries to execute an invalid operation or access an undefined variable.

  3. Logic errors- These occur when the code produces unexpected results due to incorrect programming logic. 

Find a detailed article about Errors and Exception Handling in JavaScript- Errors and Exception Handling in JavaScript.

Example

function addNumbers(a, b) {
return a + b
}
addNumbers(2 3)
// Syntax error: missing comma

Syntax Error

Try-Catch Statement  

The try-catch statement is a built-in mechanism in JavaScript to handle errors gracefully. The try block contains the code that might generate an error, while the catch block contains the code that handles the error.

Example

try {
// code that might throw an error
} catch (error) {
// code to handle the error
}

Throwing Custom Errors

We might want to throw a custom error to indicate that something has gone wrong in your code. We can use the throw statement to throw a new error object.

Example

function divideNumbers(a, b) {
if (b === 0) {
throw new Error("Divide by zero error")
}
return a / b;
}
divideNumbers(10,0);

Error 2

Error Handling Best Practices

Here are some best practices to follow when handling errors in JavaScript.

  • Always handle errors gracefully to prevent crashes and improve user experience.
  • Use descriptive error messages to help you debug the code
  • Avoid catching generic errors that might hide the actual cause of the error.
  • Use the try-catch statement only for expected errors, not for control flow.
  • Test your error handling code thoroughly to ensure it works as expected.

Summary

In this article, I have tried to cover some of the important Javascript concepts which are mostly used in our development.