JavaScript is a popular language used to make websites interactive and dynamic. It adds life to a website by making things move or change when you interact with them. Even if a website looks great, JavaScript helps make it functional and engaging.
Brendan Eich created JavaScript in 1995. At first, it was mainly used for making web pages more interactive. But now, it's used for both the front and back ends of websites. Big companies like Google and Facebook use it to build mobile apps, games, and even real-time chat apps.
Instead of diving deep into its history, let's focus on what JavaScript can do for us.
Table of Contents
1. What is the Use of JavaScript
2. What is difference between JavaScript and Java
3. JavaScript Execution with Browser
4. Setting up the environment to write JavaScript
5. JavaScript Variables
6. JavaScript Data Types
7. JavaScript Objects and Arrays
8. JavaScript If Else Statement
9. JavaScript For Loop
10. JavaScript Function
11. Interacting with HTML elements - (DOM and Events)
12. Using JavaScript for Front-End Development
13. Using JavaScript for Back-End Development
14. Conclusion
What is the Use of JavaScript
JavaScript makes web pages dynamic and interactive. It lets us control what happens when users do things like click, scroll, or type on a website. With JavaScript, we can add logic to change elements based on events or time.
While HTML and CSS help build the structure and style of a website, JavaScript brings it to life. Here are some example uses of JavaScript on web page:
- Showing or hiding elements when clicked
- Adding or removing elements at specific times
- Displaying quick messages
- Creating menu buttons like the hamburger menu
- Adding scrolling effects
- Sliding images
These are just some front-end uses. JavaScript is also used in the back-end of websites. It helps in tasks like fetching data from other sites, connecting to servers, handling database data, creating website paths, and loading dynamic content on a page.
Difference between Java and Javascript
It's common for beginners to think that Java and JavaScript are the same because of their similar names, but they're actually quite different. Here's a simple comparison to clear things up:
Java is used for building operating systems, Android apps, desktop apps, games, and data centers. It's a versatile language and one of the most popular ones out there. To run Java programs, you need to install a specific compiler on your computer. There are also frameworks in Java for building websites, though it's not as popular for web development as JavaScript.
On the other hand, JavaScript runs in web browsers and is mainly used for making websites interactive. You don't need to install anything special to run JavaScript; it works directly in your web browser.
So, even though their names sound alike, Java and JavaScript are as different as a car and a carpenter. They have different syntax, uses, and they're not related to each other in any way.
Now that we've cleared that up, let's move on to the main topic of today's session.
JavaScript Execution with Browser
All web browsers come with their own JavaScript engines built-in. These engines, like Chrome's V8 or Firefox's SpiderMonkey, understand and run JavaScript code on websites.
Let's see how we can run JavaScript in the Chrome browser:
1. Open the Chrome browser and go to any webpage.
2. Right-click on the page and select "Inspect", or you can also press Ctrl+Shift+I (Windows) or Command+Option+I (Mac) to open the Developer Tools.
3. In the Developer Tools window, click on the "Console" tab at the top.
4. You'll see a space where you can type JavaScript code.
Type `console.log("Hello World");` and then press Enter. You'll see the message "Hello World" displayed below.
Here's a quick explanation:
- `console.log()` is a JavaScript method used to print or display messages.
- Inside the parentheses `()`, we put what we want to display. In this case, "Hello World" is a string, so we put it inside double quotes.
Remember, this is just for learning how to execute JavaScript in the browser. In actual web development, we use JavaScript to add interactivity and functionality to websites, not just to print messages.
Similarly, You can copy and paste each line into the console and press Enter to see the result.
alert("Alert message");
prompt("Enter your name");
confirm("Please confirm");
These are some JavaScript methods to get input or show messages in the browser. But for building an entire website, we won't write JavaScript like this. We need to set up a proper environment for that.
Setting up the Environment to run JavaScript on Web Page
To use JavaScript on a webpage, you need to include it in HTML code. We assume you're at least a beginner with HTML. We can write JavaScript either directly in the HTML file or link to an external JavaScript file. Initially, to begin with JavaScript, we can use internal JavaScript. For bigger projects, you'll have bunch of external JS file linked with HTML code.
After setting up a new folder and opening it in VS Code, create an index.html file. We'll use internal JavaScript here, so no need for external files yet. You can write JavaScript between <script> and </script> tags in the HTML. The script tag can be added anywhere in HTML document but it's best to place the <script> tag just before the closing </body> tag.
Now, you can try out JavaScript methods like console.log()
, alert()
, and prompt()
inside these <script> tags. Open the index.html file in a browser to see the results. Anything printed with console.log() will appear in the browser's console, accessible through the inspect tool.
Whatever written after double-slash `//` is known as comments. Comments are used to add explanations or notes that are being ignored by the compiler.
Before diving into writing JavaScript, let's go over some basic concepts like data types, variables, arrays, objects, conditional statements, loops, and functions. These concepts are common across many programming languages, but their syntax are different. We'll explore these concepts with examples next.
Javascript Variables
JavaScript consists of programming statements that run sequentially from top to bottom. To store values like numbers and text, we use variables. A variable is declared using a specific keyword followed by a unique name and then assigned a value. This value can be letters, numbers, objects, or even functions.
Here's an example:
We declare a variable using the var keyword, give it a unique name, and assign the value "Anna Smith" to it. The semicolon ; at the end of the statement tells the browser or compiler that this line of code is complete.
JavaScript has three keywords for declaring variables:
- var (variable)
- let (block-scoped variable)
- const (constant)
Each keyword has a specific purpose, but for now, we'll focus on var.
Variable names, also known as identifiers, can be anything like x, y, z, name, work, job, etc. They are case-sensitive and can include letters, digits, underscores, and dollar signs, but must start with a letter.
The value assigned to a variable, like "Anna Smith", is called a string in programming. For numbers, we don't need quotes. Strings should be enclosed in single ' ' or double " " quotes.
Let's look at some examples:
var number = 18;
var myName = "Code Mafias";
let total = 54;
console.log(number);
console.log(myName);
console.log(total);
Open your HTML file in a browser, then check the browser's console to see the printed values.
This explanation simplifies the concept of JavaScript variables and provides a clearer understanding.
JavaScript Data Types
JavaScript variables can hold different types of values, this type of value is known as data types. We've already talked about strings, which is one of these data types. Here are some common data types:
- Number: Holds numeric values. Example:
var x = 5
- String: Holds text values. Example:
var myName = "Code Mafias"
- Boolean: Holds either true or false. Example:
var result = true
- Array: Holds a list of values. Example:
var list = [1, "name", "age", 5]
- Object: Holds key-value pairs. Example:
var person = {name: "Code Mafias"}
- Undefined: Variable declared but not assigned a value. Example:
var n;
- Not Defined: Variable does not exist.
These are the most common data types you'll encounter when writing JavaScript. Unlike some other programming languages, you don't need to declare variables with different keywords based on their data type in JavaScript. Any keyword can hold any type of data.
Understanding these basic data types is enough for beginners.
JavaScript Arrays and Objects
Arrays and objects allow you to store multiple related values in one variable.
Arrays
An array can hold multiple values, including numbers, strings, objects, and even other arrays. It uses square brackets `[]` to enclose its elements. Each element has an index starting from 0.
Here's an example of an array and how to access its elements:
var fruits = ["Mango", "Apple", "Banana", "Orange"];
// Accessing array elements
console.log(fruits[0]); // Mango
console.log(fruits[3]); // Orange
// Getting array length
console.log(fruits.length); // 4
This example shows the array syntax and how to access its values.
Objects
Objects store data as key-value pairs inside curly braces `{}`. The key is like a variable name, and the value can be any data type. Objects can contain properties (static data) and methods (functions).
Here's an example of an object and how to access its properties:
var employee = {
name: "Anna Smith",
designation: "Technology Head",
age: 24,
experienceYears: 3
}
// Accessing object properties
console.log(employee.name); // Anna Smith
console.log(employee.age); // 24
console.log(employee.experienceYears); // 3
// Getting object length
console.log(Object.keys(employee).length); // 4
This example shows the object syntax and how to access its values using keys.
Understanding arrays and objects is crucial as they are fundamental in JavaScript for storing and organizing data.
JavaScript If Else Statements
JavaScript If Else statements, also called as conditional statements. It allow you to execute different actions based on specific conditions. If Else condition is useful when you want your web page to respond differently based on different condition or user inputs.
There are four main types of conditional statements in JavaScript:
- if: Executes a block of code if a condition is true.
- else if: Checks another condition if the first one is false.
- else: Executes a block of code if all previous conditions are false.
- switch: Executes different actions based on different cases.
Refer below Image for better understanding:
Let's look at some examples to understand these better.
Using if-else
var age = 25;
if (age >= 18) {
alert("He can vote");
} else {
alert("He cannot vote");
}
// Expected outcome: "He can vote"
console.log(age >= 18); // true
In this example, the if block executes because age is greater than or equal to 18.
Using else if
var age = 22;
if (age < 10) {
alert("He is a kid");
} else if (age < 25) {
alert("He is a young adult");
} else {
alert("He is an adult");
}
// Expected outcome: "He is a young adult"
Here, the else if block executes because age is between 10 and 25.
You can add multiple else if statements to check more conditions. If none of the conditions are met, the else block will execute. When there is multiple cases, we can use the switch
statement. We will not talk about the switch case statement here as it will be a separate topic.
Understanding these conditional statements is fundamental in JavaScript for making your code more dynamic and responsive.
JavaScript For Loop
In JavaScript, a for loop allows you to execute a block of code repeatedly for a specified number of times. Every programming language has a concept of a loop.
Refer below Image for better understanding:
Let's look at some examples to understand how it works.
for (var i = 0; i < 10; i++) {
console.log("Hello World"); // Prints "Hello World" 10 times
}
In this example, the for loop starts with i at 0, checks if i is less than 10, and increments i by 1 after each iteration.
Now, let's loop through an array and display each item:
var languages = ["JavaScript", "Python", "Java", "C", "C++", "PHP"];
for (var n = 0; n < languages.length; n++) {
console.log(languages[n]);
}
Here, we use the for loop to log each programming language in the languages array.
JavaScript Functions
JavaScript function performs the assigned task when we call it. Just like a car has various functionalities such as engine, headlights, horns to do specific jobs, a JavaScript function does a particular task when you call it. You can create many functions in JavaScript to perform different tasks. Functions are used to avoid repetitive task
Refer below Image for better understanding:
A function takes inputs, known as parameters, and gives an output. Let's look at some examples:
// Function to add two numbers
function add(num1, num2) {
return num1 + num2;
}
// Calling the add function
console.log(add(54, 46)); // Outputs 100
In this example, we have a function add that takes two numbers as parameters and returns their sum. When we call add(54, 46)
, it returns 100.
You can also assign a function to a variable:
// Function to multiply two numbers
function multiplication(a, b) {
var result = a * b;
console.log(result);
return result;
}
// Assigning the function to a variable
var myFunction = multiplication;
// Calling the function and storing the result
var myFunctionResult = multiplication(6, 3); // Outputs 18
Here, we define a multiplication
function that multiplies two numbers. We assign the function to myFunction
without calling it. Now the variable myFunction
is also a function for multiplication. Later, we call the multiplication
function and store its result in myFunctionResult
. So I hope you can understand the difference between assigning a function to a variable and assigning an output of a function to a variable.
This was all about the basics of JavaScript. But you may not find it excited as we're not doing anything magical here. So, it's time to implement this logic and see how we can interact with HTML elements and manipulate them.
Interacting with HTML elements - (DOM and Events)
JavaScript also used to interact with HTML elements using the Document Object Model (DOM). DOM is a kind of tree structure of all your webpage's elements. With JavaScript, you can access, modify, or delete all these elements of a webpage.
Your webpage's DOM may look like this:
Let's say you have a simple webpage with an input box and a button. You want a functionality to display the text within the input box when you click the button. Here's how you can do it:
<body>
<h1>JavaScript Tutorial</h1>
<input type="text" id="myInput">
<button id="button">Show Result</button>
<p id="result"></p>
</body>
In the JavaScript code, we'll grab these elements by their IDs and add an event listener to the button. When the button is clicked, it will update the paragraph with the input value.
<script>
var input = document.getElementById("myInput");
var button = document.getElementById("button");
var result = document.getElementById("result");
button.addEventListener("click", function () {
result.innerHTML = input.value;
});
</script>
Now, when you fill in the input box and click the button, the text will appear in the paragraph. We used getElementById to select elements by their IDs and addEventListener to listen for a click event on the button.
Commonly used Events:
- click: When an element is clicked
- scroll: When a page is scrolled
- resize: When the window is resized
- keyup: When a key is pressed in an input field
- load: When the page finishes loading
- mouseover: When the mouse is over an element
- mouseout: When the mouse leaves an element
This is just a basic introduction to DOM and events in JavaScript. You can also change styles, select elements by class or tag name, and much more with JavaScript and DOM manipulation. For more advanced features, libraries like jQuery can be handy.
Using JavaScript for Front-End Development
As of now, we looked at common functionalities of JavaScript as a programming language. Now let's talk about how we can use JavaScript as the front end.
Basically, Front End is what you see on the screen. The layout, colours, user experiences and interfaces, fonts, etc. Front End is also called the client side of a website where user come and interact with the website. JavaScript has a bunch of Frameworks and Libraries to build the Front End of a Website. Framework and Libraries are set of code built using JavaScript by a contributor to help developers build the website in a standard way.
Let's take a look at the list of a few of the popular front-end frameworks and libraries:
- React Js
- Angular Js
- Svelte
- jQuery
- Vue Js
These are a few of the popular front-end frameworks and libraries built using JavaScript. You can use any of these for free to build more complex and interactive web pages and applications.
Using JavaScript for Back-End Development
Initially, When Yahoo was a popular, JavaScript was limited to front end interactive. But now it has extended its use and become very popular to build the back end of a website. Back End development means creating and setting up a server of a website. Whatever requests user send, back end respond to them. Back End is also known as the Server Side of the website.
So far, we are executing JavaScript through browser. But, in order to build the back end of a website, we need use outside of browser environment. To achieve that, we need to download and install Node Js which is a JavaScript runtime built on top of Chrome's V8 Engine. You can download it on your local machine and execute JavaScript code outside of browser.
Similar to front end, JavaScript also has several technologies to build the back end of a website in a standard way.
Here are a few of them:
- Node Js (Runtime Environment)
- Express Js (Web Framework for Node Js)
- MongoDB (Database)
- Jest (Testing Library)
These technologies make it easier to build scalable back-end systems using JavaScript.
Conclusion
Today, we've covered the basics of JavaScript, giving you a solid starting point if you're new to this language. While we haven't gone into every detail, this foundation should help you get started with JavaScript and build your understanding over time.
If you've any query related to programming or web developlment, feel free to add them into the question box give below. We'll attempt to provide you with the solution.