DEV Community

Cover image for JavaScript for Beginners: A Complete Guide
Vaibhav Gupta
Vaibhav Gupta

Posted on

JavaScript for Beginners: A Complete Guide

JavaScript is a versatile, high-level programming language widely used for creating interactive and dynamic web pages. It plays a crucial role in modern web development.

Key Benefits:

  • Flexibility: JavaScript is highly flexible and can be used both on the client side (in web browsers) and the server side (with Node.js), enabling developers to build full-stack applications.
  • Interactivity: It enables the creation of engaging web experiences by allowing developers to respond to user actions or events in real-time.
  • Extensibility: JavaScript boasts a vast ecosystem of libraries and frameworks that provide ready-to-use solutions and streamline development processes.

Core Features:

  • Object-oriented programming: JavaScript is an object-oriented programming language, which means that it allows you to create objects that have properties and methods. This makes it a powerful language for building complex applications.
  • ECMAScript: JavaScript is based on the ECMAScript standard, which ensures that JavaScript code is compatible across different browsers. This makes it a reliable language for developing web applications.

  • Asynchronous programming: JavaScript supports asynchronous programming, which means that you can run multiple tasks at the same time. This makes it a powerful language for building responsive web applications.

  • Event-driven programming: JavaScript is an event-driven language, which means that it responds to events that occur in the browser. This makes it a powerful language for building interactive web applications.

  • DOM manipulation: JavaScript can be used to manipulate the Document Object Model (DOM), which is the underlying structure of a web page. This makes it a powerful language for building dynamic web pages.

Here are some additional benefits of JavaScript:

  • It is easy to learn: JavaScript is a relatively easy language to learn, even for beginners. This is because it has a simple syntax and is similar to other programming languages like Python and Java.
  • It is cross-platform: JavaScript code can be run on any platform that has a web browser. This makes it a great choice for developing web applications that need to be accessible to users on all devices.
  • It is open source: JavaScript is an open-source language, which means that it is free to use and modify. This makes it a great choice for developers who want to be able to customize their code.

JavaScript Variables

A JavaScript variable is a name that refers to a value. Variables are used to store data temporarily during the execution of a JavaScript program.

There are two types of variables in JavaScript:

Local variables are declared inside a function or block of code. They are only accessible within the function or block where they are declared.

Global variables are declared outside of any function or block of code. They are accessible from anywhere in the JavaScript program.

To declare a variable in JavaScript, you use the var keyword. For example:
var myVariable = "Hello, world!";

The var keyword is the traditional way to declare variables in JavaScript.

However, there are two newer keywords that you can use to declare variables: let and const.

The let keyword is used to declare a local variable. It is similar to the var keyword, but it has a few advantages. For example, let variables are block-scoped, which means that they can only be accessed from within the block where they are declared. This can help to prevent errors caused by accidentally accessing a variable from outside of its scope.

The const keyword is used to declare a constant variable. A constant variable cannot be changed once it is assigned a value. This can be useful for variables that should not be changed, such as the name of a variable or the value of a mathematical constant.

var name = "Vaibhav Gupta";
let age = 20;
const pi = 3.14;
Enter fullscreen mode Exit fullscreen mode

Datatypes in JavaScript

There are two types of data: -

  • Primitive
  • Non-Primitive

Primitive Datatypes are:

