Open In App

Getting Started with JavaScript

JavaScript is a lightweight, single-threaded, dynamically typed, interpreted programming language with object-oriented capabilities. Primarily JavaScript is used to add interactivity and dynamism to web pages. It breathes life into static HTML and CSS, enabling features like dynamic content updates, user interactions, and animations.

However, JavaScript's reach extends beyond web development. It's also employed in server-side development with frameworks like Node.js and for creating mobile applications through frameworks like React Native. In this article, we will go through the fundamentals of JavaScript.

Pre-requisites

Basics of JavaScript

Variables: Storing Information Like a Box

Imagine having boxes to hold different things. In JavaScript, variables act like these boxes, allowing you to store and manage information. A variable is a named container that holds a value, which can be text, numbers, or even collections of data. Declare variables using let, const, or var (though const and let are generally preferred for modern JavaScript):

Syntax:

let name = "Bob";
const age = 25; // Unchangeable value

let is the keyword that tells JavaScript you're declaring a variable. where the message is the name of that variable. = is the assign operator that tells JavaScript to assign the value "Bob" string or 25 to the variable.

Data Types

Just like boxes can hold different items, variables in JavaScript can store various data types. Understanding these types is crucial. Data types categorize the information a variable can hold.

Common types in JavaScript:

Operators: Performing Actions on Your Data

Think of operators as tools you use to manipulate the data inside your variables. JavaScript offers various operators for performing calculations, comparisons, and more. Operators allow you to perform operations on data.

Some basic operators in JavaScript:

Control Flow Statements and Loops

Control flow statements determine the execution flow of your code:

Loops are used to execute a block of code repeatedly until a certain condition is met. JavaScript offers several looping constructs:

Functions

Functions are reusable blocks of code that perform specific tasks. They can take input (arguments) and return output (values).

Arrow Functions: A concise syntax for defining functions, introduced in ES6 (ECMAScript 2015).

Arrays

Ordered collections of values, accessed using zero-based indexes. Useful for storing lists of items.

Objects

Complex data structures that store key-value pairs, allowing you to organize related data efficiently.

Comments

Comments are lines of text ignored by the interpreter and used to explain or document code.

Syntax:

// Single-line comment
/* Multi-line comment */

Hoisting

A JavaScript behaviour where function declarations are moved to the top of their scope (typically the script) before code execution. This means you can call a function before it's declared in the code. However, this is generally considered bad practice as it can lead to unexpected behaviour in modern JavaScript.

DOM Manipulation

JavaScript can interact with the Document Object Model (DOM), allowing you to dynamically modify the content and structure of your web pages. This opens doors for creating interactive elements, updating content based on user input, and building dynamic web applications.

Event Handling

JavaScript can listen for events like button clicks, mouse movements, and keyboard presses, enabling user interaction and responsiveness. By handling these events, you can trigger specific actions like updating content, displaying messages, or performing calculations based on user input.

Steps to Run the JavaScript Code

Here are two common ways to run JavaScript code:

Using JavaScript in a web project:

Using the browser console: Most web browsers come with a built-in console where you can directly execute JavaScript code. Open your browser's developer tools (usually by pressing F12) and look for the console tab. You can then type your JavaScript code and press Enter to see the output.

Creating an HTML file: You can create a simple HTML file with a <script> tag to embed your JavaScript code. The browser will interpret the code when the webpage loads.

Here's a basic example:

<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript Code</title>
</head>
<body>
<script>
let message = "Hello from my HTML file!";
console.log(message);
</script>
</body>
</html>

Save this code as an HTML file (e.g., index.html) and open it in your browser. You won't see any direct changes on the webpage, but you can access the console to see the output: "Hello from my HTML file!" or you can get the same result my adding external javascript to the script tag in HTML.

Using JavaScript outside the browser (Node.js)

Step 1: Node.js environment: If your project involves running JavaScript code outside a web browser, you can leverage Node.js. Node.js is a JavaScript runtime environment that allows you to execute JavaScript code on your computer.

Step 2: Create JavaScript files: Similar to web development, you'll create JavaScript files (.js extension) containing your code.

Step 3: Run JavaScript code: You can run JavaScript code using the Node.js command line or integrate it into your project using Node.js modules.

Example: Here's a simple JavaScript program that logs a message to the browser console:

Console.log("GeeksforGeeks");

Output: When you run this code in a browser's developer console or an appropriate JavaScript execution environment, it will display:

GeeksforGeeks

Advantages of Using JavaScript

How to use JavaScript in a Project

Using JavaScript in a project can vary depending on the type of project you're working on and your specific requirements. JavaScript's application depends on your project's environment. Here's a breakdown for the most common scenarios:

Using JavaScript in a Web Project:

Internal JavaScript:

Include the JavaScript code directly within your HTML file using the <script> tag. Place the <script> tag either inside the <head> section (for code to run before page load) or at the end of the <body> section (for code to run after the page loads).

<!DOCTYPE html>
<html>

<head>
    <title>Internal JavaScript Example</title>
    <script>
        function greet() {
            alert("Hello from Internal JavaScript! and Welcome To GFG");
        }
    </script>
</head>

<body>
    <button onclick="greet()">Click me</button>
</body>

</html>

Open the HTML file in a web browser. The embedded JavaScript code will be executed when the page loads or when the corresponding event (like a button click) occurs.

External JavaScript:

Create a new file with a .js extension (e.g., myscript.js). Write your JavaScript code within this file. Include a <script> tag within your HTML file, but this time with the "src" attribute specifying the path to your external JavaScript file.

<!DOCTYPE html>
<html>

<head>
    <title>External JavaScript Example</title>
    <script src="myscript.js"></script>
</head>

<body>
    <button onclick="greet()">Click me</button>
</body>

</html>
function greet() {
  alert("Hello from External JavaScript! and Welcome to GFG");
}

Open the HTML file in a web browser. The external JavaScript file will be loaded and executed when the page loads.

Using JavaScript with Node.js (Backend):

Download and install Node.js from the official website https://nodejs.org/en

Similar to external JavaScript for web, create a file with a .js extension (e.g., app.js). Write your JavaScript code in this file, but here you can leverage Node.js functionalities like file system access, server creation, database interactions, etc.

Open a terminal or command prompt and navigate to the directory containing your JavaScript file. Run the following command to execute the JavaScript code using Node.js:

node app.js

This will run the code within the Node.js environment, typically used for server-side operations.

However, here are some general steps to guide you through after integrating JavaScript into your project:

By following these steps, you can effectively integrate JavaScript into your project and leverage its capabilities to build interactive and dynamic web applications.

Article Tags :