String: A sequence of characters. Strings can be enclosed in single quotes (') or double quotes (").

Number: A numeric value. Numbers can be integers or floating-point numbers.

BigInt: A large integer value. BigInts can be used to store integers that are too big to be represented by a normal JavaScript Number.

Boolean: A value that can be either true or false.

Undefined: A value that has not been assigned a value.

Null: A value that indicates that a variable does not have a value.

Symbol: A unique identifier. Symbols are used to create object properties that are guaranteed to be unique.

// String
const str = "Hello";

// Number
const num = 123;

// BigInt
const bigNum = 12345n;

// Boolean
const bool = true;

// Undefined
const undefinedVar;

// Null
const nullVar = null;

// Symbol
const symbol = Symbol("mySymbol");
Enter fullscreen mode Exit fullscreen mode

Non-Primitive Datatypes are:

Array: An ordered collection of elements. Arrays can be used to store a collection of data in a structured way.

Object: A collection of properties. Objects can be used to store data in a structured way, and they can also be used to create custom data types.

RegExp: A regular expression. Regular expressions are used to match patterns in strings.

Function: A block of code that can be executed. Functions are used to encapsulate code and make it reusable.

Date: A date and time value. Dates can be used to store the current date and time, or they can be used to represent a specific date and time in the past or future.

// Array
const arr = [1, 2, 3];

// Object
const obj = {
  name: "Vaibhav Gupta",
  age: 20,
};

// Function
const myFunction = function () {
  console.log("Hello, world!");
};

// RegExp
const myRegExp = /[a-z]/;

// Date
const myDate = new Date();
Enter fullscreen mode Exit fullscreen mode

How to add JavaScript to HTML Pages

There are following three ways in which users can add JavaScript to HTML pages.

  • Embedding code
  • Inline code
  • External file

Embedding Code: We can use the <script>.....</script> tag of the HTML to add javascript. We can also define JavaScript code in the

tag or tag because it entirely depends on the structure of the web page that we can use.

Inline Code: This method is used when we have to call a function in the HTML event attributes.
<button type = "submit" onclick = "console.log('Hello, World!')">Submit </button>

External file: We can also create a separate file for writing JavaScript code with the (.js) extension and later link it to our HTML document using the src attribute of the <script> tag.

<script src="index.js"></script>

JavaScript Comments

It is used to add information about the code user can easily understand the code.

There are two types of comments in JavaScript.

Single-line Comment: It is represented by double forward slashes (//).

//It is a single-line comment.

Multi-line Comment: It can be used to add single as well as multi-line comments.

It is represented by a forward slash with an asterisk then an asterisk with a forward slash.

/* It is a

multi-line comment */
Enter fullscreen mode Exit fullscreen mode

JavaScript Functions

Block of code designed to perform a particular task and executed when calls it.

function name(par1,par2){
//statements
}
Enter fullscreen mode Exit fullscreen mode

JS Objects

Objects are variables with more than 1 value.

const studentData = { name:"Vaibhav",roll_no:"UE215106",branch:"ECE"}
Enter fullscreen mode Exit fullscreen mode

Accessing Properties: objectName.propertyName or objectName["propertName"]

JS Strings

JavaScript strings are for storing and manipulating text. A JavaScript string is zero or more characters written inside quotes.

JavaScript strings can also contain escape characters. Escape characters are used to represent special characters in a string. For example, the escape character for the newline character is \n.

JavaScript strings can be manipulated using a variety of methods. Some of the most common methods are:

  • length(): Returns the length of the string.
  • charAt(): Returns the character at the specified index.
  • indexOf(): Returns the index of the first occurrence of the specified character or substring.
  • substring(): Returns a substring of the string.
  • concat(): Concatenates two or more strings.
  • split(): String can be converted to an array.
  • slice(start,end): Extracts a part of a string and returns extracted part.
  • replace(): Replace a specified value with another value in a string.
  • trim(): Removes white spaces from both sides of the string.
  • tolowerCase(): Converted to lowercase.
  • toupperCase(): Converted to uppercase.

JS Arrays

Collection of items that are related and they can be stored together into the same container or the same variable.

var arrName = A[n];

Array Methods:

length(): Returns the length of an array.

toString(): Converts an array to a string of array values.

includes(): Check whether any element is present in the array or not.

push(): Adds a new element to an array.

pop(): Removes the last element from an array.

concat(): Creates a new array by merging existing arrays.

JS Date

Date objects are created with the new Date() command.

Date Get Methods:

getFullYear(): Get year as a four-digit number (yyyy)

getMonth(): Get month as a number (0-11)

getDate(): Get day as a number (1-31)

getDay(): Get weekday as a number (0-6)

getHours(): Get hour (0-23)

getMinutes(): Get minute (0-59)

getSeconds(): Get second (0-59)

getMilliseconds(): Get millisecond (0-999)

getTime(): Get time (milliseconds since January 1, 1970)

Conditional Statements in JS

if-else statement:

if (condition){
//statements
}
else {
//statements
}
Enter fullscreen mode Exit fullscreen mode

switch statement:

switch(condition) {
  case x:
    // statements
    break;
  case y:
    // statements
    break;
  default:
    // statements
}
Enter fullscreen mode Exit fullscreen mode

JS Loops

JavaScript loops are used to iterate through a block of code a certain number of times. There are four types of loops in JavaScript:

For loop: The for loop is the most common type of loop in JavaScript. It is used to iterate through a block of code a fixed number of times.

While loop: The while loop is used to iterate through a block of code while a certain condition is true.

Do-while loop: The do-while loop is similar to the while loop, but the code block is executed at least once, even if the condition is false.

For-in loop: The for-in loop is used to iterate through the properties of an object.

//for loop
for(var i=0;i<n;i++){
//statements
}

//while loop
while(i<n){
//statements
i++;
}

//do-while loop
do{
//statements
i++;}
while(i<=n);

//for-in loop
for (variable in object) {
  // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

JS Operators

JavaScript operators are symbols that are used to perform operations on operands. There are many different types of operators in JavaScript, including:

Arithmetic operators: These operators are used to perform arithmetic operations on numbers. For example, the + operator is used to add two numbers together.

Assignment operators: These operators are used to assign values to variables. For example, the = operator is used to assigning the value 10 to the variable x.

Comparison operators: These operators are used to compare two values. For example, the == operator is used to compare two values to see if they are equal.

String operators: These operators are used to manipulate strings. For example, the + operator can be used to concatenate two strings together.

Logical operators: These operators are used to combine logical expressions. For example, the && operator is used to combine two logical expressions and return true if both expressions are true.

Bitwise operators: These operators are used to manipulate bits. For example, the & operator is used to perform a bitwise AND operation on two numbers.

Ternary operator: This operator is used to evaluate a conditional expression and return one of two values depending on the result. For example, the ?: operator can be used to check if a value is greater than 10 and return "greater" if it is or "less" if it is not.

Random Number Generator

Used to generate any random number.

var n = Math.random();//Generate a random number
n=Math.floor(n);//Rounds it down to nearest whole number.
Enter fullscreen mode Exit fullscreen mode

Project: Love Calculator

prompt("What is your name");
prompt("What is her name");
var loveScore = Math.random()*100;
loveScore = Math.floor(LoveScore);
alert("Your love score is " + loveScore);
if(loveScore === 100){
alert("Your love score is "+ loveScore +"%");}
Enter fullscreen mode Exit fullscreen mode

DOM (Document Object Model) Manipulation

Selecting Elements in JavaScript

Selecting elements in JavaScript DOM manipulation is the process of finding and accessing HTML elements in a web page. This can be done using a variety of methods, including:

  • getElementById(): This method returns a reference to the element with the specified ID attribute.
  • getElementsByTagName(): This method returns an array of all the elements with the specified tag name.
  • getElementsByClassName(): This method returns an array of all the elements with the specified class name.
  • querySelector(): This method returns a NodeList of the first element that matches the specified CSS selector.
  • querySelectorAll(): This method returns a NodeList of all the elements that match the specified CSS selector.
const element = document.getElementById("myElement");
const elements = document.getElementsByTagName("p");
const elements = document.getElementsByClassName("myClass");
const elements = document.querySelectorAll("p.myClass");
Enter fullscreen mode Exit fullscreen mode

JS HTML DOM Events

JavaScript HTML DOM events are events that occur in response to user interaction with a web page. These events can be used to trigger JavaScript code, which can then be used to change the behavior of the web page.

Some of the most common JavaScript HTML DOM events include:

  • Click: This event occurs when a user clicks on an element.
  • Mousedown: This event occurs when a user presses the mouse button down on an element.
  • Mouseup: This event occurs when a user releases the mouse button on an element.
  • Mouseover: This event occurs when a user's mouse hovers over an element.
  • Mouseout: This event occurs when a user's mouse moves away from an element.
  • Keydown: This event occurs when a user presses a key on their keyboard.
  • Keyup: This event occurs when a user releases a key on their keyboard.
  • Scroll: This event occurs when a user scrolls the page.
  • Load: This event occurs when a web page has finished loading.

To listen for an event, you can use the addEventListener() method. The addEventListener() method takes two arguments: the name of the event and a function that will be called when the event occurs.

const element = document.getElementById("myElement");
element.addEventListener("click", myFunction);
Enter fullscreen mode Exit fullscreen mode

JS HTML DOM Navigation

Some of the most common methods used for JavaScript HTML DOM navigation:

  • parentNode: This property returns the parent node of the current node.
  • childNodes: This property returns an array of all the child nodes of the current node.
  • firstChild: This property returns the first child node of the current node.
  • lastChild: This property returns the last child node of the current node.
  • nextSibling: This property returns the next sibling node of the current node.
  • previousSibling: This property returns the previous sibling node of the current node.
const element = document.getElementById("myElement");
const parent = element.parentNode;

const element = document.getElementById("myElement");
const children = element.childNodes;

const element = document.getElementById("myElement");
const child = element.firstChild;
Enter fullscreen mode Exit fullscreen mode

Manipulating and changing text content

style: Used to change the CSS property of an element.

document.querySelector("h1").style.fontsize ="10rem";
document.querySelector("h1").style.padding ="30";
document.querySelector("h1").style.visibility ="hidden";
Enter fullscreen mode Exit fullscreen mode

innerHTML: Select all the html code inside the query selector tag.

textContent: Only selects text content inside the tag.

document.querySelector("a").attributes;
document.querySelector("a").getAttribute("href");//Get Attribute value
document.querySelector("a").setAttribute("href","https://www.bing.com");//Set Attribute value
Enter fullscreen mode Exit fullscreen mode

Higher Order Functions and Passing functions as Argument

Higher Order Functions: Functions that can take other functions as inputs.

const element = document.getElementById("myElement");
element.addEventListener("click", myFunction);
function myFunction(){
alert("I got clicked")://statements
}
Enter fullscreen mode Exit fullscreen mode

JS Objects

Constructor Function:

function student(name,age,rollno,languages){
this.name=name;
this.age=age;
this.rollno=rollno;
this.languages=languages;
}
Enter fullscreen mode Exit fullscreen mode

Initialise Object:
var student1 = new student("Vaibhav",19,215106,["Hindi","English"]);
Calling Object:
student1.age();

Keyboard Event Listeners in JavaScript

Keyboard event listeners in JavaScript are used to respond to user input from the keyboard. There are three types of keyboard events:

  • keydown: This event is fired when a key is pressed down.
  • keypress: This event is fired when an alphabetic, numeric, or punctuation key is pressed down.
  • keyup: This event is fired when a key is released.
addEventListener("keypress",function(){
alert("Key was pressed"):
}
document.addEventListener("keypress",function(event){
console.log(event);//printing which event is happening now
console.log(event.key);//tells which key is pressed
}
Enter fullscreen mode Exit fullscreen mode

Play Sound in JavaScript

var audio = new Audio('audio_file.mp3');
audio.play();//Playing the audio
Enter fullscreen mode Exit fullscreen mode

OR

// Create an audio element
const audioElement = document.createElement("audio");

// Set the source of the audio element
audioElement.src = "my_sound.mp3";

// Set the volume of the audio element
audioElement.volume = 0.5;

// Play the audio element
audioElement.play();

// Add an event listener to the audio element
audioElement.addEventListener("ended", function() {
  // Do something when the audio element has finished playing
});
Enter fullscreen mode Exit fullscreen mode

JavaScript Animations

JavaScript animations allow you to have more control over the animation, such as timing, looping, and easing. To do this, you use the animate() method in JavaScript.

const element = document.querySelector(".my-element");

element.animate({
  height: 200,
  duration: 2000,
  timingFunction: "linear",
});
Enter fullscreen mode Exit fullscreen mode

Project: Making a Dynamic Digital Clock

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Digital Clock</title>
  </head>
  <body>
    <div>
      <script>
        setInterval(function showtime() {
          a = new Date();
          let time = a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds();
          let date = a.toLocaleDateString();

          document.getElementById("time").innerHTML = time + " " + date;
        }, 1000);
      </script>
      <h1>Digital Clock</h1>
      <br />
      <h2 id="time"></h2>
    </div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this blog, we have explored some of the key reasons why JavaScript is so popular. We have looked at its flexibility, its ease of use, its large community, and its ever-evolving nature.

JavaScript is a powerful and versatile language that is used in a wide variety of applications. It is the most popular programming language on Earth, and its popularity is only growing.

We have also discussed some of the challenges that JavaScript faces, such as its complexity and its inconsistent syntax. However, despite these challenges, JavaScript remains a valuable language for developers.

JavaScript is a valuable skill for any developer. If you are looking for a language that is flexible, easy to use and has a large community, then JavaScript is a great choice.

Overall, the future of JavaScript looks bright. It is a language that is well-positioned to continue to grow in popularity and importance in the years to come.

Before We End...

Thank you for reading!

I hope you learned something from this blog and if there is a problem whatsoever with the article, let me know in the comments.

If you found this blog helpful, please share and like it to help more people discover it.

Top comments (0)